spring encrypt password code example
Example 1: java spring username encode and decode
private static final String ALGO = "AES";
private static final byte[] keyValue = new byte[] { 'T', 'E', 'S', 'T' };
public static String encrypt(String pwd) {
String encodedPwd = "";
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(pwd.getBytes());
encodedPwd = Base64.getEncoder().encodeToString(encVal);
} catch (Exception e) {
e.printStackTrace();
}
return encodedPwd;
}
public static String decrypt(String encryptedData) {
String decodedPWD = "";
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = Base64.getDecoder().decode(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
decodedPWD = new String(decValue);
} catch (Exception e) {
}
return decodedPWD;
}
private static Key generateKey() {
SecretKeySpec key = new SecretKeySpec(keyValue, ALGO);
return key;
}
Example 2: how to encrypt password in properties file in spring boot
java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”Topsecret@123" password=dev-env-secret algorithm=PBEWITHMD5ANDDES