• AES/DES加密工具类


    一、业务场景说明:

      业务功能是实现二维码数据加密传输,并在安卓端和硬件设备端调用,实现动态刷新和时效判断。所以这里使用双层加密,外层BASE64加密,以定位到分钟的时间戳进行加密(二维码时效为一分钟),在被调用时,只需调用端获取(与服务器一直的)本地当前定位到分钟的时间戳进行解密,然后用解密得到的密文数据生成二维码即可,如果不能解密成功,则表示二维码安卓端获取到的当前时间戳已失效。设备端扫描二维码之后,进行内层解密,得到原始数据并进行校验。

    二、依赖

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>${commons-codec.version}</version>
    </dependency>
    

     其余依赖JRE中都有

    三、代码

    package com.xfc.util;// TODO
    
    import java.security.Key;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    
    import org.apache.commons.codec.DecoderException;
    import org.apache.commons.codec.binary.Base32;
    import org.apache.commons.codec.binary.Base64;
    import org.apache.commons.codec.binary.Hex;
    
    public class QREncrypt {
    
        public static Key DEFAULT_KEY = null;
    
        public static final String DEFAULT_SECRET_KEY1 = "?:P)(OL><KI*&UJMNHY^%TGBVFR$#EDCXSW@!QAZ";
        public static final String DEFAULT_SECRET_KEY2 = "1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik,9ol.0p;/";
        public static final String DEFAULT_SECRET_KEY3 = "!QAZ@WSX#EDC$RFV%TGB^YHN&UJM*IK<(OL>)P:?";
        public static final String DEFAULT_SECRET_KEY4 = "1qaz@WSX3edc$RFV5tgb^YHN7ujm*IK<9ol.)P:?";
        public static final String DEFAULT_SECRET_KEY5 = "!QAZ2wsx#EDC4rfv%TGB6yhn&UJM8ik,(OL>0p;/";
        public static final String DEFAULT_SECRET_KEY6 = "1qaz2wsx3edc4rfv5tgb^YHN&UJM*IK<(OL>)P:?";
        public static final String DEFAULT_SECRET_KEY = DEFAULT_SECRET_KEY1;
    
        public static final String AES = "AES";// public static final String DES = "DES";
    
        public static final Base32 base32 = new Base32();
    
        static {
            DEFAULT_KEY = obtainKey(DEFAULT_SECRET_KEY);
        }
    
        /**
         * 获得key
         **/
        public static Key obtainKey(String key) {
            if (key == null) {
                return DEFAULT_KEY;
            }
            KeyGenerator generator = null;
            try {
                generator = KeyGenerator.getInstance(AES);
                //generator.init(new SecureRandom(key.getBytes()));
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
                secureRandom.setSeed(key.getBytes());
                generator.init(secureRandom);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            Key key1 = generator.generateKey();
            generator = null;
            return key1;
        }
    
        /**
         * 加密<br>
         * String明文输入,String密文输出
         */
        public static String encode(String str) {
            return encode64(null, str);
        }
    
        /**
         * 加密<br>
         * String明文输入,String密文输出
         */
        public static String encode64(String key, String str) {
            byte[] bytes = obtainEncode(key, str.getBytes());
            return Base64.encodeBase64URLSafeString(bytes);
        }
    
        /**
         * 加密<br>
         * String明文输入,String密文输出
         */
        public static String encode32(String key, String str) {
            return base32.encodeAsString(obtainEncode(key, str.getBytes())).replaceAll("=", "");
        }
    
        /**
         * 加密<br>
         * String明文输入,String密文输出
         */
        public static String encode16(String key, String str) {
            return Hex.encodeHexString(obtainEncode(key, str.getBytes()));
        }
    
        /**
         * 解密<br>
         * 以String密文输入,String明文输出
         */
        public static String decode(String str) {
            return decode64(null, str);
        }
    
        /**
         * 解密<br>
         * 以String密文输入,String明文输出
         */
        public static String decode64(String key, String str) {
            byte[] bytes = Base64.decodeBase64(str);
            return new String(obtainDecode(key, bytes));
        }
    
        /**
         * 解密<br>
         * 以String密文输入,String明文输出
         */
        public static String decode32(String key, String str) {
            return new String(obtainDecode(key, base32.decode(str)));
        }
    
        /**
         * 解密<br>
         * 以String密文输入,String明文输出
         */
        public static String decode16(String key, String str) {
            try {
                return new String(obtainDecode(key, Hex.decodeHex(str.toCharArray())));
            } catch (DecoderException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 加密<br>
         * 以byte[]明文输入,byte[]密文输出
         */
        private static byte[] obtainEncode(String key, byte[] str) {
            byte[] byteFina = null;
            Cipher cipher;
            try {
                Key key1 = obtainKey(key);
                cipher = Cipher.getInstance(AES);
                cipher.init(Cipher.ENCRYPT_MODE, key1);
                byteFina = cipher.doFinal(str);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cipher = null;
            }
            return byteFina;
        }
    
        /**
         * 解密<br>
         * 以byte[]密文输入,以byte[]明文输出
         */
        private static byte[] obtainDecode(String key, byte[] str) {
            Cipher cipher;
            byte[] byteFina = null;
            try {
                Key key1 = obtainKey(key);
                cipher = Cipher.getInstance(AES);
                cipher.init(Cipher.DECRYPT_MODE, key1);
                byteFina = cipher.doFinal(str);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cipher = null;
            }
            return byteFina;
        }
    
        public static String getQRTimestamp() {
            String time = TimeUtils.formatDate(TimeUtils.DB_TIME_PATTERN_F2);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = time.substring(0, time.lastIndexOf(":") + 1) + "00";
            Date date = new Date();
            try{
                date = sdf.parse(time);
            } catch (Exception e) {
                e.printStackTrace();
            }
            long timestamp = date.getTime();
            return String.valueOf(timestamp);
        }
    
        public static String qrEncrypt(String key, String data) {
            String timestamp = getQRTimestamp();
            String s = encode32(key, data);
            String newData = timestamp + ";" + s;
            System.out.println("newData = " + newData);
            String s1 = encode64(timestamp, newData);
            return s1;
        }
    
        public static String qrDecrypt(String key, String data) {
            String timestamp = getQRTimestamp();
            String n1 = decode64(timestamp, data);
            String orignTimestamp = n1.split(";")[0];
            String m4 = n1.split(";")[1];
            String n = decode32(key, m4);
            return n;
        }
    public static void main(String[] args) {
            String data = "{'username': 'admin', 'password': '123456'}";
            System.out.println("加密前的数据 = " + data);
            String s = qrEncrypt(DEFAULT_SECRET_KEY, data);
            System.out.println("加密后的数据 = " + s);
            String ddd = qrDecrypt(DEFAULT_SECRET_KEY, s);
            System.out.println("解密后的数据 = " + ddd);
            System.out.println("解密后的数据是否与原数据一致: ------ " + data.equals(ddd));
        }
    }

    四、测试 main() 输出结果

  • 相关阅读:
    zfs
    targetcli
    targetcli
    自动制linux iso包
    yum解决重复包,依赖冲突问题
    lvm相关
    vmware相关
    配置本地yum源
    k8s安装prometheus监控
    流水线基础-Pipeline
  • 原文地址:https://www.cnblogs.com/xfc-exclave/p/10817762.html
Copyright © 2020-2023  润新知