1+ import java .security .SecureRandom ;
2+ import javax .crypto .SecretKeyFactory ;
3+ import javax .crypto .spec .PBEKeySpec ;
4+
5+ public class Test {
6+
7+ public static byte [] generateSalt (int length ) {
8+ SecureRandom random = new SecureRandom ();
9+ byte [] salt = new byte [length ];
10+ random .nextBytes (salt );
11+ return salt ;
12+ }
13+
14+ /**
15+ * PBKDF2 derivation with a weak key size.
16+ *
17+ * SAST/CBOM: - Parent: PBKDF2. - Key size is only 64 bits, which is far below acceptable security standards.
18+ * - Flagged as insecure.
19+ */
20+ public void pbkdf2WeakKeySize (String password ) throws Exception {
21+ byte [] salt = generateSalt (16 );
22+ int iterationCount = 100_000 ;
23+ int keySize = 64 ; // $Source
24+ PBEKeySpec spec = new PBEKeySpec (password .toCharArray (), salt , iterationCount , keySize ); // $Alert[java/quantum/weak-kdf-key-size]
25+ SecretKeyFactory factory = SecretKeyFactory .getInstance ("PBKDF2WithHmacSHA256" );
26+ byte [] key = factory .generateSecret (spec ).getEncoded ();
27+ }
28+
29+ /**
30+ * PBKDF2 derivation with a secure key size.
31+ *
32+ * SAST/CBOM: - Parent: PBKDF2. - Key size is 256 bits, which meets modern security standards.
33+ */
34+ public void pbkdf2SecureKeySize (String password ) throws Exception {
35+ byte [] salt = generateSalt (16 );
36+ int iterationCount = 100_000 ;
37+ int keySize = 256 ;
38+ PBEKeySpec spec = new PBEKeySpec (password .toCharArray (), salt , iterationCount , keySize );
39+ SecretKeyFactory factory = SecretKeyFactory .getInstance ("PBKDF2WithHmacSHA256" );
40+ byte [] key = factory .generateSecret (spec ).getEncoded ();
41+ }
42+ }
0 commit comments