从Java中解密的Base64字符串中删除字符

时间:2015-04-04 22:08:28

标签: java android encryption base64 initialization-vector

关于这个问题; Java (Android) Decrypting msg with IV attached

我的消息解密很好,但是有不需要的IV字节数据 我尝试删除附加的IV,但它不会删除所有字符,并且一些字符总是留在后面。我不确定如何计算编码IV的长度以删除不需要的字符。

public String decrypt(String cipherText, byte[] encryptionKey) throws Exception {
    SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");          
    cipher.init(Cipher.DECRYPT_MODE, key, iV);
    String decrypt = new String(cipher.doFinal( Base64.decode(cipherText, Base64.DEFAULT)));

    byte[] decryptData = new byte[decrypt.getBytes().length - iV.getIV().length];
    System.arraycopy(decrypt.getBytes(), iV.getIV().length, decryptData, 0, decrypt.getBytes().length - iV.getIV().length);

    Log.d("decrypt = ", decrypt);

    decrypt = new String(decryptData, "UTF-8");

    return decrypt;
}   

1 个答案:

答案 0 :(得分:0)

您需要在解密之前删除IV而不是之后,因为它是解密的参数。由于IV前置于密文,因此无需将其保存在其他位置(无需iV引用)。

byte[] ciphertextBytes = Base64.decode(cipherText, Base64.DEFAULT);
IvParameterSpec iv = new IvParameterSpec(ciphertextBytes, 0, 16);
ciphertextBytes = Arrays.copyOfRange(ciphertextBytes, 16, ciphertextBytes.length);

SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");          
cipher.init(Cipher.DECRYPT_MODE, key, iv);
String decrypt = new String(cipher.doFinal(ciphertextBytes), "UTF-8");