Zero Trust IoT library
Loading...
Searching...
No Matches
zt-encryption-utils.cc
Go to the documentation of this file.
1// zt-encryption-utils.cc
2
3#include "ns3/zt-encryption-utils.h"
4#include <cryptopp/hex.h>
5#include <cryptopp/filters.h>
6#include <cryptopp/aes.h>
7#include <cryptopp/modes.h>
8#include <cryptopp/osrng.h>
9
10namespace ns3 {
11
12using namespace CryptoPP;
13
22std::string EncryptPayload(const std::string& data, const byte* key, std::string& ivOut) {
23 AutoSeededRandomPool prng;
24 byte iv[AES::BLOCKSIZE];
25 prng.GenerateBlock(iv, sizeof(iv));
26 ivOut.assign((char*)iv, AES::BLOCKSIZE);
27
28 std::string cipher;
29 CBC_Mode<AES>::Encryption enc;
30 enc.SetKeyWithIV(key, AES::DEFAULT_KEYLENGTH, iv);
31
32 StringSource(data, true,
33 new StreamTransformationFilter(enc,
34 new StringSink(cipher)
35 )
36 );
37
38 return ivOut + cipher; // prepend IV to ciphertext
39}
40
48std::string DecryptPayload(const std::string& cipher, const byte* key) {
49 std::string iv = cipher.substr(0, AES::BLOCKSIZE);
50 std::string actualCipher = cipher.substr(AES::BLOCKSIZE);
51
52 std::string recovered;
53 CBC_Mode<AES>::Decryption dec;
54 dec.SetKeyWithIV(key, AES::DEFAULT_KEYLENGTH, (const byte*)iv.data());
55
56 StringSource(actualCipher, true,
57 new StreamTransformationFilter(dec,
58 new StringSink(recovered)
59 )
60 );
61
62 return recovered;
63}
64
71SecByteBlock HexDecodeKey(const std::string& hex) {
72 SecByteBlock key(AES::DEFAULT_KEYLENGTH);
73 StringSource(hex, true,
74 new HexDecoder(new ArraySink(key, key.size())));
75 return key;
76}
77
84std::vector<CryptoPP::byte> HexToBytes(const std::string& hex) {
85 std::string decoded;
86 CryptoPP::StringSource(hex, true,
87 new CryptoPP::HexDecoder(
88 new CryptoPP::StringSink(decoded)
89 )
90 );
91
92 return std::vector<CryptoPP::byte>(decoded.begin(), decoded.end());
93}
94
95} // namespace ns3
96
std::string EncryptPayload(const std::string &data, const byte *key, std::string &ivOut)
Encrypts a plaintext string using AES-CBC mode with a randomly generated IV.
std::vector< CryptoPP::byte > HexToBytes(const std::string &hex)
Converts a hexadecimal string into a byte vector.
std::string DecryptPayload(const std::string &cipher, const byte *key)
Decrypts a ciphertext string encrypted with EncryptPayload.
SecByteBlock HexDecodeKey(const std::string &hex)
Decodes a hex-encoded AES key string into a raw key byte block.