101 lines
2.5 KiB
C++
101 lines
2.5 KiB
C++
/*
|
|
* Copyright (c) 2014, Airbitz, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* See the LICENSE file for more information.
|
|
*/
|
|
|
|
#include "native-crypto.h"
|
|
|
|
extern "C"
|
|
{
|
|
#include "crypto_scrypt.h"
|
|
#include "base64.h"
|
|
}
|
|
|
|
#include <cmath>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <random>
|
|
#include <sstream>
|
|
|
|
using namespace std;
|
|
|
|
int fast_crypto_scrypt(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt, size_t saltlen,
|
|
uint64_t N,
|
|
uint32_t r, uint32_t p, uint8_t *buf, size_t buflen)
|
|
{
|
|
return crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen);
|
|
}
|
|
|
|
vector<uint8_t> hexToBytes(const string &hex)
|
|
{
|
|
vector<uint8_t> bytes;
|
|
for (unsigned int i = 0; i < hex.length(); i += 2)
|
|
{
|
|
string byteString = hex.substr(i, 2);
|
|
uint8_t byte = (uint8_t)strtol(byteString.c_str(), nullptr, 16);
|
|
printf("%hhu ", byte);
|
|
bytes.push_back(byte);
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
int crypto_scrypt_base64(std::string *password, std::string *salt, uint64_t N,
|
|
uint32_t r, uint32_t p, size_t size, std::string *value)
|
|
{
|
|
uint8_t *passwordBuf = (uint8_t *)password->c_str();
|
|
size_t passLen = password->length();
|
|
|
|
std::vector<uint8_t> bytes = hexToBytes(salt->c_str());
|
|
size_t saltBufLen = bytes.size();
|
|
uint8_t *saltBuf = bytes.data();
|
|
|
|
uint8_t *buffer = (uint8_t *)malloc(sizeof(char) * size);
|
|
|
|
int result = crypto_scrypt((uint8_t *)passwordBuf, passLen, (uint8_t *)saltBuf,
|
|
saltBufLen, N, r, p, buffer, size);
|
|
int b64encSize = Base64encode_len(size);
|
|
|
|
char *szB64Encoded = (char *)malloc(sizeof(char) * b64encSize);
|
|
Base64encode(szB64Encoded, (const char *)buffer, size);
|
|
value->assign(szB64Encoded);
|
|
free(buffer);
|
|
free(szB64Encoded);
|
|
return result;
|
|
}
|
|
|
|
void get_uuid(char *buffer)
|
|
{
|
|
static std::random_device dev;
|
|
static std::mt19937 rng(dev());
|
|
|
|
std::uniform_int_distribution<int> dist(0, 15);
|
|
|
|
const char *v = "0123456789abcdef";
|
|
const bool dash[] = {false, false, false, false, true, false, true, false, true, false, true,
|
|
false, false, false, false, false};
|
|
|
|
std::stringstream res;
|
|
for (bool i : dash)
|
|
{
|
|
if (i)
|
|
res << "-";
|
|
res << v[dist(rng)];
|
|
res << v[dist(rng)];
|
|
}
|
|
res >> buffer;
|
|
}
|
|
|
|
void uuid_v4(char *buffer)
|
|
{
|
|
int rc = uuid_v4_gen(buffer);
|
|
if (rc == 1)
|
|
{
|
|
}
|
|
else
|
|
{
|
|
get_uuid(buffer);
|
|
}
|
|
}
|