Crypto.h 2.4 KB

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