package com;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class DES {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
KeyGenerator kg = KeyGenerator.getInstance("DESede"); //获取密匙生成器
SecretKey key = kg.generateKey(); //生成密匙,可用多种方法来保存密匙
Cipher cp = Cipher.getInstance("DESede"); //创建密码器
cp.init(Cipher.ENCRYPT_MODE, key); //初始化 第一个参数:为1时为加密,为2时为解密
String str = "DESede对称密码体系";
byte [] ptext = str.getBytes("GBK");
byte [] ctext = cp.doFinal(ptext);//加密
System.out.println("密钥是:"+new String(key.getEncoded(),"GBK"));
System.out.println("密文是:"+new String(ctext,"GBK"));
cp.init(Cipher.DECRYPT_MODE, key); //初始化 第一个参数:为1时为加密,为2时为解密
byte [] mtext = cp.doFinal(ctext); //解密
String result = new String(mtext, "GBK");
System.out.println("明文是:"+result);
}catch(Exception e){
e.printStackTrace();
}
}
}
package com;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSA {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); //创建‘密匙对’生成器
KeyPair kp = kpg.genKeyPair();
PublicKey public_key = kp.getPublic(); //获得公匙
PrivateKey private_key = kp.getPrivate(); //获得私匙
Cipher cp = Cipher.getInstance("RSA"); //创建密码器
cp.init(Cipher.ENCRYPT_MODE, public_key); //初始化 第一个参数:为1时为加密,为2时为解密
String str = "RSA非对称密码体系";
byte [] ptext = str.getBytes("GBK");
byte [] ctext = cp.doFinal(ptext); //加密
cp.init(Cipher.DECRYPT_MODE, private_key); //初始化 第一个参数:为1时为加密,为2时为解密
byte [] mtext = cp.doFinal(ctext); //解密
System.out.println("公钥是:"+new String(public_key.getEncoded(),"GBK"));
System.out.println("私钥是:"+new String(private_key.getEncoded(),"GBK"));
System.out.println("秘文是:"+new String(ctext,"GBK"));
String result = new String(mtext, "GBK");
System.out.println("明文是:"+result);
}catch(Exception e){
e.printStackTrace();
}
}
}