上一章中我们接触了java中的对称加密,程序中的做法非常简单,只将一串字符串在程序中直接加密,这样子给人感觉这样的加密或许不是很好。这一章中,我将稍微改下上一章中的这种做法,而是将程序中产生的key与加密后的数据写到硬盘中,然后解密时,从磁盘中读取加密的数据与解密的key进行解密,这样子我们就可以将一段内容加密后生成的文件给他人,他人拿到这个文件时,如果在拿到我们key就可以对其进行解密查看内容,否则就无法看了,达到了我们要其效果。。
package com.cipher.test;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
*
* @ClassName: SimpleTest2
* @Description: 简单的对称加密(二)
* @author 我夕
* @date 2012-5-15
*/
public class SimpleTest2 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//加密
simpleSecret();
//解密
simpleDecret();
}
/**
* 加密方法
* @throws Exception
*/
public static void simpleSecret()throws Exception{
//创建cipher对象实例
Cipher cipher = Cipher.getInstance("AES");
//创建key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
//将key保存到磁盘
keySavaData(secretKey);
//初始化
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//加密数据
byte[] result=cipher.doFinal("hello java!".getBytes());
System.out.println("数据加密的结果:"+new String(result));
//讲加密的数据存到硬盘
FileOutputStream fileOutputStream = new FileOutputStream("simple.data");
fileOutputStream.write(result);
fileOutputStream.close();
}
/**
* 解密方法
* @throws Exception
*/
public static void simpleDecret()throws Exception{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keyReadData());
//从磁盘中读取数据的犯非法
byte[] result = cipher.doFinal(readData(new FileInputStream("simple.data")));
System.out.println("解密后的数据:"+new String(result));
}
/**
* 将产生的密钥写到磁盘上
* @param key
* @throws Exception
*/
public static void keySavaData(SecretKey key)throws Exception{
FileOutputStream fileOutputStream = new FileOutputStream("simple.key");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(key);
objectOutputStream.close();
fileOutputStream.close();
}
/**
* 从磁盘中读取密钥
* @throws Exception
*/
public static Key keyReadData() throws Exception{
FileInputStream fileInputStream = new FileInputStream("simple.key");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Key key = (Key)objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
return key;
}
/**
* 从磁盘中读取数据
* @param inputStream
* @throws Exception
*/
public static byte[] readData(FileInputStream inputStream) throws Exception{
ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
int len=0;
byte[] data=new byte[1024];
while((len=inputStream.read(data))!=-1){
arrayOutputStream.write(data, 0, len);
}
byte[] result=arrayOutputStream.toByteArray();
arrayOutputStream.close();
inputStream.close();
return result;
}
}
运行结果:
在程序中运行时,大家可以将解密中的方法注释掉,运行加密方法后,在对其所在的项目刷新后,会发现多了两个文件,一个加密内容后的文件,一个是生成key的文件(程序中为了方便,我是将生成的key与data直接在src路劲下)