From f0e656e719107251cce4657502d30d27623d7f90 Mon Sep 17 00:00:00 2001 From: Prasenjit Kumar Shaw Date: Sat, 6 Jul 2019 19:52:44 +0530 Subject: [PATCH] Add methods for generating RSA Key Pair in synccrypto module --- src/lib/sync/synccrypto.cpp | 49 +++++++++++++++++++++++++++++++++++++ src/lib/sync/synccrypto.h | 8 ++++++ 2 files changed, 57 insertions(+) diff --git a/src/lib/sync/synccrypto.cpp b/src/lib/sync/synccrypto.cpp index d3f45b0d1..4a1169ebd 100644 --- a/src/lib/sync/synccrypto.cpp +++ b/src/lib/sync/synccrypto.cpp @@ -20,10 +20,34 @@ #include #include #include +#include +#include #include #include +#include + +/* This function is required for Nettle's RSA support. + * We are not using random_ctx, instead we are using C++11's 's + * Merseinne Twister. + */ +void generateRandomBytes(void* randomCtx, size_t numBytes, u_char* out) +{ + Q_UNUSED(randomCtx); + + std::random_device device; + std::mt19937 generator(device()); + + // Generate a uniform int distribution in range of 0 to 255, that is 8-bit range + std::uniform_int_distribution distribution(0, 255); + + for (size_t i = 0; i < numBytes; ++i) { + out[i] = (u_char)distribution(generator); + } +} + + u_char *syncCryptoHkdf(QByteArray *in, QByteArray *info, size_t out_len) { hmac_sha256_ctx *ctx = new hmac_sha256_ctx; @@ -103,3 +127,28 @@ void deriveKeyFetchToken(QByteArray *keyFetchToken, QByteArray *tokenId, QByteAr temp2->remove(0, len); respXORKey->append(*temp2); } + +RSAKeyPair *generateRSAKeyPair() +{ + RSAKeyPair *keyPair = new RSAKeyPair(); + rsa_public_key publicKey; + rsa_private_key privateKey; + + rsa_public_key_init(&publicKey); + rsa_private_key_init(&privateKey); + + // Set public key exponent to a small Fermat prime number + mpz_set_ui(publicKey.e, 65537); + + // Using key size 2048 for security + int success = rsa_generate_keypair(&publicKey, &privateKey, + NULL, generateRandomBytes, + NULL, NULL, 2048, 0); + + Q_ASSERT(success); + + keyPair->m_publicKey = publicKey; + keyPair->m_privateKey = privateKey; + + return keyPair; +} diff --git a/src/lib/sync/synccrypto.h b/src/lib/sync/synccrypto.h index ce5f78a22..932986854 100644 --- a/src/lib/sync/synccrypto.h +++ b/src/lib/sync/synccrypto.h @@ -19,10 +19,18 @@ #include #include +#include #define SHA256_DIGEST_SIZE 32 +struct RSAKeyPair { + rsa_public_key m_publicKey; + rsa_private_key m_privateKey; +}; + +void generateRandomBytes(void *randomCtx, size_t numBytes, u_char *out); u_char *syncCryptoHkdf(QByteArray *in, QByteArray *info, size_t out_len); void syncCryptoKW(QByteArray *kw, QString name); void deriveSessionToken(QByteArray *sessionToken, QByteArray *tokenId, QByteArray *reqHMACKey, QByteArray *reqKey); void deriveKeyFetchToken(QByteArray *keyFetchToken, QByteArray *tokenId, QByteArray *reqHMACKey, QByteArray *respHMACKey, QByteArray *respXORKey); +RSAKeyPair *generateRSAKeyPair();