DES加密解密_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > DES加密解密

DES加密解密

 2012/6/29 16:37:12  leeo1124  程序员俱乐部  我要评论(0)
  • 摘要:DES对称加密工具类,支持DES的加密与解密。importjava.security.Key;importjava.security.SecureRandom;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;/***DES加密工具类**@authorLeeo**/publicclassDESUtils
  • 标签:加密解密
DES对称加密工具类,支持DES的加密与解密。

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

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

/**
 * DES加密工具类
 * 
 * @author Leeo
 * 
 */
public class DESUtils {

 private static Key key;
 private static String KEY_STR = "myKey";

 static {
  try {
   KeyGenerator generator = KeyGenerator.getInstance("DES");
   generator.init(new SecureRandom(KEY_STR.getBytes()));
   key = generator.generateKey();
   generator = null;
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 /**
  * 对字符串进行DES加密
  * 
  * @param str
  *            加密字符串
  * @return BASE64编码的加密字符串
  */
 public static String getEncryptString(String str) {
  BASE64Encoder base64en = new BASE64Encoder();
  try {
   byte[] strBytes = str.getBytes("UTF8");
   Cipher cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   byte[] encryptStrBytes = cipher.doFinal(strBytes);
   return base64en.encode(encryptStrBytes);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 /**
  * 对BASE64编码的加密字符串进行解密
  * 
  * @param str
  *            解密字符串
  * @return 解密后的字符串
  */
 public static String getDecryptString(String str) {
  BASE64Decoder base64De = new BASE64Decoder();
  try {
   byte[] strBytes = base64De.decodeBuffer(str);
   Cipher cipher = Cipher.getInstance("DES");
   cipher.init(Cipher.DECRYPT_MODE, key);
   byte[] decryptStrBytes = cipher.doFinal(strBytes);
   return new String(decryptStrBytes, "UTF8");
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}


发表评论
用户名: 匿名