I have code using the Crypto++ library where I am encrypting some bytes, I am having a problem where some bytes are not being encrypted.
This problem only occurs when I use a key and an iv for each byte
If I use a key and a single iv this problem does not occur
I have following code:
std::vector<uint8_t> sizeTToBytes(size_t value) {
std::vector<uint8_t> bytes(sizeof(size_t));
std::memcpy(bytes.data(), &value, sizeof(size_t));
return bytes;
}
std::vector<uint8_t> SHA1Hash(size_t value) {
std::vector<uint8_t> bytes = sizeTToBytes(value);
std::vector<uint8_t> hash(CryptoPP::SHA1::DIGESTSIZE);
CryptoPP::SHA1().CalculateDigest(hash.data(), bytes.data(), bytes.size());
std::vector<uint8_t> truncatedHash(hash.begin(), hash.begin() + 16);
return truncatedHash;
}
CryptoPP::SecByteBlock GenerateKey(const std::vector<uint8_t>& password, const std::vector<uint8_t>& salt, size_t iterations, size_t keyLength) {
CryptoPP::SecByteBlock Key(keyLength);
CryptoPP::PKCS5_PBKDF2_HMAC<CryptoPP::SHA1> pbkdf2;
pbkdf2.DeriveKey(
Key.data(), Key.size(),
0, // purpose identifier
password.data(), password.size(),
salt.data(), salt.size(),
iterations
);
return Key;
}
void BytesEncrypt(uint8_t *my_byte, uint32_t byte_len, size_t unique_id, size_t unique_val, size_t unique_val2) {
auto NewIV = SHA1Hash(unique_id);
auto NewSalt = SHA1Hash(unique_val);
auto NewKey = SHA1Hash(unique_val2);
CryptoPP::SecByteBlock my_key = GenerateKey(NewKey, 213, NewSalt, 32);
CryptoPP::SecByteBlock my_iv = GenerateKey(NewIV, 137, NewSalt, 12);
CryptoPP::GCM<CryptoPP::AES>::Encryption e;
e.SetKeyWithIV(my_key.data(), my_key.size(), my_iv.data(), my_iv.size());
e.ProcessData(my_byte, my_byte, byte_len);
}
Now if I change the code to use a single key and iv it encrypts all bytes
Can anyone tell me how I can fix the problem?