| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- #pragma once
- #include <string>
- #include <vector>
- #include "common/error.hpp"
- namespace smartbotic::crypto {
- // AES-256-GCM encryption result
- struct EncryptedData {
- std::vector<uint8_t> ciphertext;
- std::vector<uint8_t> iv; // 12 bytes
- std::vector<uint8_t> auth_tag; // 16 bytes
- // Serialize to base64 encoded JSON for storage
- std::string toJson() const;
- static common::Result<EncryptedData> fromJson(const std::string& json);
- // Convenience for single-field storage
- std::string toBase64() const;
- static common::Result<EncryptedData> fromBase64(const std::string& encoded);
- };
- // AES-256-GCM encryption configuration
- struct AesGcmConfig {
- std::string master_key; // Raw key or passphrase
- int pbkdf2_iterations = 100000; // Key derivation iterations
- bool use_key_derivation = true; // If false, master_key is used directly
- };
- // AES-256-GCM authenticated encryption
- class AesGcm {
- public:
- explicit AesGcm(const AesGcmConfig& config);
- ~AesGcm() = default;
- // Encrypt plaintext
- common::Result<EncryptedData> encrypt(const std::string& plaintext);
- common::Result<EncryptedData> encrypt(const std::vector<uint8_t>& plaintext);
- // Decrypt ciphertext
- common::Result<std::string> decrypt(const EncryptedData& data);
- common::Result<std::vector<uint8_t>> decryptBytes(const EncryptedData& data);
- // Convenience methods for string-based storage
- common::Result<std::string> encryptToBase64(const std::string& plaintext);
- common::Result<std::string> decryptFromBase64(const std::string& encoded);
- // Generate random bytes for IV
- static std::vector<uint8_t> generateRandomIv();
- // Generate random key (32 bytes for AES-256)
- static std::string generateRandomKey();
- private:
- // Derive encryption key from master key using PBKDF2
- std::vector<uint8_t> deriveKey(const std::vector<uint8_t>& salt);
- AesGcmConfig config_;
- std::vector<uint8_t> derived_key_; // Cached derived key (if not using salt per encryption)
- };
- // Base64 encoding/decoding utilities
- namespace base64 {
- std::string encode(const std::vector<uint8_t>& data);
- std::string encode(const uint8_t* data, size_t len);
- common::Result<std::vector<uint8_t>> decode(const std::string& encoded);
- }
- } // namespace smartbotic::crypto
|