在Java中快速模块化添加2个(可能很大)的文件

时间:2014-06-24 20:12:46

标签: java performance cryptography nio

我正在使用One Time Pads进行加密实验。

我有两个文件OTP和TEXT(1K-10K),其中包含字节。 OTP很大(> 1GB)。我想创建第三个文件CYPHERTEXT(与TEXT相同的大小),通过使用OTP的偏移执行TEXT与OTP的模块化添加。我使用java.io手工编写了这个代码,但是它很有效,但即使使用缓冲的IO(流或写入器),它也不是很敏捷。

我一直在寻找一种方法来使用NIO将一个底层字节缓冲区与另一个缓冲区一起添加但是找不到(内置)方法来执行此操作,或者使用来自OTP的数据来过滤TEXT的内容除了手工。有没有办法做这样的事情而不重新发明轮子?我以为我可以使用选择器。理想情况下,我希望能够处理OTP和TEXT大小超过2GB的文件,这就是我看NIO的原因。

private static void createOTP() {
...
System.out.print("Generating " + filename + " ");
long startTime = System.nanoTime();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos, MB);
for(long currentSize =0; currentSize < OTPSize; currentSize += baSize){
   new SecureRandom().nextBytes(ba);
   bos.write(ba);
   if(currentSize % (MB * 20L * (long)sizeInGB)==0){
      System.out.print(".");
   }
}
long elapsedTime = System.nanoTime() - startTime;
System.out.println(" OTP generation elapsed Time is " + (elapsedTime / 1000000.0) + " msec");
fos.close();
bos.close();
...
}

private static void symetricEncryptionDecryption(boolean encrypt) { 
...
outtext=new File(intext.getParentFile(), direction + ".OTP");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outtext), MB);
byte[] plaindata = new byte[(int)intext.length()];
DataInputStream dataIs = new DataInputStream(new FileInputStream(intext));
dataIs.readFully(plaindata);
dataIs.close();
ByteBuffer bb = ByteBuffer.wrap(plaindata);
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(otpFile))); 
in.skip(offset);
while(bb.hasRemaining()){
    bos.write( bb.get() + (encrypt? in.readByte() : -in.readByte()) );
}
bos.close();
in.close();
System.out.println("Offset: " + offset);
}

所以有一种更为灵巧的方法:

while(bb.hasRemaining()){
    bos.write( bb.get() + (encrypt? in.readByte() : -in.readByte()) );
}

或者为此生成OTP。

1 个答案:

答案 0 :(得分:1)

目前还不清楚你要做什么,但如果你的内存映射OTP文件,给你随机访问,你一次读取/处理8个字节,即long值你应该eb能够在100毫秒内编写一个加密的10K文本文件,大部分时间都用于启动JVM。

顺便说一句:如果您有权访问加密的TEXT和OTP文件,您可以解码文本而不会偏移,即您可以使用暴力破解。