我尝试解密加密文本并使用此代码,但是向我收到此错误:
Exception in thread "main" java.security.InvalidKeyException: Illegal key size
和解密代码是:
String key = "ffce885876a617e7";
String vector = "9ee153a3df56965e7baf13a7fa1075cc";
IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
SecretKeySpec keySpec = new SecretKeySpec(vector.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //error occured in this line
答案 0 :(得分:1)
.getBytes()
不会自动将“十六进制字符串”转换为匹配的字节。
相反,请尝试使用此实用程序方法:
private static byte[] hexStringToBytes(final String input)
{
final int len = input.length();
if (len % 2 != 0)
throw new IllegalArgumentException();
final byte[] ret = new byte[len / 2];
int offset = 0;
for (int i = 0; i < ret.length; i++) {
ret[i] = (byte) Integer.parseInt(input.substring(offset, offset+2), 16);
offset += 2;
}
return ret;
}
然后在您的代码中使用hexStringToBytes(key)
等
答案 1 :(得分:0)
我用这个来解密AES。但是在Android环境中而不是Java vanila。
public String decrypt(String enc) throws Exception {
try {
String key = "ffce885876a617e7";
String vector = "9ee153a3df56965e7baf13a7fa1075cc";
IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
SecretKeySpec keySpec = new SecretKeySpec(vector.getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
return new String(cipher.doFinal(hexToByte(enc)), "UTF-8");
} catch (Exception localException) {
throw new Exception("[decrypt] " + localException.getMessage());
}
}
private static byte[] hexToByte(String enc) {
int j = enc.length() / 2;
byte[] arrayOfByte = new byte[j];
if (j >= 2) {
for (int i = 0; i < j; i++) {
arrayOfByte[i] = ((byte) Integer.parseInt(
enc.substring(i * 2, 2 + i * 2), 16));
}
}
return arrayOfByte;
}