2626 * All in one example for encryption and decryption of a string in one method.
2727 * - Random password generation using strong secure random number generator
2828 * - Random salt generation
29- * - Key derivation using PBKDF2 HMAC SHA-256 ,
29+ * - Key derivation using PBKDF2 HMAC SHA-512 ,
3030 * - AES-256 authenticated encryption using GCM
3131 * - BASE64 encoding as representation for the byte-arrays
3232 * - UTF-8 encoding of Strings
@@ -38,21 +38,24 @@ public class ExampleStringEncryptionPasswordBasedInOneMethod {
3838 public static void main (String [] args ) {
3939 String plainText = "Text that is going to be sent over an insecure channel and must be encrypted at all costs!" ;
4040 try {
41+ String password = null ;
4142 // GENERATE password (not needed if you have a password already)
42- KeyGenerator keyGen = KeyGenerator .getInstance ("AES" );
43- keyGen .init (256 );
44- String password = Base64 .getEncoder ().encodeToString (keyGen .generateKey ().getEncoded ());
43+ if (password == null || password .isEmpty ()) {
44+ KeyGenerator keyGen = KeyGenerator .getInstance ("AES" );
45+ keyGen .init (256 );
46+ password = Base64 .getEncoder ().encodeToString (keyGen .generateKey ().getEncoded ());
47+ }
4548
4649 // GENERATE random salt (needed for PBKDF2)
4750 final byte [] salt = new byte [64 ];
4851 SecureRandom random = SecureRandom .getInstanceStrong ();
4952 random .nextBytes (salt );
5053
5154 // DERIVE key (from password and salt)
52- SecretKeyFactory factory = SecretKeyFactory .getInstance ("PBKDF2WithHmacSHA512" );
53- KeySpec keyspec = new PBEKeySpec (password .toCharArray (), salt , 10000 , 256 );
54- SecretKey tmp = factory .generateSecret (keyspec );
55- SecretKey key = new SecretKeySpec (tmp .getEncoded (), "AES" );
55+ SecretKeyFactory secretKeyFactory = SecretKeyFactory .getInstance ("PBKDF2WithHmacSHA512" );
56+ KeySpec passwordBasedEncryptionKeySpec = new PBEKeySpec (password .toCharArray (), salt , 10000 , 256 );
57+ SecretKey secretKeyFromPBKDF2 = secretKeyFactory .generateSecret (passwordBasedEncryptionKeySpec );
58+ SecretKey key = new SecretKeySpec (secretKeyFromPBKDF2 .getEncoded (), "AES" );
5659
5760 // GENERATE random nonce (number used once)
5861 final byte [] nonce = new byte [32 ];
0 commit comments