`
aa860326
  • 浏览: 95734 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

DES加密与解密

    博客分类:
  • J2EE
阅读更多

===================使用DES进行加密和解密============================

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.SecureRandom;

 

/**
  * 功能: DES加密
  */
 private String encrypt(String key, String source){
  String algorithm  = "DES";
  byte [] cipherByte   = null;
  
  try {
   DESKeySpec dks = new DESKeySpec(key.getBytes());
   SecureRandom sr = new SecureRandom();
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
   SecretKey securekey = keyFactory.generateSecret(dks);
   Cipher c1 = Cipher.getInstance(algorithm);
   c1.init(Cipher.ENCRYPT_MODE, securekey, sr);
   cipherByte = c1.doFinal(source.getBytes());
  } catch (Exception e) {
   e.printStackTrace();
  }
  BASE64Encoder base64encoder = new BASE64Encoder();
  String encode=base64encoder.encode(cipherByte);
  return encode;
 }
 /**
  * 功能: DES解密
  * @param key
  * @param source
  * @return
  */
 private String decrypt(String key, String source){
  String algorithm  = "DES";
  SecureRandom sr  = new SecureRandom(); 
  String result   = null; 
  try {
   DESKeySpec dks  = new DESKeySpec(key.getBytes());   
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);   
         SecretKey securekey = keyFactory.generateSecret(dks);   
         Cipher cipher  = Cipher.getInstance(algorithm);   
         cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
         BASE64Decoder base64decoder = new BASE64Decoder();
         byte[] encodeByte = base64decoder.decodeBuffer(source);
         byte[] cipherByte = cipher.doFinal(encodeByte);
         result = new String(cipherByte, "GBK");
  } catch (Exception e){
   e.printStackTrace();
  }
        return result;
 }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics