123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- #include <stdio.h>
- #include <string>
- #include <memory>
- using std::unique_ptr;
- #include <openssl/bn.h>
- #include <openssl/rsa.h>
- #include <openssl/sha.h>
- using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
- using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
- uint32_t generate_rsa_key(std::string& priv_key_str, std::string& pub_key_str)
- {
- int rc;
- RSA_ptr rsa(RSA_new(), ::RSA_free);
- BN_ptr bn(BN_new(), ::BN_free);
- rc = BN_set_word(bn.get(), 3);
- if(rc != 1)
- return 0x1;
- rc = RSA_generate_key_ex(rsa.get(), 3072, bn.get(), NULL);
- if(rc != 1)
- return 0x2;
- printf("Generated key\n"); fflush(stdout);
- /* int pub_key_der_encoded_len, priv_key_der_encoded_len;
- unsigned char *pub_key_der, priv_key_der;
- pub_key_der = NULL;
- pub_key_der_encoded_len = i2d_RSAPublicKey(rsa.get(), (unsigned char**) &pub_key_der);
- if (pub_key_der_encoded_len < 0)
- return 0x3;
- priv_key_der = NULL;
- priv_key_der_encoded_len = i2d_RSAPrivateKey(rsa.get(), (unsigned char**) &priv_key_der);
- if (priv_key_der_encoded_len < 0)
- return 0x4;
- printf("Done\n"); fflush(stdout);
- // priv_key_str=std::string(priv_key_der, priv_key_der_encoded_len); //, priv_key_der);
- // pub_key_str=std::string(pub_key_der, pub_key_der_encoded_len);
- */
- const BIGNUM* n_internal_bigendian_struct;
- RSA_get0_key(rsa.get(), &n_internal_bigendian_struct, NULL, NULL);
- BIGNUM* n_bigendian_struct = BN_dup(n_internal_bigendian_struct);
- uint32_t count;
- int n_bignum_length=BN_num_bytes(n_bigendian_struct);
- unsigned char *n_bigendian = (unsigned char*) malloc(n_bignum_length);
- int length_bignum_le = BN_bn2bin(n_bigendian_struct, n_bigendian);
- unsigned char* n_littleendian = (unsigned char*) malloc(length_bignum_le);
- for(count=0; count<length_bignum_le; count++)
- n_littleendian[count] = n_bigendian[length_bignum_le-count-1];
- unsigned char hash[SHA256_DIGEST_LENGTH];
- SHA256_CTX sha256;
- SHA256_Init(&sha256);
- SHA256_Update(&sha256, n_littleendian, length_bignum_le);
- SHA256_Final(hash, &sha256);
- // TODO: Return hash of the public key for now
- // TODO: Print public key
- // TODO: Use EVP funs - https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestInit.html
- free(n_bigendian); free(n_littleendian);
- return 0; //length_bignum_le;
- }
|