decryption fails with: Invalid_Authentication_Tag: GCM tag check failed #4845
-
this is my code: vector<uint8_t> encrypt_aes256_gcm(vector<uint8_t> buffer, const uint8_t* key) {
const auto enc = Botan::AEAD_Mode::create("AES-256/GCM", Botan::Cipher_Dir::Encryption);
enc->set_key(key, 32);
Botan::AutoSeeded_RNG rng;
const auto nonce = rng.random_vec(12);
enc->start(nonce);
enc->finish(buffer, buffer.size());
vector<uint8_t> result(nonce.size() + buffer.size());
std::ranges::copy(nonce, result.begin()); // Add nonce at the start
std::ranges::copy(buffer, result.begin() + nonce.size()); // Add ciphertext+tag
return std::move(result);
}
vector<uint8_t> decrypt_aes256_gcm(vector<uint8_t> buffer, const uint8_t* key) {
const auto dec = Botan::AEAD_Mode::create("AES-256/GCM", Botan::Cipher_Dir::Decryption);
dec->set_key(key, 32);
vector nonce(buffer.begin(), buffer.begin() + 12);
buffer.erase(buffer.begin(), buffer.begin() + 12);
dec->start(nonce);
dec->finish(buffer);
return std::move(buffer);
} vector<uint8_t> to_bytes(string_view str) {
return vector<uint8_t>(str.begin(), str.end());
}
string to_string(const vector<uint8_t>& bytes) {
return string(bytes.begin(), bytes.end());
}
int main() {
const string sample_text = "سلام دنیا"; // Hello World in Persian
const uint8_t key[32] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20
};
cout << "Original text: " << sample_text << endl;
auto encrypted = encrypt_aes256_gcm(to_bytes(sample_text), key);
cout << "Encrypted size: " << encrypted.size() << " bytes" << endl;
auto decrypted = decrypt_aes256_gcm(encrypted, key);
cout << "Decrypted text: " << to_string(decrypted) << endl;
return 0;
} please help me! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
the problem was this |
Beta Was this translation helpful? Give feedback.
-
Hi Mohammad. What was going wrong in the first place? Did you have see compiler errors or did the code behave unexpectedly? Anyway: |
Beta Was this translation helpful? Give feedback.
Hi Mohammad. What was going wrong in the first place? Did you have see compiler errors or did the code behave unexpectedly?
Anyway:
enc->finish()
expects a vector as the first parameter (as it might have to re-allocate its length to accomodate the authentication tag). The second parameter (calledoffset
) is fairly technical and allows operating on only a portion of the passed-in vector. Typical uses won't need that and should leave it out (as you already found yourself).