java中加密解密工具类
在工作中经常遇到需要加密、解密的场景。例如用户的手机号等信息,在保存到数据库的过程中,需要对数据进行加密。取出时进行解密。
public class DEStool { private String sKey; public DEStool() { //默认构造函数提供默认密钥 sKey = "des@#$12"; } public DEStool(String securityKey) { if (securityKey.length() < 8) { throw new IllegalArgumentException("密钥长度至少8位"); } this.sKey = securityKey; } private Cipher makeCipher() throws Exception{ return Cipher.getInstance("DES"); } private SecretKey makeKeyFactory() throws Exception{ SecretKeyFactory des = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = des.generateSecret(new DESKeySpec(sKey.getBytes())); return secretKey; } public String encrypt(String text) throws Exception{ Cipher cipher = makeCipher(); SecretKey secretKey = makeKeyFactory(); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return new String(Base64.encodeBase64(cipher.doFinal(text.getBytes()))); } public String decrypt(String text) throws Exception{ Cipher cipher = makeCipher(); SecretKey secretKey = makeKeyFactory(); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.decodeBase64(text.getBytes()))); } public static void main(String[] args) { DEStool tool = new DEStool("nice1234"); String content = "中国"; System.out.println("原文内容:"+content); String encrpt = null; try { encrpt = tool.encrypt(content); } catch (Exception e) { e.printStackTrace(); } System.out.println("加密后:"+encrpt + ", 长度=" + encrpt.length()); String descript =null; try { descript = tool.decrypt(encrpt); } catch (Exception e) { e.printStackTrace(); } System.out.println("解密后:" + descript); } }
学习过程中,难免出错。如果您在阅读过程中遇到不太明白,或者有疑问。欢迎指正...联系邮箱crazyCodeLove@163.com
如果觉得有用,想赞助一下请移步赞助页面:赞助一下
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)