Crypto.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef BELL_CRYPTO_H
  2. #define BELL_CRYPTO_H
  3. #include <string> // for string
  4. #include <vector> // for vector
  5. #include <mbedtls/aes.h> // for mbedtls_aes_context
  6. #include <mbedtls/md.h> // for mbedtls_md_context_t
  7. #include <stddef.h> // for size_t
  8. #include <stdint.h> // for uint8_t
  9. #define DH_KEY_SIZE 96
  10. const static unsigned char DHPrime[] = {
  11. /* Well-known Group 1, 768-bit prime */
  12. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2,
  13. 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1,
  14. 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6,
  15. 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd,
  16. 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
  17. 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45,
  18. 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9,
  19. 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
  20. static unsigned char DHGenerator[1] = {2};
  21. class CryptoMbedTLS {
  22. private:
  23. mbedtls_md_context_t sha1Context;
  24. mbedtls_aes_context aesCtx;
  25. bool aesCtxInitialized = false;
  26. public:
  27. CryptoMbedTLS();
  28. ~CryptoMbedTLS();
  29. // Base64
  30. std::vector<uint8_t> base64Decode(const std::string& data);
  31. std::string base64Encode(const std::vector<uint8_t>& data);
  32. // Sha1
  33. void sha1Init();
  34. void sha1Update(const std::string& s);
  35. void sha1Update(const std::vector<uint8_t>& vec);
  36. std::string sha1Final();
  37. std::vector<uint8_t> sha1FinalBytes();
  38. // HMAC SHA1
  39. std::vector<uint8_t> sha1HMAC(const std::vector<uint8_t>& inputKey,
  40. const std::vector<uint8_t>& message);
  41. // AES CTR
  42. void aesCTRXcrypt(const std::vector<uint8_t>& key, std::vector<uint8_t>& iv,
  43. uint8_t* data, size_t nbytes);
  44. // AES ECB
  45. void aesECBdecrypt(const std::vector<uint8_t>& key,
  46. std::vector<uint8_t>& data);
  47. // Diffie Hellman
  48. std::vector<uint8_t> publicKey;
  49. std::vector<uint8_t> privateKey;
  50. void dhInit();
  51. std::vector<uint8_t> dhCalculateShared(const std::vector<uint8_t>& remoteKey);
  52. // PBKDF2
  53. std::vector<uint8_t> pbkdf2HmacSha1(const std::vector<uint8_t>& password,
  54. const std::vector<uint8_t>& salt,
  55. int iterations, int digestSize);
  56. // Random stuff
  57. std::vector<uint8_t> generateVectorWithRandomData(size_t length);
  58. };
  59. #define Crypto CryptoMbedTLS
  60. #endif