zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    剖析并利用Visual Studio Code在Mac上编译、调试c#程序【转】
    算法题—百灯判熄
    聪明的情侣算法题
    C#中&与&&的区别
    C# 日期格式精确到毫秒 【转】
    C#关于窗体的keysdown事件,无法获取到焦点
    百度,迅雷,华为,阿里巴巴笔试面试
    对 Linux 新手非常有用的 20 个命令
    阿里面试题2015
    Ant工具 ant的安装与配置 ant作用
  • 原文地址:https://www.cnblogs.com/zhaopengcheng/p/7245230.html
Copyright © 2011-2022 走看看