【发布时间】:2013-03-16 06:36:10
【问题描述】:
我一直在尝试使用 AES 加密 android 中的一些 XML 文件,使用 FTP 将它们发送到服务器,然后使用 java 在 Linux 终端中对它们进行解密。
我尝试使用 AES、DES、Triple DES 和其他加密方法进行加密,但是通过 FTP 将文件发送到服务器后,其中一些(约 25%)无法解密,总是相同的。 我也尝试在 android 模拟器中解密接收到的文件,但它也不起作用
还尝试下载 spongycastle jars 并使用它们而不是 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
【问题讨论】:
-
有点不清楚,但问题似乎出在您的密文上。但是,听起来您一直专注于明文,您是否在对密文进行编码?你的 ftp 传输可靠吗?
-
我尝试通过 ftp 重新发送文件,以防传输出现问题,但在第一次传输中失败的文件仍然失败,完全相同。我使用 FileOutputStream 将密文直接放入文件中,然后在尝试解密之前不要再触摸它。我将编辑帖子并添加我用于解密的代码,以防万一。
-
Ftp协议确实有编码,编码问题会导致这样的问题,你不妨试试base64编码密文进行传输。
-
您知道
RandomAccessFile.read需要循环执行吗?直到它返回 -1 ? -
我在最后 2 次测试中使用 RandomAccessFile.read(目前已经完成了 21 次),之前也遇到过同样的问题。但是从一开始就用ftp,所以base64编码密文的思路不错。我要试一试并发布结果。我认为使用 ftp 传输文件会在服务器中产生文件的一点点完美副本...
标签: java android encryption aes padding