Closed NKCSS closed 6 days ago
This is incorrect usage of the BC API. Replace lines 6-9 of DecryptCookie with this:
AeadParameters parameters = new AeadParameters(new KeyParameter(key), 128, iv, null);
gcmCipher.Init(false, parameters);
byte[] decryptedBytes = new byte[gcmCipher.GetOutputSize(encrypted.Length + tag.Length)];
int len = gcmCipher.ProcessBytes(encrypted, 0, encrypted.Length, decryptedBytes, 0);
len += gcmCipher.ProcessBytes(tag, 0, tag.Length, decryptedBytes, len);
...and it now decrypts fine.
Note that the associatedText
parameter of AeadParameters
is not for the tag; it is a way to pass "additional authenticated data" (AAD) that AEAD modes support (another way is to use ProcessAadByte(s)
calls). We pass null here to indicate there is no AAD.
The BC implementation instead expects the tag to be included at the end of the ciphertext. So we change the input to GetOutputSize
and also pass the tag data using a second ProcessBytes
call. Note that when encrypting with BC it will also include the tag at the end of the ciphertext automatically.
Describe the Bug
AES-GCM decryption using BouncyCastle's GcmBlockCipher class results in a mac check in GCM failed error, while the same parameters (key, IV, ciphertext, and tag) successfully decrypt in .NET's built-in AesGcm class. The issue seems to stem from differences in how BouncyCastle and .NET handle AES-GCM tag verification and decryption, particularly around tag and ciphertext handling.
To Reproduce
Verify in Python:
Verify in C#
Failed Decryption in C# with BouncyCastle:
Expected Behavior
Successful decryption with the tag verified.
Screenshots and Logs
Actual Output: mac check in GCM failed error.
Observations
The same parameters (key, IV, tag, and ciphertext) decrypt correctly using .NET's built-in AesGcm class. The Decrypt method of .NET's AesGcm automatically handles tag verification and decryption without issues. When using BouncyCastle, it appears that there's a mismatch or misalignment between how the tag and ciphertext are handled, resulting in the error.
Product Deployment
Please complete the following information:
Desktop
Please complete the following information: