如何从AES-GCM获取身份验证标签



我使用BouncyCastle加密C#中的数据,使用AES256 GCM算法。为此,我使用了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生成两个输出:密文和消息身份验证码(也称为身份验证标签)。

我不明白如何从这个代码中获得身份验证标签?有人能帮我吗?

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

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

来源:http://www.bouncycastle.org/docs/docs1.5on/org/bouncycastle/crypto/modes/GCMBlockCipher.html"返回与上次处理的流关联的MAC的值"MAC="消息验证码"

DoFinal()函数的文档说明"完成在数据末尾附加或验证MAC的操作",这似乎证实了早先的假设,即cipherText也将包含MAC。使用GetMacSize(),您应该能够确定它与cipherText末尾的偏移量。

最新更新