Crypto.h 2.4 KB

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