package com.james.chps;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class CephTest {
/**
* @param args
* @throws Exception
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws NoSuchAlgorithmException, Exception {
// TODO Auto-generated method stub
Cipher c=Cipher.getInstance("AES");
FileInputStream fis=new FileInputStream("myscret.key");
ObjectInputStream ois=new ObjectInputStream(fis);
Key key=(Key) ois.readObject();
//SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
//加密
c.init(Cipher.ENCRYPT_MODE, key);
//从加密文件中读出key
byte[] jiamihou=c.doFinal("sdfa".getBytes());
System.out.println(jiamihou);
//解密
c.init(Cipher.DECRYPT_MODE, key);
System.out.println(new String(c.doFinal(jiamihou)));
}
//method1
public void method1() throws Exception, Throwable{
// TODO Auto-generated method stub
Cipher c=Cipher.getInstance("AES");
SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
//加密
c.init(Cipher.ENCRYPT_MODE, sk);
byte[] jiamihou=c.doFinal("sdfa".getBytes());
System.out.println(jiamihou);
//解密
c.init(Cipher.DECRYPT_MODE, sk);
System.out.println(new String(c.doFinal(jiamihou)));
}
//method2将密匙写入文件
public void method3() throws Exception{
// TODO Auto-generated method stub
Cipher c=Cipher.getInstance("AES");
SecretKey sk=KeyGenerator.getInstance("AES").generateKey();
//加密
c.init(Cipher.ENCRYPT_MODE, sk);
//密匙写入文件
FileOutputStream fos=new FileOutputStream("myscret.key");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(sk);
oos.flush();
oos.close();
byte[] jiamihou=c.doFinal("sdfa".getBytes());
System.out.println(jiamihou);
//解密
c.init(Cipher.DECRYPT_MODE, sk);
System.out.println(new String(c.doFinal(jiamihou)));
}
}