无效的AES密钥长度错误 [英] invalid AES key length error
问题描述
此代码给出无效的AES密钥长度错误。我该怎么纠正? (我想要128位密钥AES加密)
this code give invalid AES key length error. how can i correct it ? ( i want 128 bit key AES encryption )
package org.temp2.cod1;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class Code1 {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
String s = "9882623867";
byte[] plaintext = s.getBytes("UTF-16");
String s2 = "supernova";
byte[] key = s2.getBytes("UTF-16");
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(plaintext);
System.out.println(encryptedData);
}
}
任何帮助赞赏
推荐答案
使用 SecretKeyFactory
从密码中导出密钥字节。您可以看到一个详细的示例这里请注意,您需要指定128位密钥的密钥长度,而不是256位,如该示例所示。
Use a SecretKeyFactory
to derive key bytes from a password.You can see a detailed example here. Note that you'll need to specify a key length of 128 bits key instead of 256 bits as shown in that example.
您将遇到的下一个问题是您尚未指定填充方案。除非您的消息是16字节的倍数(AES块大小),否则会引起错误。使用PKCS5Padding,如示例所示。
The next problem that you will run into is that you have not specified a padding scheme. Unless your messages are a multiple of 16 bytes (the AES block size), that will raise an error. Use PKCS5Padding as shown in the example.
在密码上使用CBC模式将需要为每条消息选择一个新的初始化向量。这个独特的IV必须与加密的消息一起发送给收件人。
Use of CBC mode on the cipher will require a new initialization vector to be chosen for each message. This unique IV must be sent along with the encrypted message to the recipient.
尝试在不深入了解这里提出的概念的情况下执行加密(还有更多)可能导致不安全的系统。
Trying to perform cryptography without a thorough understanding of the concepts raised here (and a lot more) is likely to result in an insecure system.
这篇关于无效的AES密钥长度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!