对称加密常用的几种:DES,AES,3DES等
对称加密应用场景
1.本地数据加密(sp)
2.网络传输(post请求username=li,psw=jsdcaaosiiJDJJ(对密码进行了加密))
3.加密用户登入结果信并序列化到本地磁盘
4.网页交互数据加密
/**
* 生成秘钥并保存到硬盘上,之后读取该秘钥进行加密解密操作
*/
public class SymmetricalEncryption {
public static void main(String[] args) throws Exception {
//生成秘钥,并将其保存到硬盘上
//generateKey();
//从磁盘上读取key对象
Key key = readKey();
encrypt(key);
}
public static void generateKey() throws IOException, NoSuchAlgorithmException {
//随机生成秘钥
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
//序列化
/*FileOutputStream fos = new FileOutputStream(new File("heima.key"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(secretKey);*/
SerializableUtil.saveObject(secretKey, "heima.key");
}
public static Key readKey() throws ClassNotFoundException, IOException {
//反序列化
/*FileInputStream fis = new FileInputStream(new File("heima.key"));
ObjectInputStream ois = new ObjectInputStream(fis);
Key key = (Key) ois.readObject();
return key;*/
return (Key) SerializableUtil.readObject("heima.key");
}
public static void encrypt(Key key) throws Exception {
String content = "黑马程序员";
Cipher cipher = Cipher.getInstance("AES");
//加密
cipher.init(Cipher.ENCRYPT_MODE, key);
//分批处理
/*cipher.update("黑马".getBytes());
cipher.update("程序员".getBytes());
byte[] result = cipher.doFinal();*/
//一次性处理
byte[] result = cipher.doFinal(content.getBytes());
System.out.println("加密: " + new String(result));
//解密
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptResult = cipher.doFinal(result);
System.out.println("解密: " + new String(decryptResult));
System.out.println(cipher.getProvider().getInfo());
}
}
public class SerializableUtil {
//序列化
public static void saveObject(Object obj, String path) throws IOException{
FileOutputStream fos = new FileOutputStream(new File(path));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
}
//反序列化
public static Object readObject(String path) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(new File(path));
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ois.close();
return obj;
}
}