package com.ngsn.security;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
* 对称加密(加密解密的密钥一样)
* @author John.Yao
*
*/
public class SecretKeyTest1 {
public static void main(String[] args) throws Exception{
// SecretEncrypt();
SecretDecrypt();
}
/**
* 加密方法
* 将加密的密钥保存在zxx_secret.key文件中
* 将加密的数据保存在zxx.data文件中
* @throws Exception
*/
private static void SecretEncrypt() throws Exception{
//Cipher 此类为加密和解密提供密码功能
Cipher cipher = Cipher.getInstance("AES");
//根据AES的加密方法生成一个密钥
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
FileOutputStream fosKey = new FileOutputStream("zxx_secret.key");
ObjectOutputStream oosSecretKey = new ObjectOutputStream(fosKey);
//将密钥保存到zxx_secret.key文件中
oosSecretKey.writeObject(key);
oosSecretKey.close();
fosKey.close();
//初始化
//Cipher.ENCRYPT_MODE 为加密模式
//key 为加密的密钥
cipher.init(Cipher.ENCRYPT_MODE,key);
//对byte[] 进行加密,返回一个加密后的byte[]
byte[] result = cipher.doFinal("abc".getBytes());
System.out.println("result----->"+new String(result));
FileOutputStream fosData = new FileOutputStream("zxx.data");
fosData.write(result);
fosData.close();
}
/**
* 解密方法
* @throws Exception
*/
private static void SecretDecrypt()throws Exception{
//Cipher 此类为加密和解密提供密码功能
Cipher cipher = Cipher.getInstance("AES");
//从zxx_secret.key文件中得到key
FileInputStream fisKey = new FileInputStream("zxx_secret.key");
ObjectInputStream ois = new ObjectInputStream(fisKey);
Key key = (Key)ois.readObject();
ois.close();
fisKey.close();
//解密
//初始化
cipher.init(Cipher.DECRYPT_MODE, key);
//从zxx.data文件中得到加密的数据
FileInputStream fis = new FileInputStream("zxx.data");
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = fis.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
//从输出流中得到byte[]的加密数据
byte[] result = bos.toByteArray();
fis.close();
bos.close();
//对加密的数据进行解密
byte[] b = cipher.doFinal(result);
System.out.println("b------>"+new String(b));
}
}
java安全2
最新推荐文章于 2022-04-12 00:32:22 发布