java 加密工具类

来源:互联网 发布:thinkphp3.2博客源码 编辑:程序博客网 时间:2024/05/01 14:47
package com.zf.test;import java.security.Key;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;/** * 字符串加解密 * @author zhoufeng * */public class MySecurity {private  static String strDefaultKey = "zhoufeng";private Cipher entyptCipher = null ;private Cipher decryptCipher = null ;public MySecurity() throws Exception{ this(strDefaultKey);}public MySecurity(String strKey)throws Exception{Key key = getKey(strKey.getBytes());entyptCipher = Cipher.getInstance("DES");entyptCipher.init(Cipher.ENCRYPT_MODE, key);decryptCipher = Cipher.getInstance("DES");decryptCipher.init(Cipher.DECRYPT_MODE, key);}private Key getKey(byte[] arrBTmp) throws Exception{byte[] arrB = new byte[8];for (int i = 0; i < arrB.length && i < arrBTmp.length; i++) {arrB[i] = arrBTmp[i];}Key key = new SecretKeySpec(arrB, "DES");return key ;}/* 加密字符串 */public  String entyptStr(String str) throws Exception{//注释部分也是一种实现方式/*byte[] arryB = str.getBytes();int len = arryB.length;StringBuilder sb = new StringBuilder(len * 2);for (int i = 0; i < len ; i++) {int intTmp = arryB[i];while(intTmp < 0 ){intTmp += 256 ;}if(intTmp < 16){sb.append("0");}sb.append(Integer.toString(intTmp ,16));}return sb.toString();*/return new String(entyptCipher.doFinal(str.getBytes("utf-8")) ,"iso-8859-1");}/* 字符串解密 */public  String decypt(String strIn) throws Exception{//注释部分也是一种实现方式/*byte arrB[] = strIn.getBytes();int len = arrB.length;byte arrOut [] = new byte[len / 2] ;for (int i = 0; i < len ; i+= 2) {String strTmp = new String(arrB , i , 2);arrOut[i / 2] = (byte)Integer.parseInt(strTmp , 16);} return new String(arrOut);*/return new String(decryptCipher.doFinal(strIn.getBytes("iso-8859-1")) ,"utf-8");}public static void main(String[] args)throws Exception {MySecurity ms = new MySecurity();String str = "中国";String entyptStr = ms.entyptStr(str) ;String decypt = ms.decypt(entyptStr) ; System.out.println("加密后:" + entyptStr);System.out.println("解密后:" + decypt);}}


原创粉丝点击