CipherStream类
javax.crypto.CipherInputStream和javax.crypto.CipherOutputStream提供方便的对流的打包方式,且自动进行加解密,特别适合对网络数据流及文件IO的加解密。
javax.crypto.CipherInputStream和javax.crypto.CipherOutputStream提供方便的对流的打包方式,且自动进行加解密,特别适合对网络数据流及文件IO的加解密。
使用CipherInputStream和CipherOutputStream时,必需使用相同的Key对流进行加解密。
RC4是最常见的网络流加密算法,RC4的速度非常快,但由于RC4算法加密是采用的xor,所以,一旦子密钥序列出现了重复,密文就有可能被破解。
RC4加密后的密文与明文长度相同。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
/**
* CipherStream演示
* @author shanl
*
*/
public class CipherStreamDemo1 {
public static void main(String[] args){
t2();
// t1();
}
/**
* 使用CipherInputStream对 已加密文件解密
*/
static void t2(){
File dir = new File("D:\\test\\2\\");
File plain = new File(dir,"encrypt.zip");
File dest = new File(dir, "plain.zip");
File keyBin = new File(dir, "key.bin");
CipherInputStream in = null;
OutputStream out = null;
byte[] buff = new byte[512];
int readLen = 0;
InputStream keyIn = null;
try{
SecureRandom sr = new SecureRandom();
keyIn = new FileInputStream(keyBin);
readLen = keyIn.read(buff);
keyIn.close();
Key key = new SecretKeySpec(buff,0,readLen,"RC4");
Cipher cip = Cipher.getInstance("RC4");
cip.init(Cipher.DECRYPT_MODE, key, sr);
in = new CipherInputStream(new FileInputStream(plain), cip);
out = new FileOutputStream(dest);
long l = System.currentTimeMillis();
for(;-1!=(readLen=in.read(buff));){
out.write(buff, 0, readLen);
}
System.out.println("耗时:"+(System.currentTimeMillis()-l));
in.close();
out.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 使用CipherOutputStream对文件加密
*/
static void t1(){
File dir = new File("D:\\test\\2\\");
File src = new File(dir,"src.zip");
File dest = new File(dir,"encrypt.zip");
File keyBin = new File(dir, "key.bin");
InputStream in = null;
CipherOutputStream out = null;
byte[] buff = new byte[512];
int readLen = 0;
OutputStream keyOut = null;
try{
SecureRandom sr = new SecureRandom();
KeyGenerator keyGener = KeyGenerator.getInstance("RC4");
keyGener.init(128);
Key key = keyGener.generateKey();
Cipher cip = Cipher.getInstance("RC4");
cip.init(Cipher.ENCRYPT_MODE, key, sr);
keyOut = new FileOutputStream(keyBin);
keyOut.write(key.getEncoded());
keyOut.close();
in = new FileInputStream(src);
out = new CipherOutputStream(new FileOutputStream(dest), cip);
System.out.println("原文件长度:"+src.length());
long l = System.currentTimeMillis();
for(int i=0;-1!=(readLen=in.read(buff)); i++){
out.write(buff, 0, readLen);
}
System.out.println("耗时:"+(System.currentTimeMillis()-l));
in.close();
out.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}