【发布时间】:2018-09-26 06:44:22
【问题描述】:
我正在尝试制作一个加密工具,我想加密字符串,保存在数据库中然后解密,我正在使用 TextEncryptor 可查询的弹簧安全加密模块,因为我想用于 rest apiKey,但我无法制作它工作。
这是我的代码:
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
【问题讨论】:
-
我认为是相同的例外,但不是相同的情况。我认为文档解释了可查询的,因为我希望对给定的文本进行相同的加密。 docs.spring.io/spring-security/site/docs/current/reference/…
标签: java encryption spring-security