• AES加解密工具类


    package com.panchan.tsmese.utils;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.commons.codec.binary.Base64;
    
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * @Description AES加解密
     * @version 1.0
     * @since JDK1.8
     * @author XueXiangDong
     * @Created on 2018年11月20日
     */
    @Slf4j
    public class AesUtil {
    
        /**
         * 加密
         * @param sSrc 需要加密的参数
         * @param sKey 秘钥 可以为空 为空则默认秘钥
         * @return
         * @throws Exception
         */
        public static String Encrypt(String sSrc, String sKey) throws Exception {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            String other = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(encrypted);
            return other;// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
        }
    
        /**
         * 解密
         * @param <T>
         * @param sSrc 需要解密的参数
         * @param sKey 秘钥 可以为空 为空则默认秘钥
         * @return
         * @throws Exception
         */
        public static String Decrypt(String sSrc, String sKey) throws Exception {
            try {
                byte[] raw = sKey.getBytes("utf-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] encrypted1 = new Base64().decode(sSrc);// 先用base64解密
                try {
                    byte[] original = cipher.doFinal(encrypted1);
                    String originalString = new String(original, "utf-8");
                    log.info("解密后的请求报文为{}", originalString);
                    return originalString;
                } catch (Exception e) {
                    log.error(e.getMessage());
                    return null;
                }
            } catch (Exception ex) {
                log.error(ex.getMessage());
                return null;
            }
        }
    }
  • 相关阅读:
    android button click事件
    springmvc 多方法访问
    hibernate的save和saveOrUpdate方法
    总结的方法
    oracle 存储过程
    ibatis学习笔记(四)>>>>>>>ibatis使用实例
    ibatis学习笔记(二)>>>>>>>sqlMapConfig.xml文件详解
    ibatis学习笔记(三)>>>>>>>java实体跟表映射.xml文件详解
    ibatis学习笔记(一)>>>>>>>sqlMapConfig.xml文件详解
    spring
  • 原文地址:https://www.cnblogs.com/huyanlon/p/10641200.html
Copyright © 2020-2023  润新知