
## 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.0 KiB
Plaintext
40 lines
1.0 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,kotlin,diff-id=101,diff-type=noncompliant]
|
|
----
|
|
fun encrypt(key: ByteArray, ptxt: ByteArray) {
|
|
val iv = "7cVgr5cbdCZV".toByteArray()
|
|
|
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
|
val keySpec = SecretKeySpec(key, "AES")
|
|
val gcmSpec = GCMParameterSpec(128, iv)
|
|
|
|
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec) // Noncompliant
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=101,diff-type=compliant]
|
|
----
|
|
fun encrypt(key: ByteArray, ptxt: ByteArray) {
|
|
val random = SecureRandom()
|
|
val iv = ByteArray(12)
|
|
random.nextBytes(iv)
|
|
|
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
|
val keySpec = SecretKeySpec(key, "AES")
|
|
val gcmSpec = GCMParameterSpec(128, iv)
|
|
|
|
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec)
|
|
}
|
|
----
|
|
|
|
include::../../common/how-does-this-work.adoc[]
|