使用JAVA加密AES文件 [英] Encrypting a large file with AES using JAVA

查看:159
本文介绍了使用JAVA加密AES文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用少于这个(10mb,100mb,500mb)的文件测试了我的代码,加密工作。但是,我遇到的文件大于1GB的问题。
我生成了一个大文件(大约2gb),我想使用JAVA加密AES,但是我遇到这个错误:

I've tested my code with files less than this(10mb, 100mb, 500mb) and the encryption works. However, I run in to problems with files greater than 1gb. I've generated a large file (about 2gb) and I want to encrypt it with AES using JAVA, but I'm running into this error:

线程中的异常主要java.lang.OutOfMemoryError:Java堆空间

"Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"

我尝试使用-Xmx8G增加可用内存,但没有骰子。
我的代码部分如下

I've tried increasing available memory by using -Xmx8G, but no dice. Part of my code is as follows

    File selectedFile = new File("Z:\\dummy.txt");         
    Path path = Paths.get(selectedFile.getAbsolutePath());       
    byte[] toencrypt = Files.readAllBytes(path);       
    byte[] ciphertext = aesCipherForEncryption.doFinal(toencrypt);
    FileOutputStream fos = new FileOutputStream(selectedFile.getAbsolutePath());
    fos.write(ciphertext);
    fos.close();

据我所知,它以这种方式行事的原因是它试图读取整个文件,加密,并将其存储到另一个字节数组,而不是缓冲和流式传输。任何人都可以帮助我一些代码提示?

As far as I can tell, the reason it is behaving this way, is that it is trying to read the whole file at once, encipher it, and store it into another byte array instead of buffering and streaming it in. Can anyone help me with some code tips?

我是一个初学者编码,所以我真的不太了解,任何帮助将不胜感激。

I am a beginner to coding, so I don't really know much, any help will be appreciated.

推荐答案

尝试将整个大文件读入内存。一次加密缓冲区。只需执行标准的复制循环,并在 FileOutputStream 中包含一个适当初始化的 CipherOutputStream 。您可以将其用于所有文件,无需特别处理。使用8k以上的缓冲区。

Don't even try to read entire large files into memory. Encrypt a buffer at a time. Just do the standard copy loop with a suitably initialized CipherOutputStream wrapped around the FileOutputStream. You can use this for all files, no need to make a special case out of it. Use a buffer of 8k or more.

编辑 Java中的标准复制循环如下所示:

EDIT The 'standard copy loop' in Java is as follows:

byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

在这种情况下, out = new CipherOutputStream(new FileOutputStream(selectedFile),cipher)

这篇关于使用JAVA加密AES文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆