1个回答
展开全部
package cn.xinxi.des;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class DES {
private static final String str="xinxi";
public static void main(String[] args) throws Exception {
jdkDES();
bcDES();
}
public static void jdkDES() throws Exception{
//生成key
//KeyGenerator,密钥生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);//指定key size 这里使用默认值56位
//声称密钥
SecretKey secreKey= keyGenerator.generateKey();
byte[] bytesKey = secreKey.getEncoded();
//key转换(恢复密钥)
// SecretKey convertSecreKey = new SecretKeySpec(bytesKey,"DES");//与下面三行效果貌似差不多
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
// System.out.println(keyGenerator.getProvider());
Key convertSecreKey = factory.generateSecret(desKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[] result = cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("JDK DES加密结果:"+Hex.encodeHexString(result));//转成16进制
//解密 生成key和key转换 与加密一样
cipher.init(Cipher.DECRYPT_MODE, convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("JDK DES解密结果:"+new String(result));
}
public static void bcDES() throws Exception{
Security.addProvider(new BouncyCastleProvider());
//生成key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
// System.out.println(keyGenerator.getProvider());
keyGenerator.init(56);//指定key size 这里使用默认值56位
SecretKey secreKey= keyGenerator.generateKey();
byte[] bytesKey = secreKey.getEncoded();
//key转换
DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
Key convertSecreKey = factory.generateSecret(desKeySpec);
//加密
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");//加密算法/工作方式/填充方式
cipher.init(Cipher.ENCRYPT_MODE,convertSecreKey);//模式(此处是加密模式)、key
byte[] result = cipher.doFinal(str.getBytes());//参数是要被加密的内容
System.out.println("BC DES加密结果:"+Hex.encodeHexString(result));//转成16进制
//解密 生成key和key转换与加密一样
cipher.init(Cipher.DECRYPT_MODE, convertSecreKey);//模式(此处是解密模式)、key
result=cipher.doFinal(result);
System.out.println("BC DES解密结果:"+new String(result));
}
}
是你想要的么?
追问
您好,这个包是哪里的?import org.bouncycastle.jce.provider.BouncyCastleProvider;
追答
这个算法BouncyCastle也有提供,你使用上面JDK提供的就好,效果是一样的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询