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 java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
*
* 作者: IT一号男
* 功能:安全密钥类(进行加密解密)
* 时间:2012-10-20 下午11:06:16
* 备注:1.加密分为对称加密(加密解密的密钥必须相同,只有通信的上方才能知道密钥.速度快);
* 2.非对称加密(即公钥加密,速度慢,加密解密的密钥不同,只有一个知道私钥,任何人都可以知道公钥);
*
*/
public class SecurityKey {
/**
* 加密
*
* @param encryptFile
* 加密文件
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws FileNotFoundException
* @throws IOException
* @throws Exception
*/
private static void secretEncrypt(String encryptFile)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, FileNotFoundException, IOException, Exception {
// 加密
Cipher cipher = Cipher.getInstance("AES");// 根据加密算法创建加密对象
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化加密方式
byte[] results = cipher.doFinal(encryptFile.getBytes());
System.out.println(new String(results));
// 创建解密key
FileOutputStream foskey = new FileOutputStream("zxx_secret.key");
ObjectOutputStream ossSecretKey = new ObjectOutputStream(foskey);
ossSecretKey.writeObject(key);
ossSecretKey.close();
foskey.close();
/*SecretKey key2=SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("12345678".toCharArray()));
cipher.init(Cipher.DECRYPT_MODE,key2);*/
// 存放解密数据
FileOutputStream fosData = new FileOutputStream("zxx.dat");
fosData.write(results);
fosData.close();
}
/**
* 解密
*
* @throws Exception
*/
private static void secretDecrypt() throws Exception {
Cipher cipher = Cipher.getInstance("AES");// 根据加密算法创建加密对象
FileInputStream fisKey = new FileInputStream("zxx_secret.key");
ObjectInputStream oisKey = new ObjectInputStream(fisKey);
Key key = (Key) oisKey.readObject();// 从文件读取密钥
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fisData = new FileInputStream("zxx.dat");
byte[] src = new byte[fisData.available()];
int len = fisData.read(src);
int total = 0;
while (total <= src.length) {
total += len;
len = fisData.read(src, total, src.length - total);
}
byte[] result = cipher.doFinal(src);
oisKey.close();
fisData.close();
System.out.println("解密内容为:" + new String(result));
}
public static void main(String[] args) throws Exception {
//secretEncrypt("pp");// 加密
secretDecrypt();// 解密
}
}