1. Overview
In a real-life scenario, we come across several situations where we need encryption and decryption for security purposes. We can achieve this easily using a secret key. So for encrypting and decrypting a secret key, we have to know the way of converting the secret keys to string and vice-versa. In this tutorial, we’ll see the secret key and String conversion in Java. Also, we'll go through different ways of creating Secret Key in Java with examples.
2. Secret Key
A secret key is the piece of information or parameter that is used to encrypt and decrypt messages. In Java, we have SecretKey an interface that defines it as a secret (symmetric) key. The purpose of this interface is to group (and provide type safety for) all secret key interfaces.
There are two ways for generating a secret key in Java: generating from a random number or deriving from a given password.
In the first approach, the secret key is generated from a Cryptographically Secure (Pseudo-)Random Number Generator like the SecureRandom class.
For generating a secret key, we can use the KeyGenerator class. Let’s define a method for generating a SecretKey — the parameter n specifies the length (128, 192, or 256) of the key in bits:
public static SecretKey generateKey(int n) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(n);
SecretKey originalKey = keyGenerator.generateKey();
return originalKey;
}
In the second approach, the secret key is derived from a given password using a password-based key derivation function like PBKDF2. We also need a salt value for turning a password into a secret key. The salt is also a random value.
We can use the SecretKeyFactory class with the PBKDF2WithHmacSHA256 algorithm for generating a key from a given password.
Let’s define a method for generating the SecretKey from a given password with 65,536 iterations and a key length of 256 bits:
public static SecretKey getKeyFromPassword(String password, String salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey originalKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
return originalKey;
}
3. SecretKey and String Conversion
3.1. SecretKey to String
We'll convert the SecretKey into a byte array. Then, we'll convert the byte array into String using Base64 encoding:
public static String convertSecretKeyToString(SecretKey secretKey) throws NoSuchAlgorithmException {
byte[] rawData = secretKey.getEncoded();
String encodedKey = Base64.getEncoder().encodeToString(rawData);
return encodedKey;
}
3.2. String to SecretKey
We'll convert the encoded String key into a byte array using Base64 decoding. Then, using SecretKeySpecs, we'll convert the byte array into the SecretKey:
public static SecretKey convertStringToSecretKeyto(String encodedKey) {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
return originalKey;
}
Let's verify the conversion quickly:
SecretKey encodedKey = ConversionClassUtil.getKeyFromPassword("Baeldung@2021", "@$#baelDunG@#^$*");
String encodedString = ConversionClassUtil.convertSecretKeyToString(encodedKey);
SecretKey decodeKey = ConversionClassUtil.convertStringToSecretKeyto(encodedString);
Assertions.assertEquals(encodedKey, decodeKey);
4. Conclusion
In summary, we've learned how to convert a SecretKey into String and vice versa in Java. Additionally, we've discussed various ways of creating SecretKey in Java.
As always, the full source code of the article is available over on GitHub.
The post Secret Key and String Conversion in Java first appeared on Baeldung.