I was trying to make an crypto util, I want to encrypt string, save in db then decrypt, I'm using TextEncryptor queryable spring security crypto module, because I want to use for rest apiKey , but i can`t make it work.
Here is my code:
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;
public class CryptoUtil {
public static String encrypt(String plain, String password) {
String salt = KeyGenerators.string().generateKey();
TextEncryptor textEncryptor = Encryptors.queryableText(password, salt);
return textEncryptor.encrypt(plain);
}
public static String decrypt(String encrypted, String password) {
String salt = KeyGenerators.string().generateKey();
TextEncryptor textEncryptor = Encryptors.queryableText(password, salt);
return textEncryptor.decrypt(encrypted);
}
}
----------------------------------------------------
public static void main(String[] args) {
String password = "password";
String plain = "hello";
String encrypted = CryptoUtil.encrypt(plain,password);`enter code here`
String decrypted = CryptoUtil.decrypt(encrypted, password);
}
----------------------------------------------------
Exception in thread "main" java.lang.IllegalStateException: Unable to invoke Cipher due to bad padding
at org.springframework.security.crypto.encrypt.CipherUtils.doFinal(CipherUtils.java:142)
at org.springframework.security.crypto.encrypt.AesBytesEncryptor.decrypt(AesBytesEncryptor.java:128)
at org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor.decrypt(HexEncodingTextEncryptor.java:40)
at com.ind.app.util.CryptoUtil.decrypt(CryptoUtil.java:18)
at com.ind.app.Test.main(UsuarioTest.java:11)
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at org.springframework.security.crypto.encrypt.CipherUtils.doFinal(CipherUtils.java:135)
... 4 more