Java(Android)解密附加IV的msg
我生成一个随机的IV,这个IV被附加到加密的msg前面(以普通字节表示),如下所示Java(Android)解密附加IV的msg,java,aes,Java,Aes,我生成一个随机的IV,这个IV被附加到加密的msg前面(以普通字节表示),如下所示 public String encrypt(String plainText, byte[] encryptionKey) throws Exception { SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES"); cipher.init(Cipher.ENCRYPT_MODE, key, iV);
public String encrypt(String plainText, byte[] encryptionKey) throws Exception {
SecretKeySpec key = new SecretKeySpec(encryptionKey, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, iV);
byte[] data = new byte[iV.getIV().length + plainText.getBytes("UTF-8").length];
// Merge together plain IV and encrypted cipher text
System.arraycopy(iV.getIV(), 0, data, 0, iV.getIV().length);
System.arraycopy(cipher.doFinal(plainText.getBytes("UTF-8")), 0, data, iV.getIV().length, plainText.getBytes("UTF-8").length);
return Base64.encodeToString(data, Base64.DEFAULT);
}
该消息使用WiFi Direct在设备之间发送。这是在我的主要活动中处理的
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
crypto.iV = new IvParameterSpec(Arrays.copyOf(readBuf, 16));
// Construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
try {
String decryptMsg = crypto.decrypt(readMessage, SECRET_KEY);
// Present the message
(chatFragment).pushMessage("Buddy (decrypt): " + decryptMsg);
Log.d(TAG, decryptMsg);
} catch (Exception e) {
e.printStackTrace();
}
// Present the message (comment out after testing!)
//(chatFragment).pushMessage("Buddy (encrypt): " + readMessage);
break;
在解密过程中失败并发出警告
04-04 14:55:05.770:W/System.err(9847):javax.crypto.IllegalBlockSizeException:解密中的最后一个块未完成
04-04 14:55:05.789:W/System.err(9847):在com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:850)
04-04 14:55:05.790:W/System.err(9847):位于javax.crypto.Cipher.doFinal(Cipher.java:1340)
04-04 14:55:05.790:W/System.err(9847):位于com.example.cryptochat.Crypto.decrypt(Crypto.java:52)
04-04 14:55:05.790:W/System.err(9847):位于com.example.cryptochat.MainActivity.handleMessage(MainActivity.java:463)
问题在于解密方法,但我不确定我做错了什么。该方法如下
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)));
decrypt = new String(Arrays.copyOfRange(decrypt.getBytes(), 16, decrypt.getBytes().length));
return decrypt;
}
使用带填充的分组密码时,加密文本始终大于解密文本。但是,您只能将解密文本复制到要发送的消息中的字节数。因此,您的加密邮件不完整
byte[] encryped = cipher.doFinal(plainText.getBytes("UTF-8"));
byte[] data = new byte[iV.getIV().length + encrypted.length];
System.arraycopy(iV.getIV(), 0, data, 0, iV.getIV().length);
System.arraycopy(encrypted, 0, data, iV.getIV().length, encrypted.length);
谢谢你的帮助,罗伯特!我可以用附加的IV解密文本,它在解密“CipherTextWithout IV”时不起作用。解密后如何删除Iv?不要在base64编码的字符串上执行字符串操作。解码它,然后执行操作。我仍然无法成功地从解密的消息中删除IV。CopyOfRange()似乎不起作用,对我应该做什么有什么建议吗?(*更新代码)