As per https://www.nuget.org/packages/Blazor.SubtleCrypto The package uses SubtleCrypto encrypt/decrypt methods and AES-GCM algorithm and returned in ciphertext. I am under the impression that using a shared key used during encryption, I should be able to decrypt the ciphertext in the backend using System.Security.Cryptography. But I encounter an exception: System.Security.Cryptography.CryptographicException : The computed authentication tag did not match the input authentication tag.
private static string Decrypt(string cypherText)
{
// convert from base64 to raw bytes spans
var encryptedData = Convert.FromBase64String(cypherText).AsSpan();
var key = Convert.FromBase64String("V4iOXGCoPpX3UncQ5W9bsfUCqIlWvewbMsBNT4IHZRQ=").AsSpan();
// 128 bit encryption / 8 bit = 16 bytes
var tagSizeBytes = 16;
var ivSizeBytes = 12; // 12 bytes iv
// cipher text size is whole data - iv - tag
var cipherSize = encryptedData.Length - tagSizeBytes - ivSizeBytes;
// extract iv (nonce) 12 bytes prefix
var iv = encryptedData.Slice(0, ivSizeBytes);
// followed by the real cipher text
var cipherBytes = encryptedData.Slice(ivSizeBytes, cipherSize);
// followed by the tag (trailer)
var tagStart = ivSizeBytes + cipherSize;
var tag = encryptedData.Slice(tagStart);
// now that we have all the parts, the decryption
Span<byte> plainBytes = cipherSize < 1024
? stackalloc byte[cipherSize]
: new byte[cipherSize];
using var aes = new AesGcm(key);
aes.Decrypt(iv, cipherBytes, tag, plainBytes);
return Encoding.UTF8.GetString(plainBytes);
}