rspec/rules/S3329/kotlin/rule.adoc

35 lines
959 B
Plaintext
Raw Normal View History

include::../description.adoc[]
== Noncompliant Code Example
----
val bytesIV = "7cVgr5cbdCZVw5WY".toByteArray(charset("UTF-8")) // Predictable / hardcoded IV
val iv = IvParameterSpec(bytesIV)
val skeySpec = SecretKeySpec(secretKey.toByteArray(), "AES")
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv) // Noncompliant (s3329)
val encryptedBytes: ByteArray = cipher.doFinal("foo".toByteArray())
----
== Compliant Solution
----
val random: SecureRandom = SecureRandom()
val bytesIV: ByteArray = ByteArray(16)
random.nextBytes(bytesIV); // Unpredictable / random IV
val iv = IvParameterSpec(bytesIV)
val skeySpec = SecretKeySpec(secretKey.toByteArray(), "AES")
val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv) //Compliant (s3329)
val encryptedBytes: ByteArray = cipher.doFinal("foo".toByteArray())
----
include::../see.adoc[]