public class SecretKeyTest {
public static void main(String[] args) throws Exception{
SecrectEncrypt();
SecretDecrpy();
}
private static void SecrectEncrypt() throws Exception {
//
Cipher cipher=Cipher.getInstance("PBEWithMD5AndDES");
// SecretKey key=KeyGenerator.getInstance("AES").generateKey();
//Key SecretKey,publicKey/PrivateKey
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("abcdefg".toCharArray()));
//
FileOutputStream foskey = new FileOutputStream("c://k.txt");
ObjectOutputStream ooskey = new ObjectOutputStream(foskey);
ObjectOutputStream sysout=new ObjectOutputStream(System.out);
System.out.println(" :");
sysout.writeObject(key);
ooskey.writeObject(key);
ooskey.close();
foskey.close();
//
cipher.init(Cipher.ENCRYPT_MODE, key,new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8}, 8));
byte[] results = cipher.doFinal(" ".getBytes());
//
System.out.println(" : ");
FileOutputStream fosDate = new FileOutputStream("c://data.txt");
fosDate.write(results);
fosDate.close();
}
private static void SecretDecrpy() throws Exception {
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec("abcdefg".toCharArray()));
ObjectOutputStream sysout=new ObjectOutputStream(System.out);
System.out.println(" :");
sysout.writeObject(key);
cipher.init(Cipher.DECRYPT_MODE, key,new PBEParameterSpec(new byte[]{1,2,3,4,5,6,7,8}, 8));
FileInputStream fisdate = new FileInputStream("c://data.txt");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(fisdate, baos);
byte[] result = cipher.doFinal(baos.toByteArray());
fisdate.close();
baos.close();
System.out.println(" :"+new String(result));
}
private static void copyStream(InputStream ips,OutputStream ops) throws Exception {
byte[] buf = new byte[1024];
int len=ips.read(buf);
while (len !=- 1) {
ops.write(buf, 0,len);
len = ips.read(buf);
}
}
}