import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;public class test { public static void main(String[] args) {
// TODO Auto-generated method stub

//生成密钥

SecureRandom sr = new SecureRandom();
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance( "DES" );
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
kg.init(sr);

SecretKey key = kg.generateKey();
byte [] rawKeyData = key.getEncoded(); for(byte e : rawKeyData)
{
System.out.print(e);
}
System.out.println();//加密数据

Cipher cipher = null;
try {
cipher = Cipher.getInstance( "DES" );
cipher.init( Cipher.ENCRYPT_MODE, key, sr );
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

byte [] data ="caocongteng".getBytes();
byte [] encryptedData = null;
try {
encryptedData = cipher.doFinal( data );
} catch (IllegalBlockSizeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BadPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(byte e : encryptedData)
{
System.out.print(e);
}
System.out.println();
//解密数据
byte [] decryptedData=null;
try {
decryptedData = cipher.doFinal( encryptedData );
} catch (IllegalBlockSizeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BadPaddingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str2=new String(decryptedData); System.out.print(str2);
}}