package net.itdos.secrit;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Jiajie {
/**
* @param args
*/
public static void main(String[] args) {
jiami();
jiemi();
}
private static void jiami() {
try {
//实例个 加密对象
Cipher cipher=Cipher.getInstance("AES");
// 实例密钥
SecretKey secreKey = KeyGenerator.getInstance("AES").generateKey();
//通过secreKey加密
cipher.init(Cipher.ENCRYPT_MODE, secreKey);
byte[] result = cipher.doFinal("itdoselt444".getBytes());
//把key保存到硬盘
FileOutputStream foskey = new FileOutputStream("txx_key");
ObjectOutputStream oossecreKey = new ObjectOutputStream(foskey);
oossecreKey.writeObject(secreKey);
oossecreKey.close();
foskey.close();
//把result保存到硬盘
FileOutputStream fosresult = new FileOutputStream("txx_data");
fosresult.write(result);
fosresult.close();
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void jiemi(){
try {
//实例个 加密对象
Cipher cipher=Cipher.getInstance("AES");
FileInputStream fiskey = new FileInputStream("txx_key");
ObjectInputStream oiskey = new ObjectInputStream(fiskey);
Key key = (Key)oiskey.readObject();
oiskey.close();
fiskey.close();
//通过secreKey解密
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fisresult = new FileInputStream("txx_data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(fisresult,baos);
byte[] result = cipher.doFinal(baos.toByteArray());
baos.close();
fisresult.close();
System.out.println(
new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void copyStream(InputStream fis,OutputStream fos){
byte[] buf = new byte[1024];
try {
int len = fis.read(buf);
while (len != -1) {
fos.write(buf, 0, len);
len = fis.read(buf);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
转载于:https://blog.51cto.com/itdos/614811