当运行下面的程序时,我得到这个异常。无法弄清楚 AES 允许 128 -256 位 key 的问题是什么?
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 29 bytes
at com.sun.crypto.provider.AESCipher.engineGetKeySize(DashoA13*..)
at javax.crypto.Cipher.b(DashoA13*..)
在第 20 行获取异常
这是程序
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AESEncryptionDecryptionTest {
private static final String ALGORITHM = "AES";
private static final String myEncryptionKey = "ThisIsSecurityKey";
private static final String UNICODE_FORMAT = "UTF8";
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key); //////////LINE 20
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = new BASE64Encoder().encode(encValue);
return encryptedValue;
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
byte[] keyAsBytes;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
return key;
}
public static void main(String[] args) throws Exception {
String value = "password1";
String valueEnc = AESEncryptionDecryptionTest.encrypt(value);
String valueDec = AESEncryptionDecryptionTest.decrypt(valueEnc);
System.out.println("Plain Text : " + value);
System.out.println("Encrypted : " + valueEnc);
System.out.println("Decrypted : " + valueDec);
}
}
最佳答案
AES 允许 128、192 或 256 位 key 长度。即 16、24 或 32 字节。尝试仅将 mEncryptionKey
的前 16 个字节作为 keyAsBytes
。
编辑:
我想到了之后。我养成的一个习惯,也是我推荐的一个习惯,就是采用密码/密码短语的 SHA 哈希,并将其用作 key 的源字节。无论密码/密码的长度如何,采用散列可确保 key 数据的大小正确。您当前使用字符串字节的实现有两个问题;
- 如果有人使用短密码,它会破坏您的 key 生成。
- 前 16 个字节相同的两个不同密码将创建相同的 key 。
这两个问题都通过使用哈希来消除。
看看这个类中的buildKey()
方法; https://github.com/qwerky/DataVault/blob/master/src/qwerky/tools/datavault/DataVault.java
关于java - 获取异常 java.security.InvalidKeyException : Invalid AES key length: 29 bytes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10831801/