在java中使用rsa加密和解密大文件
发布时间:2020-12-15 04:26:36 所属栏目:Java 来源:网络整理
导读:我使用RSA算法加密和解密大小超过rsa密钥大小的文件. 在下面的代码中进行加密,我正在逐块读取文件内容并转换为密文.块大小为32个字节. FileInputStream fin1 = new FileInputStream(genfile);FileOutputStream fout = new FileOutputStream(seedcipher);byte
我使用RSA算法加密和解密大小超过rsa密钥大小的文件.
在下面的代码中进行加密,我正在逐块读取文件内容并转换为密文.块大小为32个字节. FileInputStream fin1 = new FileInputStream(genfile); FileOutputStream fout = new FileOutputStream(seedcipher); byte[] block = new byte[32]; int i; while ((i = fin1.read(block)) != -1) { byte[] inputfile= cipher.doFinal(block); fout.write(inputfile); } fin1.close(); 在解密部分,在代码中完成相同的逐块解密,其中我已经提到块大小为128字节 FileInputStream fin1 = new FileInputStream(encryptedfile); FileOutputStream fout = new FileOutputStream(seedcipher); DataInputStream dos =new DataInputStream(fin1); DataOutputStream dosnew =new DataOutputStream(fout); byte[] block = new byte[128]; int i; while ((i = fin1.read(block)) != -1) { byte[] inputfile= cipher.doFinal(block); fout.write(inputfile); } 输入文件大小为81.3 kB并且文件包含 0 1 2 3 4.....29000 解密文件后,输出包含一些不相关的额外值.为什么结果中有额外的数据? 解决方法
用于逐块读取的IO代码不正确:
while ((i = fin1.read(block)) != -1) { byte[] inputfile= cipher.doFinal(block); fout.write(inputfile); } >它假定每次要求读取块时,都会读取整个块.情况不一定如此.只能读取几个字节. read()方法返回实际读取的字节数(并存储在i中).你不应该忽视它. 使用RSA加密大文件不是一个好主意.例如,您可以生成随机AES密钥,使用RSA对其进行加密并将其存储在输出文件中,然后使用AES加密文件本身,这样可以更快,并且对大输入没有任何问题.解密将读取加密的AES密钥,对其进行解密,然后使用AES解密文件的其余部分. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |