
## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
40 lines
1.2 KiB
Plaintext
40 lines
1.2 KiB
Plaintext
== 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[]
|