Crypto.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #include "Crypto.h"
  2. #include <mbedtls/base64.h> // for mbedtls_base64_encode, mbedtls_base64_...
  3. #include <mbedtls/bignum.h> // for mbedtls_mpi_free, mbedtls_mpi_init
  4. #include <mbedtls/ctr_drbg.h> // for mbedtls_ctr_drbg_free, mbedtls_ctr_drb...
  5. #include <mbedtls/entropy.h> // for mbedtls_entropy_free, mbedtls_entropy_...
  6. #include <mbedtls/pkcs5.h> // for mbedtls_pkcs5_pbkdf2_hmac
  7. #include <cstdint> // for uint8_t
  8. #include <stdexcept> // for runtime_error
  9. extern "C" {
  10. #include "aes.h" // for AES_ECB_decrypt, AES_init_ctx, AES_ctx
  11. }
  12. CryptoMbedTLS::CryptoMbedTLS() {}
  13. CryptoMbedTLS::~CryptoMbedTLS() {
  14. if (aesCtxInitialized) {
  15. mbedtls_aes_free(&aesCtx);
  16. }
  17. }
  18. std::vector<uint8_t> CryptoMbedTLS::base64Decode(const std::string& data) {
  19. // Calculate max decode length
  20. size_t requiredSize;
  21. mbedtls_base64_encode(nullptr, 0, &requiredSize, (unsigned char*)data.c_str(),
  22. data.size());
  23. std::vector<uint8_t> output(requiredSize);
  24. size_t outputLen = 0;
  25. mbedtls_base64_decode(output.data(), requiredSize, &outputLen,
  26. (unsigned char*)data.c_str(), data.size());
  27. return std::vector<uint8_t>(output.begin(), output.begin() + outputLen);
  28. }
  29. std::string CryptoMbedTLS::base64Encode(const std::vector<uint8_t>& data) {
  30. // Calculate max output length
  31. size_t requiredSize;
  32. mbedtls_base64_encode(nullptr, 0, &requiredSize, data.data(), data.size());
  33. std::vector<uint8_t> output(requiredSize);
  34. size_t outputLen = 0;
  35. mbedtls_base64_encode(output.data(), requiredSize, &outputLen, data.data(),
  36. data.size());
  37. return std::string(output.begin(), output.begin() + outputLen);
  38. }
  39. // Sha1
  40. void CryptoMbedTLS::sha1Init() {
  41. // Init mbedtls md context, pick sha1
  42. mbedtls_md_init(&sha1Context);
  43. mbedtls_md_setup(&sha1Context, mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), 1);
  44. mbedtls_md_starts(&sha1Context);
  45. }
  46. void CryptoMbedTLS::sha1Update(const std::string& s) {
  47. sha1Update(std::vector<uint8_t>(s.begin(), s.end()));
  48. }
  49. void CryptoMbedTLS::sha1Update(const std::vector<uint8_t>& vec) {
  50. mbedtls_md_update(&sha1Context, vec.data(), vec.size());
  51. }
  52. std::vector<uint8_t> CryptoMbedTLS::sha1FinalBytes() {
  53. std::vector<uint8_t> digest(20); // SHA1 digest size
  54. mbedtls_md_finish(&sha1Context, digest.data());
  55. mbedtls_md_free(&sha1Context);
  56. return digest;
  57. }
  58. std::string CryptoMbedTLS::sha1Final() {
  59. auto digest = sha1FinalBytes();
  60. return std::string(digest.begin(), digest.end());
  61. }
  62. // HMAC SHA1
  63. std::vector<uint8_t> CryptoMbedTLS::sha1HMAC(
  64. const std::vector<uint8_t>& inputKey, const std::vector<uint8_t>& message) {
  65. std::vector<uint8_t> digest(20); // SHA1 digest size
  66. sha1Init();
  67. mbedtls_md_hmac_starts(&sha1Context, inputKey.data(), inputKey.size());
  68. mbedtls_md_hmac_update(&sha1Context, message.data(), message.size());
  69. mbedtls_md_hmac_finish(&sha1Context, digest.data());
  70. mbedtls_md_free(&sha1Context);
  71. return digest;
  72. }
  73. // AES CTR
  74. void CryptoMbedTLS::aesCTRXcrypt(const std::vector<uint8_t>& key,
  75. std::vector<uint8_t>& iv, uint8_t* buffer,
  76. size_t nbytes) {
  77. if (!aesCtxInitialized) {
  78. mbedtls_aes_init(&aesCtx);
  79. aesCtxInitialized = true;
  80. }
  81. // needed for internal cache
  82. size_t off = 0;
  83. unsigned char streamBlock[16] = {0};
  84. // set IV
  85. if (mbedtls_aes_setkey_enc(&aesCtx, key.data(), key.size() * 8) != 0) {
  86. throw std::runtime_error("Failed to set AES key");
  87. }
  88. // Perform decrypt
  89. if (mbedtls_aes_crypt_ctr(&aesCtx, nbytes, &off, iv.data(), streamBlock,
  90. buffer, buffer) != 0) {
  91. throw std::runtime_error("Failed to decrypt");
  92. }
  93. }
  94. void CryptoMbedTLS::aesECBdecrypt(const std::vector<uint8_t>& key,
  95. std::vector<uint8_t>& data) {
  96. struct AES_ctx aesCtr;
  97. AES_init_ctx(&aesCtr, key.data());
  98. for (unsigned int x = 0; x < data.size() / 16; x++) {
  99. AES_ECB_decrypt(&aesCtr, data.data() + (x * 16));
  100. }
  101. }
  102. // PBKDF2
  103. std::vector<uint8_t> CryptoMbedTLS::pbkdf2HmacSha1(
  104. const std::vector<uint8_t>& password, const std::vector<uint8_t>& salt,
  105. int iterations, int digestSize) {
  106. auto digest = std::vector<uint8_t>(digestSize);
  107. // Init sha context
  108. sha1Init();
  109. mbedtls_pkcs5_pbkdf2_hmac(&sha1Context, password.data(), password.size(),
  110. salt.data(), salt.size(), iterations, digestSize,
  111. digest.data());
  112. // Free sha context
  113. mbedtls_md_free(&sha1Context);
  114. return digest;
  115. }
  116. void CryptoMbedTLS::dhInit() {
  117. privateKey = generateVectorWithRandomData(DH_KEY_SIZE);
  118. // initialize big num
  119. mbedtls_mpi prime, generator, res, privKey;
  120. mbedtls_mpi_init(&prime);
  121. mbedtls_mpi_init(&generator);
  122. mbedtls_mpi_init(&privKey);
  123. mbedtls_mpi_init(&res);
  124. // Read bin into big num mpi
  125. mbedtls_mpi_read_binary(&prime, DHPrime, sizeof(DHPrime));
  126. mbedtls_mpi_read_binary(&generator, DHGenerator, sizeof(DHGenerator));
  127. mbedtls_mpi_read_binary(&privKey, privateKey.data(), DH_KEY_SIZE);
  128. // perform diffie hellman G^X mod P
  129. mbedtls_mpi_exp_mod(&res, &generator, &privKey, &prime, NULL);
  130. // Write generated public key to vector
  131. this->publicKey = std::vector<uint8_t>(DH_KEY_SIZE);
  132. mbedtls_mpi_write_binary(&res, publicKey.data(), DH_KEY_SIZE);
  133. // Release memory
  134. mbedtls_mpi_free(&prime);
  135. mbedtls_mpi_free(&generator);
  136. mbedtls_mpi_free(&privKey);
  137. mbedtls_mpi_free(&res);
  138. }
  139. std::vector<uint8_t> CryptoMbedTLS::dhCalculateShared(
  140. const std::vector<uint8_t>& remoteKey) {
  141. // initialize big num
  142. mbedtls_mpi prime, remKey, res, privKey;
  143. mbedtls_mpi_init(&prime);
  144. mbedtls_mpi_init(&remKey);
  145. mbedtls_mpi_init(&privKey);
  146. mbedtls_mpi_init(&res);
  147. // Read bin into big num mpi
  148. mbedtls_mpi_read_binary(&prime, DHPrime, sizeof(DHPrime));
  149. mbedtls_mpi_read_binary(&remKey, remoteKey.data(), remoteKey.size());
  150. mbedtls_mpi_read_binary(&privKey, privateKey.data(), DH_KEY_SIZE);
  151. // perform diffie hellman (G^Y)^X mod P (for shared secret)
  152. mbedtls_mpi_exp_mod(&res, &remKey, &privKey, &prime, NULL);
  153. auto sharedKey = std::vector<uint8_t>(DH_KEY_SIZE);
  154. mbedtls_mpi_write_binary(&res, sharedKey.data(), DH_KEY_SIZE);
  155. // Release memory
  156. mbedtls_mpi_free(&prime);
  157. mbedtls_mpi_free(&remKey);
  158. mbedtls_mpi_free(&privKey);
  159. mbedtls_mpi_free(&res);
  160. return sharedKey;
  161. }
  162. // Random stuff
  163. std::vector<uint8_t> CryptoMbedTLS::generateVectorWithRandomData(
  164. size_t length) {
  165. std::vector<uint8_t> randomVector(length);
  166. mbedtls_entropy_context entropy;
  167. mbedtls_ctr_drbg_context ctrDrbg;
  168. // Personification string
  169. const char* pers = "cspotGen";
  170. // init entropy and random num generator
  171. mbedtls_entropy_init(&entropy);
  172. mbedtls_ctr_drbg_init(&ctrDrbg);
  173. // Seed the generator
  174. mbedtls_ctr_drbg_seed(&ctrDrbg, mbedtls_entropy_func, &entropy,
  175. (const unsigned char*)pers, 7);
  176. // Generate random bytes
  177. mbedtls_ctr_drbg_random(&ctrDrbg, randomVector.data(), length);
  178. // Release memory
  179. mbedtls_entropy_free(&entropy);
  180. mbedtls_ctr_drbg_free(&ctrDrbg);
  181. return randomVector;
  182. }