zoukankan      html  css  js  c++  java
  • DES加解密工具类

    这两天在跟友商对接接口,在对外暴露接口的时候,因为友商不需要登录即可访问对于系统来说存在安全隐患,所以需要友商在调用接口的时候需要将数据加密,系统解密验证后才执行业务。所有的加密方式并不是万能的,只是增加了破解的成本高低而已~~

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import java.io.UnsupportedEncodingException;
    import java.security.SecureRandom;
    
    public class DesEncryptUtils {
    
        public static final String KEY = "marklogzhu202306111454";
    
        /**
         * 加密
         *
         * @param content
         *            需要加密的内容
         * @param password
         *            加密密码
         * @return
         */
        public static byte[] encrypt(String content, String password) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(password.getBytes());
                kgen.init(128, random);
    //            kgen.init(128, new SecureRandom(password.getBytes()));
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return result; // 加密
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 解密
         *
         * @param content
         *            待解密内容
         * @param password
         *            解密密钥
         * @return
         */
        public static byte[] decrypt(byte[] content, String password) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(password.getBytes());
                kgen.init(128, random);
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器
                cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(content);
                return result; // 加密
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 将二进制转换成16进制
         *
         * @param buf
         * @return
         */
        public static String parseByte2HexStr(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                String hex = Integer.toHexString(buf[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        }
    
        /**
         * 将16进制转换为二进制
         *
         * @param hexStr
         * @return
         */
        public static byte[] parseHexStr2Byte(String hexStr) {
            if (hexStr.length() < 1)
                return null;
            byte[] result = new byte[hexStr.length() / 2];
            for (int i = 0; i < hexStr.length() / 2; i++) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        }
    
        /**
         * 加密
         *
         * @param content
         *            需要加密的内容
         * @param password
         *            加密密码
         * @return
         */
        public static byte[] encrypt2(String content, String password) {
            try {
                SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
                byte[] byteContent = content.getBytes("utf-8");
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
                byte[] result = cipher.doFinal(byteContent);
                return result; // 加密
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static String getDecryptResult(String bizData) throws UnsupportedEncodingException {
            byte[] decode = DesEncryptUtils.parseHexStr2Byte(bizData);
            byte[] decryptResult = DesEncryptUtils.decrypt(decode, DesEncryptUtils.KEY);
            String decryptStr = new String(decryptResult, "UTF-8");
            return decryptStr;
        }
    
        public static void main(String[] args) throws UnsupportedEncodingException {
            String content = "hello 中国--2018";
            // 加密
            System.out.println("加密前:" + content);
            byte[] encode = DesEncryptUtils.encrypt(content, DesEncryptUtils.KEY);
    
            //传输过程,不转成16进制的字符串,程序就会崩溃掉
            String code = DesEncryptUtils.parseByte2HexStr(encode);
            System.out.println("密文字符串:" + code);
            byte[] decode = DesEncryptUtils.parseHexStr2Byte(code);
            // 解密
            byte[] decryptResult = DesEncryptUtils.decrypt(decode, DesEncryptUtils.KEY);
            System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不转码会乱码
    
        }
    }
    
    

    启动运行

    加密前:hello 中国--2018
    密文字符串:3461AA5F7D3434A58C47F4BFBE2AA9D4953E5E3D5717D2EF6ABAD1E421C82B7E
    解密后:hello 中国--2018
    

    遇到的问题

    现象

    在window 环境下加解密都可以,但是 Linux 下解密报空指针异常。

    原因

    SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264

    解决办法

    将如下代码替换:

    kgen.init(128, new SecureRandom(password.getBytes()));
    

    替换为:

    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(password.getBytes());
    kgen.init(128, random);
    
  • 相关阅读:
    MATLAB学习1 之画图函数
    innobackupex 出现Unrecognized character x01; marked by
    innobackupex 出现Unrecognized character x01; marked by
    innobackupex 出现Unrecognized character x01; marked by
    innobackupex 出现Unrecognized character x01; marked by
    企业云桌面-03-安装第1个企业 CA-013-CA01
    python 串行执行和并行执行
    cx_Oracle 查询 传参
    运维工程师要失业了?抛开噱头与调侃,闲聊我心中的运维!
    迭代器
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/11400229.html
Copyright © 2011-2022 走看看