crypto.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <stdio.h>
  2. #include <string>
  3. #include <memory>
  4. using std::unique_ptr;
  5. #include <openssl/bn.h>
  6. #include <openssl/rsa.h>
  7. #include <openssl/sha.h>
  8. using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
  9. using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
  10. uint32_t generate_rsa_key(std::string& priv_key_str, std::string& pub_key_str)
  11. {
  12. int rc;
  13. RSA_ptr rsa(RSA_new(), ::RSA_free);
  14. BN_ptr bn(BN_new(), ::BN_free);
  15. rc = BN_set_word(bn.get(), 3);
  16. if(rc != 1)
  17. return 0x1;
  18. rc = RSA_generate_key_ex(rsa.get(), 3072, bn.get(), NULL);
  19. if(rc != 1)
  20. return 0x2;
  21. printf("Generated key\n"); fflush(stdout);
  22. /* int pub_key_der_encoded_len, priv_key_der_encoded_len;
  23. unsigned char *pub_key_der, priv_key_der;
  24. pub_key_der = NULL;
  25. pub_key_der_encoded_len = i2d_RSAPublicKey(rsa.get(), (unsigned char**) &pub_key_der);
  26. if (pub_key_der_encoded_len < 0)
  27. return 0x3;
  28. priv_key_der = NULL;
  29. priv_key_der_encoded_len = i2d_RSAPrivateKey(rsa.get(), (unsigned char**) &priv_key_der);
  30. if (priv_key_der_encoded_len < 0)
  31. return 0x4;
  32. printf("Done\n"); fflush(stdout);
  33. // priv_key_str=std::string(priv_key_der, priv_key_der_encoded_len); //, priv_key_der);
  34. // pub_key_str=std::string(pub_key_der, pub_key_der_encoded_len);
  35. */
  36. const BIGNUM* n_internal_bigendian_struct;
  37. RSA_get0_key(rsa.get(), &n_internal_bigendian_struct, NULL, NULL);
  38. BIGNUM* n_bigendian_struct = BN_dup(n_internal_bigendian_struct);
  39. uint32_t count;
  40. int n_bignum_length=BN_num_bytes(n_bigendian_struct);
  41. unsigned char *n_bigendian = (unsigned char*) malloc(n_bignum_length);
  42. int length_bignum_le = BN_bn2bin(n_bigendian_struct, n_bigendian);
  43. unsigned char* n_littleendian = (unsigned char*) malloc(length_bignum_le);
  44. for(count=0; count<length_bignum_le; count++)
  45. n_littleendian[count] = n_bigendian[length_bignum_le-count-1];
  46. unsigned char hash[SHA256_DIGEST_LENGTH];
  47. SHA256_CTX sha256;
  48. SHA256_Init(&sha256);
  49. SHA256_Update(&sha256, n_littleendian, length_bignum_le);
  50. SHA256_Final(hash, &sha256);
  51. // TODO: Return hash of the public key for now
  52. // TODO: Print public key
  53. // TODO: Use EVP funs - https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestInit.html
  54. free(n_bigendian); free(n_littleendian);
  55. return 0; //length_bignum_le;
  56. }