Aes加密解密

package com.gsh56.wlhy.service.insurance;


import com.gsh56.common.jpa.dto.BizException;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * AES对称加密和解密
 *
 * @author chenchao
 */
public class AesUtils {

    /**
     * 加密
     * 1.构造密钥生成器
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    public static String AesEncode(String encodeRules, String content) throws Exception {

        //1.构造密钥生成器,指定为AES算法,不区分大小写
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        //2.根据ecnodeRules规则初始化密钥生成器
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encodeRules.getBytes());
        //生成一个128位的随机源,根据传入的字节数组
//            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
        keygen.init(128, random);
        //3.产生原始对称密钥
        SecretKey originalKey = keygen.generateKey();
        //4.获得原始对称密钥的字节数组
        byte[] raw = originalKey.getEncoded();
        //5.根据字节数组生成AES密钥
        SecretKey key = new SecretKeySpec(raw, "AES");
        //6.根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance("AES");
        //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
        cipher.init(Cipher.ENCRYPT_MODE, key);
        //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
        byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
        //9.根据密码器的初始化方式--加密:将数据加密
        byte[] aes = cipher.doFinal(byteEncode);
        return Base64.encodeBase64String(aes);

    }

    /**
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String AESDecode(String encodeRules, String content) throws Exception {

        //1.构造密钥生成器,指定为AES算法,不区分大小写
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        //2.根据ecnodeRules规则初始化密钥生成器
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encodeRules.getBytes());
        //生成一个128位的随机源,根据传入的字节数组
//            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
        keygen.init(128, random);
        //3.产生原始对称密钥
        SecretKey originalKey = keygen.generateKey();
        //4.获得原始对称密钥的字节数组
        byte[] raw = originalKey.getEncoded();
        //5.根据字节数组生成AES密钥
        SecretKey key = new SecretKeySpec(raw, "AES");
        //6.根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance("AES");
        //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
        cipher.init(Cipher.DECRYPT_MODE, key);
        //8.将加密并编码后的内容解码成字节数组
        byte[] byteContent = Base64.decodeBase64(content);
        byte[] byteDecode = cipher.doFinal(byteContent);
        return new String(byteDecode, StandardCharsets.UTF_8);

    }

    /**
     * 加密
     * 1.构造密钥生成器
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    public static String AESECBEncode(String encodeRules, String content) throws Exception {
        SecretKeySpec skey = new SecretKeySpec(encodeRules.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        byte[] crypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String AESECBDecode(String encodeRules, String content) {
        byte[] bits;
        try {
            byte[] str = new BASE64Decoder().decodeBuffer(content);
            SecretKeySpec skey = new SecretKeySpec(encodeRules.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            bits = cipher.doFinal(str);
        } catch (Exception e) {
            throw new BizException("解密失败", e);
        }
        return new String(bits, StandardCharsets.UTF_8);
    }


    /**
     * AES加密
     *
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, byte[] key, String Mode) throws Exception {
        SecretKey aeskey = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(Mode);
        cipher.init(Cipher.ENCRYPT_MODE, aeskey);
        return cipher.doFinal(data);
    }

    /**
     * AES解密
     *
     * @param data 待解密数据
     * @param bKey AES密钥
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] bKey, String Mode) throws Exception {
        SecretKey key = new SecretKeySpec(bKey, "AES");
        Cipher cipher = Cipher.getInstance(Mode);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * Aes加密数据并转成base64
     *
     * @param encodeRules 加密aesKey
     * @param content     加密数据
     * @return
     */
    public static String encryptDataToBase64(String encodeRules, String content) throws Exception {
        String enResult = AesEncode(encodeRules, content);
        return Base64.encodeBase64String(enResult.getBytes(StandardCharsets.UTF_8));
    }

//    public static void main(String[] args) throws Exception {
//        System.out.println(AESECBEncode("d4d35e6ec61a5a289dbd49e21b43b804", "{\"applicantInfo\":{\"applicantId\":\"41302619890903427X\",\"applicantName\":\"投保人名称\",\"contactName\":\"联系人姓名\",\"email\":\"邮箱\",\"phoneNumber\":\"联系人手机号\",\"registAddress\":\"注册详细地址\",\"registPlace\":\"客户注册所在地\"},\"cargoInfo\":{\"amount\":\"货物数量\",\"cargoName\":\"货物名称\",\"cargoValue\":\"1000\",\"category1\":\"货物一级类别\",\"category2\":\"货物二级类别\",\"loadingMode\":\"装载方式\"},\"insuredInfo\":{\"insuredId\":\"证件号码\",\"insuredName\":\"被保险人名称\"},\"orderNo\":\"订单号\",\"transportInfo\":{\"departureDate\":\"启运日期\",\"departurePlace\":\"启运地\",\"destination\":\"目的地\",\"licenseNo\":\"车牌号\",\"transitPlace\":\"中转地\",\"transportMode\":\"运输方式\",\"vehicleModel\":\"车型\",\"waybillNo\":\"运单/提单号码\"}}"));
//        String md5Encode = MD5Util.getMD5Str("{\"applicantInfo\":{\"applicantId\":\"41302619890903427X\",\"applicantName\":\"投保人名称\",\"contactName\":\"联系人姓名\",\"email\":\"邮箱\",\"phoneNumber\":\"联系人手机号\",\"registAddress\":\"注册详细地址\",\"registPlace\":\"客户注册所在地\"},\"cargoInfo\":{\"amount\":\"货物数量\",\"cargoName\":\"货物名称\",\"cargoValue\":\"1000\",\"category1\":\"货物一级类别\",\"category2\":\"货物二级类别\",\"loadingMode\":\"装载方式\"},\"insuredInfo\":{\"insuredId\":\"证件号码\",\"insuredName\":\"被保险人名称\"},\"orderNo\":\"订单号\",\"transportInfo\":{\"departureDate\":\"启运日期\",\"departurePlace\":\"启运地\",\"destination\":\"目的地\",\"licenseNo\":\"车牌号\",\"transitPlace\":\"中转地\",\"transportMode\":\"运输方式\",\"vehicleModel\":\"车型\",\"waybillNo\":\"运单/提单号码\"}}&d4d35e6ec61a5a289dbd49e21b43b804&1516772554057");
//        System.out.println(md5Encode.toUpperCase());
//        System.out.println(AESECBDecode("d4d35e6ec61a5a289dbd49e21b43b804", "q5mlRXL3t9MCtw0wMmpmPFZxW8LEfHtU6dGNnCYZC27tDsHWMd+qp+9MBn7Ol/1B"));
//    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值