package com.what21.demo02;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
*/
public class StreamSecure {
/**
* 存储内容(保存时加密)
*
* @param fileName
* @param content
* @param cp
*/
public static void save(String fileName,String content,Cipher cp){
FileOutputStream fos=null;
CipherOutputStream cos=null;
try {
byte[] bt=content.getBytes("UTF8");
fos=new FileOutputStream(fileName);
cos=new CipherOutputStream(fos,cp);
cos.write(bt, 0, bt.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(cos!=null){
try {
cos.close();
} catch (IOException e) {
e.printStackTrace();
}
cos=null;
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
fos=null;
}
}
}
/**
* 读取内容(内存加密)
*
* @param fileName
* @param cp
* @return
*/
public static String read(String fileName,Cipher cp){
String content="";
FileInputStream fis=null;
CipherInputStream cis=null;
try {
File f=new File(fileName);
fis=new FileInputStream(fileName);
cis=new CipherInputStream(fis,cp);
int len=(int) f.length();
byte[] bt=new byte[len];
cis.read(bt,0,len);
String str=new String(bt,"UTF8");
content=str;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(cis!=null){
try {
cis.close();
} catch (IOException e) {
e.printStackTrace();
}
cis=null;
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
fis=null;
}
}
return content;
}
/**
* @param args
*/
public static void main(String[] args) {
KeyGenerator kg = null;
try {
//生成对称密钥
kg = KeyGenerator.getInstance("DESede");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
kg.init(168);
SecretKey key=kg.generateKey();
Cipher cp = null;
try {
//生成密码器
cp = Cipher.getInstance("DESede");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
//对内容进行加密,并保存文件
String content="测试对输入输出流的加密......1";
try {
//初始化密码器
cp.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
StreamSecure.save("stream.txt", content, cp);
//读取加密内容,并解密
String text="";
try {
//初始化密码器
cp.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
text=StreamSecure.read("stream.txt", cp);
//打印解密内容
System.out.println(text);
}
}