3

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

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

4

1 回答 1

3

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

...
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.

于 2016-05-01T10:27:25.297 回答