如何从 AES-GCM 获取认证标签

How to get authentication tag from AES-GCM

我使用 BouncyCastle 在 C# 中使用 AES256 GCM 算法加密数据。为此,我使用 implementation provided by James Tuley。下面是这段代码的片段:

public byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
    if (key == null || key.Length != KeyBitSize / 8)
        throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(key));

    if (secretMessage == null || secretMessage.Length == 0)
        throw new ArgumentException("Secret Message Required!", nameof(secretMessage));

    nonSecretPayload = nonSecretPayload ?? new byte[] { };
        
    byte[] nonce = _csprng.RandomBytes(NonceBitSize / 8);

    var cipher = new GcmBlockCipher(new AesFastEngine());
    var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
    cipher.Init(true, parameters);
        
    var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
    int len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
    cipher.DoFinal(cipherText, len);
        
    using (var combinedStream = new MemoryStream())
    {
        using (var binaryWriter = new BinaryWriter(combinedStream))
        {
            binaryWriter.Write(nonSecretPayload);
            binaryWriter.Write(nonce);
            binaryWriter.Write(cipherText);
        }

        return combinedStream.ToArray();
    }
}

我需要获取认证标签(在RFC 5084中提到)。它提到身份验证标签是输出的一部分:

AES-GCM generates two outputs: a ciphertext and message authentication code (also called an authentication tag).

我不明白如何从此代码中获取身份验证标签?谁能帮帮我?

调用cipher对象的GetMac()函数获取认证标签:

...
cipher.DoFinal(cipherText, len);
var auth_tag =  cipher.GetMac();
...

来源: http://www.bouncycastle.org/docs/docs1.5on/org/bouncycastle/crypto/modes/GCMBlockCipher.html "Return the value of the MAC associated with the last stream processed" MAC = "Message Authentication Code"

DoFinal() 函数的文档说明 "Finish the operation either appending or verifying the MAC at the end of the data",这似乎证实了之前的假设,即 cipherText 也已经包含 MAC。使用 GetMacSize(),您应该能够确定其距 cipherText.

末尾的偏移量