【发布时间】:2012-12-04 04:53:55
【问题描述】:
我正在尝试使用 BigInteger 在 Java 中实现文件的 RSA 加密和解密。
我有我的参数 p、q、e、n、d
我将一个文件读入一个字节[]
System.out.println("Opening file: " + infile);
File file = new File(infile);
FileInputStream fis = new FileInputStream(file);
int filelength = (int)file.length();
byte[] filecontent = new byte[filelength];
fis.read(filecontent);
fis.close();
然后从那个字节[]制作一个BigInteger
BigInteger plaintext = new BigInteger(filecontent);
那么加密很简单
BigInteger ciphertext = plaintext.modPow(e, n);
然后我将密文写入一个新的加密文件
FileOutputStream fos = new FileOutputStream(outfile);
fos.write(ciphertext.toByteArray());
fos.close();
解密也差不多
BigInteger plaintext = ciphertext.modPow(d, n);
当我第一次用一个小文本文件对其进行测试时,它工作得非常好。它加密和解密就好了。然而,当我开始使用 jpg 或 zip 等其他文件进行测试时,一切都崩溃了。我无法确定调试问题,但我确实注意到有时从文件 byte[] 到 BigInteger 的转换会导致 BigInteger 对象为空。
在加密之前我需要对 byte[] 做些什么吗?
【问题讨论】:
-
“一切都崩溃了”是什么意思?
-
最好将文件内容拆分成块,分别加密。
-
我会得到空的加密文件,当然随后会得到不正确的解密文件。有关如何拆分文件的任何建议?
-
您应该使用 RSA 和对称密码的组合来加密文件,例如CBC 模式下的 AES。对于 RSA,您应该尽可能使用 OAEP 模式填充,尽管 PKCS#1 填充更容易用于学习目的。两者都已在 RSA 实验室的公开可用(且可读性强)的 PKCS#1 标准中进行了描述。仅使用模幂来加密文件就是学习如何不执行加密。没有对大数据进行填充的 RSA 是愚蠢的。
-
您只是想学习,还是有真正的应用?
标签: java cryptography rsa biginteger public-key-encryption