简体   繁体   English

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

[英]Removing characters from decrypted Base64 string in Java

In relation to this question; 关于这个问题; Java (Android) Decrypting msg with IV attached Java(Android)解密带有IV的味精

My message decrypts fine but with the unwanted IV byte data. 我的消息可以很好地解密,但带有不需要的IV字节数据。
I try to remove the attached IV, yet it does not delete all the characters and some character always remain behind. 我尝试删除所附的IV,但是并没有删除所有字符,并且某些字符始终保留在后面。 I'm not sure how I should be calculating the length of the encoded IV to remove the non-required characters. 我不确定如何计算编码的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;
}   

You need to remove the IV before decryption not after it, because it is a parameter of the decryption. 您需要在解密之前而不是之后删除IV,因为它是解密的参数。 Since the IV is prepended to the ciphertext there is no need to save it somewhere else (no need for your iV reference). 由于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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM