1+ import javax .crypto .Cipher ;
2+ import javax .crypto .KeyGenerator ;
3+ import javax .crypto .SecretKey ;
4+ import javax .crypto .spec .IvParameterSpec ;
5+
6+ public class Test {
7+ public static void main (String [] args ) throws Exception {
8+ SecretKey key = KeyGenerator .getInstance ("AES" ).generateKey ();
9+ IvParameterSpec iv = new IvParameterSpec (new byte [16 ]);
10+ byte [] data = "SensitiveData" .getBytes ();
11+
12+ // Insecure block mode: ECB
13+ Cipher cipherECB = Cipher .getInstance ("AES/ECB/PKCS5Padding" ); // $Alert
14+ cipherECB .init (Cipher .ENCRYPT_MODE , key );
15+ byte [] ecbEncrypted = cipherECB .doFinal (data );
16+ System .out .println ("ECB encrypted: " + bytesToHex (ecbEncrypted ));
17+
18+ // Insecure block mode: CFB
19+ Cipher cipherCFB = Cipher .getInstance ("AES/CFB/PKCS5Padding" ); // $Alert
20+ cipherCFB .init (Cipher .ENCRYPT_MODE , key , iv );
21+ byte [] cfbEncrypted = cipherCFB .doFinal (data );
22+ System .out .println ("CFB encrypted: " + bytesToHex (cfbEncrypted ));
23+
24+ // Insecure block mode: OFB
25+ Cipher cipherOFB = Cipher .getInstance ("AES/OFB/PKCS5Padding" ); // $Alert
26+ cipherOFB .init (Cipher .ENCRYPT_MODE , key , iv );
27+ byte [] ofbEncrypted = cipherOFB .doFinal (data );
28+ System .out .println ("OFB encrypted: " + bytesToHex (ofbEncrypted ));
29+
30+ // Insecure block mode: CTR
31+ Cipher cipherCTR = Cipher .getInstance ("AES/CTR/NoPadding" ); // $Alert
32+ cipherCTR .init (Cipher .ENCRYPT_MODE , key , iv );
33+ byte [] ctrEncrypted = cipherCTR .doFinal (data );
34+ System .out .println ("CTR encrypted: " + bytesToHex (ctrEncrypted ));
35+
36+ // Secure block mode: CBC with random IV
37+ IvParameterSpec randomIv = new IvParameterSpec (KeyGenerator .getInstance ("AES" ).generateKey ().getEncoded ());
38+ Cipher cipherCBCRandomIV = Cipher .getInstance ("AES/CBC/PKCS5Padding" );
39+ cipherCBCRandomIV .init (Cipher .ENCRYPT_MODE , key , randomIv );
40+ byte [] cbcRandomIVEncrypted = cipherCBCRandomIV .doFinal (data );
41+ System .out .println ("CBC (random IV) encrypted: " + bytesToHex (cbcRandomIVEncrypted ));
42+
43+ // Secure block mode: GCM (authenticated encryption)
44+ IvParameterSpec gcmIv = new IvParameterSpec (new byte [12 ]);
45+ Cipher cipherGCM = Cipher .getInstance ("AES/GCM/NoPadding" );
46+ cipherGCM .init (Cipher .ENCRYPT_MODE , key , gcmIv );
47+ byte [] gcmEncrypted = cipherGCM .doFinal (data );
48+ System .out .println ("GCM encrypted: " + bytesToHex (gcmEncrypted ));
49+ }
50+
51+ private static String bytesToHex (byte [] bytes ) {
52+ StringBuilder sb = new StringBuilder ();
53+ for (byte b : bytes )
54+ sb .append (String .format ("%02x" , b ));
55+ return sb .toString ();
56+ }
57+ }
0 commit comments