javax.crypto.Ciphe加密大文本文件是不是不行啊
为什么每次文字一多 就不能输出正确的东西   
文字一少就可以呢
/***********************分割线****************//***********************源代码****************/package com.fzu.security.SymmetricalSecretKey;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
 * 演示对称秘钥加密解密
 * 
 * @author Administrator
 * 
 */
public class SymmetricalSecretKey {
public static void main(String[] args) {
encrypt("d:/a.txt");
decrypt();
}
/**
 * 加密方法
 */
public static void encrypt(String filePath) {
try {
Cipher cipher=Cipher.getInstance("AES");
SecretKey secretKey=KeyGenerator.getInstance("AES").generateKey();
OutputStream keyOut=new FileOutputStream("fzu_smiler.key");
ObjectOutputStream objectOutputStream=new ObjectOutputStream(keyOut);
objectOutputStream.writeObject(secretKey);
objectOutputStream.close();
keyOut.close();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//  byte[] b=cipher.doFinal("abc".getBytes());
FileInputStream plaintextInputStream=new FileInputStream(filePath);
int len=-1;
byte[] buf=new byte[1024];
while((len=plaintextInputStream.read(buf))!=-1)
{
cipher.update(buf,0,len);}
byte[] result=cipher.doFinal();
OutputStream dateOut=new FileOutputStream("fzu_smiler_encreptdata.dat");
dateOut.write(result);
dateOut.close();} catch (Exception e) {
e.printStackTrace();
}
}/**
 * 解密方法
 */
public static void decrypt() {
try {
Cipher cipher=Cipher.getInstance("AES");
InputStream keyInputStream=new FileInputStream("fzu_smiler.key");
ObjectInputStream objectInputStream=new ObjectInputStream(keyInputStream);
SecretKey secretKey=(SecretKey)objectInputStream.readObject();
if(secretKey!=null)
{
cipher.init(Cipher.DECRYPT_MODE, secretKey);
InputStream dateInputStream=new FileInputStream("fzu_smiler_encreptdata.dat");
int len = -1;
byte[] b = new byte[1024];
while ((len = dateInputStream.read(b)) != -1) {
cipher.update(b,0,len);
}
byte[] result=cipher.doFinal();
System.out.println(new String(result));
OutputStream dataOut=new FileOutputStream("fzu_smiler_decreptdata.dat");
dataOut.write(result);
dateInputStream.close();
dataOut.close();}objectInputStream.close();
keyInputStream.close();} catch (Exception e) {
e.printStackTrace();
}}
}
希望高手能给我说说哪里出问题了呢  谢谢了。

解决方案 »

  1.   

    大数据文件要分段加密或解密,要用到blockSize和outputSize。
    1、你可以从Cipher实例中的getBlockSize方法获得blockSize,这个blockSize表示的是加密块的大小,和你的公钥私钥长度有关,如果长度是1024,blockSize就是127字节。
    2、你可以从Cipher实例中的getOutputSize方法获得outputSize,如果blockSize是127字节,这个应该是128字节。
    3、如果你的原始数据是22736字节的,也就是22.2kb的样子,加密的块数就是n=22736/127,如果不能整除,就是n=22736/127+1。这里的n=180块,最后一块只包含3字节。加密后的数据大小则是n
    *128=23040.解密则是这个的逆过程,也就是23040字节被还原成22736字节。
    3、用到的方法有Cipher实例的update和doFinal方法,详细的内容具体参考api文档应该就可以了。
      

  2.   


    路过,顶一下。虽然不懂这个,但肯定不会如LZ所理解的那样。这个东西肯定是没有问题的。建议多看下问题,相信会有解决的方法的。祝LZ可以早点找到解决方案!