rspec/rules/S3329/kotlin/how-to-fix-it/java-cryptography-extension.adoc
daniel-teuchert-sonarsource a2b0adf225
Modify rule S3329: Correct example code (#4242)
* Modify rule S3329: Correct example code

* Aligned compliant and noncompliant code

* Use AES/CBC/PKCS5Padding in all examples for Java and Kotlin
2024-09-06 15:47:04 +02:00

87 lines
2.4 KiB
Plaintext

== How to fix it in Java Cryptography Extension
=== Code examples
==== Noncompliant code example
[source,kotlin,diff-id=1,diff-type=noncompliant]
----
import java.nio.charset.StandardCharsets
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.Cipher
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
fun encrypt(key: String, plainText: String) {
val randomBytes = "7cVgr5cbdCZVw5WY".toByteArray(StandardCharsets.UTF_8)
val iv = IvParameterSpec(randomBytes)
val keySpec = SecretKeySpec(key.toByteArray(StandardCharsets.UTF_8), "AES")
try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv) // Noncompliant
} catch (e: NoSuchAlgorithmException) {
// ...
} catch (e: InvalidKeyException) {
// ...
} catch (e: NoSuchPaddingException) {
// ...
} catch (e: InvalidAlgorithmParameterException) {
// ...
}
}
----
==== Compliant solution
:explicit_strong: java.security.SecureRandom
include::../../common/fix/explicit-fix.adoc[]
[source,kotlin,diff-id=1,diff-type=compliant]
----
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.Cipher
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
fun encrypt(key: String, plainText: String) {
val random = SecureRandom();
val randomBytes = ByteArray(128);
random.nextBytes(randomBytes);
val iv = IvParameterSpec(randomBytes)
val keySpec = SecretKeySpec(key.toByteArray(StandardCharsets.UTF_8), "AES")
try {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv)
} catch (e: NoSuchAlgorithmException) {
// ...
} catch (e: InvalidKeyException) {
// ...
} catch (e: NoSuchPaddingException) {
// ...
} catch (e: InvalidAlgorithmParameterException) {
// ...
}
}
----
=== How does this work?
include::../../common/fix/fix.adoc[]