aes_gcm.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include "common/error.hpp"
  5. namespace smartbotic::crypto {
  6. // AES-256-GCM encryption result
  7. struct EncryptedData {
  8. std::vector<uint8_t> ciphertext;
  9. std::vector<uint8_t> iv; // 12 bytes
  10. std::vector<uint8_t> auth_tag; // 16 bytes
  11. // Serialize to base64 encoded JSON for storage
  12. std::string toJson() const;
  13. static common::Result<EncryptedData> fromJson(const std::string& json);
  14. // Convenience for single-field storage
  15. std::string toBase64() const;
  16. static common::Result<EncryptedData> fromBase64(const std::string& encoded);
  17. };
  18. // AES-256-GCM encryption configuration
  19. struct AesGcmConfig {
  20. std::string master_key; // Raw key or passphrase
  21. int pbkdf2_iterations = 100000; // Key derivation iterations
  22. bool use_key_derivation = true; // If false, master_key is used directly
  23. };
  24. // AES-256-GCM authenticated encryption
  25. class AesGcm {
  26. public:
  27. explicit AesGcm(const AesGcmConfig& config);
  28. ~AesGcm() = default;
  29. // Encrypt plaintext
  30. common::Result<EncryptedData> encrypt(const std::string& plaintext);
  31. common::Result<EncryptedData> encrypt(const std::vector<uint8_t>& plaintext);
  32. // Decrypt ciphertext
  33. common::Result<std::string> decrypt(const EncryptedData& data);
  34. common::Result<std::vector<uint8_t>> decryptBytes(const EncryptedData& data);
  35. // Convenience methods for string-based storage
  36. common::Result<std::string> encryptToBase64(const std::string& plaintext);
  37. common::Result<std::string> decryptFromBase64(const std::string& encoded);
  38. // Generate random bytes for IV
  39. static std::vector<uint8_t> generateRandomIv();
  40. // Generate random key (32 bytes for AES-256)
  41. static std::string generateRandomKey();
  42. private:
  43. // Derive encryption key from master key using PBKDF2
  44. std::vector<uint8_t> deriveKey(const std::vector<uint8_t>& salt);
  45. AesGcmConfig config_;
  46. std::vector<uint8_t> derived_key_; // Cached derived key (if not using salt per encryption)
  47. };
  48. // Base64 encoding/decoding utilities
  49. namespace base64 {
  50. std::string encode(const std::vector<uint8_t>& data);
  51. std::string encode(const uint8_t* data, size_t len);
  52. common::Result<std::vector<uint8_t>> decode(const std::string& encoded);
  53. }
  54. } // namespace smartbotic::crypto