【发布时间】:2022-01-14 00:33:42
【问题描述】:
我想使用加密密钥对我的密码进行编码。但是在打印编码密码时,我得到了一个空值。我在下面附上了我的代码:
public class FirstJava {
private static final Long ENCRYPTION_KEY = 29190210908917L;
public static String encrypt(String strToEncrypt, byte[] key) {
if (strToEncrypt == null)
return strToEncrypt;
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes()));
} catch (Exception exception) {
System.out.println("ERROR");
}
return null;
}
public static void main(String[] args) {
String password = "12345678";
byte[] arr = String.valueOf(ENCRYPTION_KEY).getBytes();
String passwordEnc = encrypt(password,arr);
System.out.println("passwordEnc============= "+passwordEnc);
}
}
【问题讨论】:
-
您的
encrypt方法在发生异常时返回 null,因此很可能发生的情况是:异常。如果发生异常,您会写出“错误”,这很有帮助,因此如果您在输出中看到它,这将表明您确实有异常。然后下一步是找出异常是什么。为此,您可以在 catch 块中写exception.printStackTrace();。 -
java.security.InvalidKeyException: Invalid AES key length: 14 bytes