java私人封装的加密jar包以及使用
此加密方法使用密匙所以加密之后的字段内容无法做模糊查询。
测试示例结果:
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("需要解密的字符"); //返回明文数据
代码操作示例:
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了