1、用到的jar包:http://pan.baidu.com/s/1mgIbLvq提取码:ytj9
package com.tan.sucurity;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
import org.bouncycastle.util.encoders.Hex;
public class MyDES {
public static void main(String[] args) {
MyDES myDES=new MyDES();
myDES.jdkDES("imooc secuity des");
myDES.bcDES("imooc secuity des");
}
public void jdkDES(String src){
try {
//生成一个KEY
KeyGenerator keyGenerator=KeyGenerator.getInstance("DES");
keyGenerator.init(56);
SecretKey secretKey=keyGenerator.generateKey();
byte[] byteKey=secretKey.getEncoded();
//KEY的转换
DESKeySpec desKeySpec=new DESKeySpec(byteKey);
SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
SecretKey converSecrettKey=factory.generateSecret(desKeySpec);
//加密
Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密用到的条件
cipher.init(Cipher.ENCRYPT_MODE, converSecrettKey);
byte[] result=cipher.doFinal(src.getBytes());
System.out.println("jdk des encrypt:"+Hex.toHexString(result));
//解密操作
cipher.init(Cipher.DECRYPT_MODE, converSecrettKey);
result=cipher.doFinal(result);
System.out.println("jdk des encrypt:"+new String(result));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void bcDES(String src){
Security.addProvider(new BouncyCastleProvider());
try {
//生成一个KEY
KeyGenerator keyGenerator=KeyGenerator.getInstance("DES","BC");
keyGenerator.getProvider();
keyGenerator.init(56);
SecretKey secretKey=keyGenerator.generateKey();
byte[] byteKey=secretKey.getEncoded();
//KEY的转换
DESKeySpec desKeySpec=new DESKeySpec(byteKey);
SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
SecretKey converSecrettKey=factory.generateSecret(desKeySpec);
//加密
Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");//加密用到的条件
cipher.init(Cipher.ENCRYPT_MODE, converSecrettKey);
byte[] result=cipher.doFinal(src.getBytes());
System.out.println("bc des encrypt:"+Hex.toHexString(result));
//解密操作
cipher.init(Cipher.DECRYPT_MODE, converSecrettKey);
result=cipher.doFinal(result);
System.out.println("bc des encrypt:"+new String(result));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}