InvalidAlgorithmParameterException:必须在 CBC 模式下指定 IV

Mal*_*ngh 4 java encryption android kotlin android-studio

我首先使用这种方法生成 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后尝试解密使用上述方法生成的 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);
Run Code Online (Sandbox Code Playgroud)

上述代码片段的最后一行出现以下异常:

    java.lang.RuntimeException: java.security.InvalidAlgorithmParameterException: IV must be specified in CBC mode
Run Code Online (Sandbox Code Playgroud)

Afs*_*hin 6

我看不出你有什么用IV。尝试以下密码初始化:

_cx.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
Run Code Online (Sandbox Code Playgroud)