我一直在尝试使用AES加密android中的一些XML文件,使用FTP将它们发送到服务器,然后使用java在Linux终端中解密它们。
我尝试使用AES,DES,Triple DES和其他加密方法加密,但是在通过FTP将文件发送到服务器之后,其中一些(约25%)无法解密,总是相同的。 我也试图解密在Android模拟器中收到的文件,但它无法正常工作
还尝试下载spongycastle jar并使用它们而不是BouncyCastle库,我在android java中读到了某些地方,但它也没有用。
我还尝试在加密文件之前删除每个\ r \ n。
我现在正在使用的库是:
我现在得到的错误是“javax.crypto.IllegalBlockSizeException:解密时最后一个块不完整”
我目前用于加密/解密的代码是:
String fileNotEncrypted=Environment.getExternalStorageDirectory() + "unencrypted.xml";
RandomAccessFile fileNotEncryptedRa = new RandomAccessFile(fileNotEncrypted, "r");
byte[] textNotEncryptedByte = new byte[(int)fileNotEncryptedRa.length()];
fileNotEncryptedRa.read(textNotEncryptedByte);
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
byte[] textEncryptedByte = EncodeDecodeAES.encryptBytes("1234567890123456", textNotEncryptedByte);
String fileEncrypted=Environment.getExternalStorageDirectory() + "encrypted.xml";
FileOutputStream fos = new FileOutputStream(fileEncrypted);
fos.write(textEncryptedByte);
fos.close();
这是我用于解密FTP收到的文件的代码
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
//encryptedFile is a String I get from main(String[] args), so I can use the code in a script easily
RandomAccessFile fileEncrypted = new RandomAccessFile(encryptedFile, "r");
byte[] textEncryptedByte = new byte[(int)fileEncrypted.length()];
fileEncrypted.read(textEncryptedByte);
byte[] textDecryptedByte = EncodeDecodeAES.decryptBytes("Dephi20101234567", textEncryptedByte);
//decriptedFile is another String got from main(String[] args)
FileOutputStream fos = new FileOutputStream(decryptedFile);
fos.write(textDecryptedByte);
fos.close();
解决方案:
问题是由尝试通过FTP发送密文引起的。 我要做的是将密文编码为base64,然后将base64写入文件,并通过FTP发送该文件。
对于Base64编码,我使用的是这里的开源库: Base64Coder
答案 0 :(得分:1)
我在解密Linux上加密的文件(反之亦然)时遇到了类似于Android的Base64类的问题。 Linux仅使用\n
(或仅\r
,不记得),而不是\r\n
正在进行中。这导致文件具有不同的长度并且解密失败。上面,您说已删除所有\r\n
,但我猜您没有检查\n
。尝试检查两个应该连贯的案例。
最后,http://examples.oreilly.com/9781565924024/files/oreilly/jonathan/util/Base64.java是我在Android和Linux上使用的Base64类,以确保一致性。