43 lines
1.0 KiB
Plaintext
43 lines
1.0 KiB
Plaintext
== How to fix it in Java SE
|
|
|
|
=== Code examples
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
import javax.crypto.spec.PBEParameterSpec;
|
|
|
|
public void hash() {
|
|
byte[] salt = "salty".getBytes();
|
|
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, 10000); // Noncompliant
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
import java.security.SecureRandom;
|
|
import javax.crypto.spec.PBEParameterSpec;
|
|
|
|
public void hash() {
|
|
SecureRandom random = new SecureRandom();
|
|
byte[] salt = new byte[16];
|
|
random.nextBytes(salt);
|
|
|
|
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, 10000);
|
|
}
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/salt.adoc[]
|
|
|
|
Here, the compliant code example ensures the salt is random and has a sufficient
|
|
length by calling the `nextBytes` method from the `SecureRandom` class with a
|
|
salt buffer of 16 bytes. This class implements a cryptographically secure
|
|
pseudo-random number generator.
|