概述
工作中用到的,希望对大家有帮助.
- import java.security.Key;
- import java.security.spec.AlgorithmParameterSpec;
- import javax.crypto.Cipher;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESKeySpec;
- import javax.crypto.spec.IvParameterSpec;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- public class CryptoTools {
- private static final String key_ = "ising@ws"; //
- private static final byte [] DESkey = key_.getBytes();//设置密钥,略去
- private static final byte[] DESIV = { (byte)0x12,(byte) 0x34, (byte)0x56, (byte)0x78, (byte)0x90,
- (byte)0xAB, (byte)0xCD,(byte) 0xEF };//设置向量,略去
- private static AlgorithmParameterSpec iv =null;//加密算法的参数接口,IvParameterSpec是它的一个实现
- private static Key key =null;
- public CryptoTools() throws Exception {
- DESKeySpec keySpec = new DESKeySpec(DESkey);//设置密钥参数
- iv = new IvParameterSpec(DESIV);//设置向量
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");//获得密钥工厂
- key = keyFactory.generateSecret(keySpec);//得到密钥对象
- }
- public String encode(String data) throws Exception {
- Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");//得到加密对象Cipher
- enCipher.init(Cipher.ENCRYPT_MODE,key,iv);//设置工作模式为加密模式,给出密钥和向量
- byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
- BASE64Encoder base64Encoder = new BASE64Encoder();
- return base64Encoder.encode(pasByte);
- }
- public String decode(String data) throws Exception{
- Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
- deCipher.init(Cipher.DECRYPT_MODE,key,iv);
- BASE64Decoder base64Decoder = new BASE64Decoder();
- byte[] pasByte=deCipher.doFinal(base64Decoder.decodeBuffer(data));
- return new String(pasByte,"UTF-8");
- }
- public static void main(String[] args) throws Exception{
- String value = "hello";
- CryptoTools tools =new CryptoTools();
- System.out.println(tools.encode(value));
- System.out.println("解密"+tools.decode(tools.encode(value)));
- }
- }
- }
修改后的:
- public String encode(String data) throws Exception
- {
- byte [] DESkey = key_.getBytes();
- byte[] DESIV = { (byte)0x12,(byte) 0x34, (byte)0x56, (byte)0x78, (byte)0x90,(byte)0xAB, (byte)0xCD,(byte) 0xEF };
- DESKeySpec keySpec = new DESKeySpec(DESkey);
- iv = new IvParameterSpec(DESIV);
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- key = keyFactory.generateSecret(keySpec);
- SecureRandom sr = new SecureRandom();
- Cipher enCipher = Cipher.getInstance("DES");
- enCipher.init(Cipher.ENCRYPT_MODE, key,sr);
- byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
- BASE64Encoder base64Encoder = new BASE64Encoder();
- return base64Encoder.encode(pasByte);
- }
2009-04-30
最后
以上就是机灵西装为你收集整理的java的des加密的全部内容,希望文章能够帮你解决java的des加密所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复