java私人封装的加密jar包以及使用

来源:互联网 发布:apache开源项目 编辑:程序博客网 时间:2024/06/02 08:09

此加密方法使用密匙所以加密之后的字段内容无法做模糊查询。


测试示例结果:


pom.xml 加入jar依赖:

<dependency><groupId>com.daixinlian</groupId><artifactId>daixinlian_commons</artifactId><version>1.0</version></dependency>

jar包内容:

package com.daixinlian.common.encrypt;import java.security.Key;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class DESUtils{  private static Key key;  private static String KEY_STR = "abcdefg";//此处为一个公共密匙    static {    try { KeyGenerator generator = KeyGenerator.getInstance("DESede");      SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");      secureRandom.setSeed(KEY_STR.getBytes());      generator.init(secureRandom);            key = generator.generateKey();      generator = null;    } catch (Exception e) {      throw new RuntimeException(e);    }  }    public static String getEncryptString(String str)  {    if (str == null) {      return null;    }    BASE64Encoder base64en = new BASE64Encoder();    try {      byte[] strBytes = str.getBytes("UTF8");      Cipher cipher = Cipher.getInstance("DESede");      cipher.init(1, key);      byte[] encryptStrBytes = cipher.doFinal(strBytes);      return base64en.encode(encryptStrBytes);    } catch (Exception e) {      throw new RuntimeException(e);    }  }    public static String getDecryptString(String str)  {    if (str == null) {      return null;    }    BASE64Decoder base64De = new BASE64Decoder();    try {      byte[] strBytes = base64De.decodeBuffer(str);      Cipher cipher = Cipher.getInstance("DESede");      cipher.init(2, key);      byte[] decryptStrBytes = cipher.doFinal(strBytes);      return new String(decryptStrBytes, "UTF8");    } catch (Exception e) {      e.printStackTrace(); }    return str;  }}


使用方法:

String encrypStr = DESUtils.getEncryptString("需要加密的字符");//返回加密字符串

String decryptStr = DESUtils.getDecryptString("需要解密的字符"); //返回明文数据



代码操作示例: