37 lines
925 B
Plaintext
37 lines
925 B
Plaintext
![]() |
== How to fix it in .NET
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
The example uses a hardcoded IV as a nonce, which causes AES-CCM to be insecure. To fix it, a nonce is randomly generated instead.
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,csharp,diff-id=101,diff-type=noncompliant]
|
||
|
----
|
||
|
public void encrypt(byte[] key, byte[] ptxt, byte[] ciphertext, byte[] tag)
|
||
|
{
|
||
|
var nonce = Encoding.UTF8.GetBytes("7cVgr5cbdCZV");
|
||
|
|
||
|
using var cipher = new AesGcm(key);
|
||
|
|
||
|
cipher.Encrypt(nonce, plaintext, ciphertext, tag); // Noncompliant
|
||
|
}
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,csharp,diff-id=101,diff-type=compliant]
|
||
|
----
|
||
|
public void encrypt(byte[] key, byte[] ptxt, byte[] ciphertext, byte[] tag)
|
||
|
{
|
||
|
var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
|
||
|
RandomNumberGenerator.Fill(nonce);
|
||
|
|
||
|
using var cipher = new AesGcm(key);
|
||
|
|
||
|
cipher.Encrypt(nonce, plaintext, ciphertext, tag);
|
||
|
}
|
||
|
----
|
||
|
|
||
|
include::../../common/how-does-this-work.adoc[]
|