日期:2014-05-20  浏览次数:20796 次

java版AES文件加密速度问题
简单的一个java版的AES文件加密demo,   运行正常,   但文件一大速度就会很慢,不知道是否能优化一下,以提高增快加密的速度或许是我的代码写法有问题,   希望各位大俠指正

       
import   java.io.File;
import   java.io.FileInputStream;
import   java.io.FileOutputStream;
import   java.security.SecureRandom;

import   javax.crypto.Cipher;
import   javax.crypto.KeyGenerator;
import   javax.crypto.SecretKey;
import   javax.crypto.spec.SecretKeySpec;

public   class   AES   {

//   加密文件
public   static   void   encryptfile(String   pwd,   File   fileIn)   throws   Exception   {
try   {
                        //读取文件
FileInputStream   fis   =   new   FileInputStream(fileIn);
byte[]   bytIn   =   new   byte[(int)   fileIn.length()];
for   (int   i   =   0;   i   <   fileIn.length();   i++)   {
bytIn[i]   =   (byte)   fis.read();
}
                        //AES加密
KeyGenerator   kgen   =   KeyGenerator.getInstance( "AES ");
kgen.init(128,   new   SecureRandom(pwd.getBytes()));
SecretKey   skey   =   kgen.generateKey();
byte[]   raw   =   skey.getEncoded();
SecretKeySpec   skeySpec   =   new   SecretKeySpec(raw,   "AES ");
Cipher   cipher   =   Cipher.getInstance( "AES ");
cipher.init(Cipher.ENCRYPT_MODE,   skeySpec);
                        //写文件
byte[]   bytOut   =   cipher.doFinal(bytIn);
FileOutputStream   fos   =   new   FileOutputStream(fileIn.getPath()
+   ".aes ");
for   (int   i   =   0;   i   <   bytOut.length;   i++)   {
fos.write((int)   bytOut[i]);
}
fos.close();
fis.close();
}   catch   (Exception   e)   {
throw   new   Exception(e.getMessage());
}
}
public   static   void   main(String[]   args)   throws   Exception   {
AES   aes   =   new   AES();
String   pwd   =   "123 ";
File   file   =   new   File( "d:/xxx.doc ");
aes.encryptfile(pwd,   file);
}
}


------解决方案--------------------
FileInputStream fis = new FileInputStream(fileIn);
byte[] bytIn = new byte[(int) fileIn.length()];
for (int i = 0; i < fileIn.length(); i++) {
bytIn[i] = (byte) fis.read();
}

改为

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileIn));
byte[] bytIn = new byte[(int) fileIn.length()];
bis.read(b);
bis.close();

写也是类似。