【发布时间】:2018-05-11 19:12:57
【问题描述】:
我首先使用这种方法生成了 IV:
public static String generateRandomIV() {
SecureRandom ranGen = new SecureRandom();
byte[] aesKey = new byte[16];
ranGen.nextBytes(aesKey);
StringBuffer result = new StringBuffer();
for (byte b : aesKey) {
result.append(String.format("%02x", b));
}
if (16 > result.toString().length()) {
return result.toString();
} else {
return result.toString().substring(0, 16);
}
}
然后尝试解密使用上述方法生成的IV加密的字符串:
private String decrypt(String _inputText, String _encryptionKey,
String _initVector) throws Exception {
String _out = "";
int len = _encryptionKey.getBytes("UTF-8").length;
if (_encryptionKey.getBytes("UTF-8").length >= _key.length) {
len = _key.length;
int ivlen = _initVector.getBytes("UTF-8").length;
if (_initVector.getBytes("UTF-8").length > _iv.length)
ivlen = _iv.length;
System.arraycopy(_encryptionKey.getBytes("UTF-8"), 0, _key, 0, len);
System.arraycopy(_initVector.getBytes("UTF-8"), 0, _iv, 0, ivlen);
SecretKeySpec keySpec = new SecretKeySpec(_key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(_iv);
//Decryption starts
_cx.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decodeValue = Base64.decode(_inputText.getBytes(), Base64.DEFAULT);
在上面代码 sn-p 的最后一行出现以下异常:
java.lang.RuntimeException: java.security.InvalidAlgorithmParameterException: IV must be specified in CBC mode
【问题讨论】:
-
您检查过 IV 以确保它是 16 字节吗?
-
你在哪里使用
IvParameterSpec ivSpec = new IvParameterSpec(_iv);????我看不出它有什么用处。
标签: java android android-studio encryption kotlin