3

AES256 GCM アルゴリズムを使用して、BouncyCastle を使用して 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 は、暗号文とメッセージ認証コード (認証タグとも呼ばれます) の 2 つの出力を生成します。

このコードから認証タグを取得する方法がわかりませんか? 誰でも私を助けることができますか?

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 に答える