== How to fix it in Java Cryptography Extension

=== 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,java,diff-id=101,diff-type=noncompliant]
----
public void encrypt(byte[] key, byte[] ptxt) {
    byte[] nonce = "7cVgr5cbdCZV".getBytes("UTF-8");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce);

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec); // Noncompliant
}
----

==== Compliant solution

[source,java,diff-id=101,diff-type=compliant]
----
public void encrypt(byte[] key, byte[] ptxt) {
    SecureRandom random = new SecureRandom();
    byte[] nonce = new byte[12];
    random.nextBytes(nonce);

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
    GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce);

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
}
----

include::../../common/how-does-this-work.adoc[]
