如何使用自定义秘密密钥而不是在AES 256加密中生成新的秘密密钥
我现在正在尝试在Java开发AES 256 CFB加密程序。
我想使用自己的秘密钥匙(十六进制)。但是,它回报了关键长度有问题。
代码
class encryption_different {
private static String SECRET_KEY = "afd7a42b34f4875e05d210ea1252e02d5305becdb752f3553d657bab1236f733";
public static String encrypt(String strToEncrypt) {
try {
//IV handling
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
//convert custom key string to Secret key format
byte[] decodedKey = Base64.getDecoder().decode(SECRET_KEY);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, originalKey, ivspec);
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static void main(String[] args){
encrypt("password1");
}
}
这是我收到的错误消息的
Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 48 bytes
:因此,我想知道为什么我会收到此错误消息以及如何修复它。
I am now trying to develop a AES 256 CFB encryption program in Java.
I wish to use my own secret key (Hex). However, it returned that there is something wrong with the key length.
Here is the code
class encryption_different {
private static String SECRET_KEY = "afd7a42b34f4875e05d210ea1252e02d5305becdb752f3553d657bab1236f733";
public static String encrypt(String strToEncrypt) {
try {
//IV handling
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
//convert custom key string to Secret key format
byte[] decodedKey = Base64.getDecoder().decode(SECRET_KEY);
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, originalKey, ivspec);
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static void main(String[] args){
encrypt("password1");
}
}
The error message I got:
Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 48 bytes
And therefore, I would like to know why I am getting this error message and how to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论