rspec/rules/S3329/java/how-to-fix-it/java-cryptographic-extension.adoc
Loris S 981e54d330
Modify S3329: Learn-As-You-Code migration (#2293)
## Review

A dedicated reviewer checked the rule description successfully for:

- [x] logical errors and incorrect information
- [x] information gaps and missing content
- [x] text style and tone
- [x] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)

---------

Co-authored-by: hendrik-buchwald-sonarsource <64110887+hendrik-buchwald-sonarsource@users.noreply.github.com>
2023-06-28 17:25:56 +02:00

77 lines
2.3 KiB
Plaintext

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