加密工具类

------------------------------------------------------------------------------------

1.引入依赖

 <!-- 加密工具包 包含MD5、RSA、AES等加密方式-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
        </dependency>

AES加、解密算法工具类

package pers.darcy.flower.utils.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * AES加、解密算法工具类
 */
public class AESUtil {
    /**
     * 加密算法AES
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * key的长度,Wrong key size: must be equal to 128, 192 or 256
     * 传入时需要16、24、36
     */
    private static final Integer KEY_LENGTH = 16 * 8;

    /**
     * 算法名称/加密模式/数据填充方式
     * 默认:AES/ECB/PKCS5Padding
     */
    private static final String ALGORITHMS = "AES/ECB/PKCS5Padding";

    /**
     * 后端AES的key,由静态代码块赋值
     */
    public static String key;

    static {
        key = getKey();
    }

    /**
     * 获取key
     */
    public static String getKey() {
        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < KEY_LENGTH / 8; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(3);
            switch (type) {
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
                    break;
                case 1:
                    //ASCII在65-90之间为大写,获取大写随机
                    uid.append((char) (rd.nextInt(25) + 65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写,获取小写随机
                    uid.append((char) (rd.nextInt(25) + 97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        //设置Cipher对象
        Cipher cipher = Cipher.getInstance(ALGORITHMS,new BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), KEY_ALGORITHM));

        //调用doFinal
        byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));

        // 转base64
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        //base64格式的key字符串转byte
        byte[] decodeBase64 = Base64.decodeBase64(encryptStr);

        //设置Cipher对象
        Cipher cipher = Cipher.getInstance(ALGORITHMS,new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), KEY_ALGORITHM));

        //调用doFinal解密
        byte[] decryptBytes = cipher.doFinal(decodeBase64);
        return new String(decryptBytes);
    }


//    public static void main(String[] args) {
//        //16位
//        String key = "MIGfMA0GCSqGSIb3";
//
//        //字符串
//        String str = "huanzi.qch@qq.com:欢子";
//        try {
//            //加密
//            String encrypt = AESUtil.encrypt(str, key);
//            //解密
//            String decrypt = AESUtil.decrypt(encrypt, key);
//            System.out.println("加密前:" + str);
//            System.out.println("加密后:" + encrypt);
//            System.out.println("解密后:" + decrypt);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    public static void main(String[] args) {
        //16位
        String key = "MIGfMA0GCSqGSIb3";

        //复杂对象
        Map<String,Object> userMap = new HashMap<>(2);
        userMap.put("username","123456");
        userMap.put("password","111111");
        try {
            //加密
            String encrypt = AESUtil.encrypt(userMap.toString(), key);
            //解密
            String decrypt = AESUtil.decrypt(encrypt, key);
            System.out.println("加密前:" + userMap.toString());
            System.out.println("加密后:" + encrypt);
            System.out.println("解密后:" + decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Base64加密解密 工具类

package pers.darcy.flower.utils.util;

import org.apache.commons.codec.binary.Base64;

/**
 * Base64加密解密 工具类
 *
 * @author wbw
 * @version 1.0
 * @since 1.0
 */
public abstract class Base64Util {

    /**
     * 字符编码
     */
    private final static String ENCODING = "UTF-8";

    /**
     * 方法描述: Base64编码
     *
     * @param data 待编码数据
     * @return java.lang.String
     * @author wqf
     * @date 2022/1/19 11:54
     */
    public static String encode(String data) throws Exception {

        // 执行编码
        byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));

        return new String(b, ENCODING);
    }


    /**
     * 方法描述: Base64安全编码<br>
     * 遵循RFC 2045实现
     *
     * @param data 待编码数据
     * @return java.lang.String
     * @author wqf
     * @date 2022/1/19 11:53
     */
    public static String encodeSafe(String data) throws Exception {

        // 执行编码
        byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);

        return new String(b, ENCODING);
    }

    /**
     * 方法描述: Base64解码
     *
     * @param data 待解码数据
     * @return java.lang.String
     * @author wqf
     * @date 2022/1/19 11:53
     */
    public static String decode(String data) throws Exception {
        // 执行解码
        byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));
        return new String(b, ENCODING);
    }
}

DES工具类

package pers.darcy.flower.utils.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

/**
 * DES安全编码组件
 *
 * @author wbw
 * @version 1.0
 */
public abstract class DESUtil {
    static {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
    }

    //new BouncyCastleProvider();后端加解密中,不能在代码里new BouncyCastleProvider(),JceSecurity. getVerificationResult内部会进行判断,如果是新值,则每次都会put到map中,导致内存缓便被耗尽,程序假死崩溃
   // private static final BouncyCastleProvider BOUNCY_CASTLE_PROVIDER=new BouncyCastleProvider();

    /**
     * 密钥算法 <br>
     * Java 6 只支持56bit密钥 <br>
     * Bouncy Castle 支持64bit密钥
     */
    private static final String KEY_ALGORITHM = "DES";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     */
    private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";

    /**
     * 转换密钥
     *
     * @param key 二进制密钥
     * @return Key 密钥
     * @throws Exception
     */
    private static Key toKey(byte[] key) throws Exception {
        // 实例化DES密钥材料
        DESKeySpec dks = new DESKeySpec(key);
        // 实例化秘密密钥工厂
        SecretKeyFactory keyFactory = SecretKeyFactory
                .getInstance(KEY_ALGORITHM);
        // 生成秘密密钥
        return keyFactory.generateSecret(dks);
    }

    /**
     * 方法描述: 解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[]
     * @author wqf
     * @date 2022/1/19 14:03
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {

        // 还原密钥
        Key k = toKey(key);

        // 实例化
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

        // 初始化,设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, k);

        // 执行操作
        return cipher.doFinal(data);
    }

    /**
     * 方法描述:  加密
     *
     * @param data 待加密数据
     * @param key  密钥
     * @return byte[]
     * @author wqf
     * @date 2022/1/19 14:03
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 还原密钥
        Key k = toKey(key);
        // 实例化
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化,设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, k);
        // 执行操作
        return cipher.doFinal(data);
    }

    /**
     * 方法描述: 生成密钥
     *
     * @return byte[]
     * @author wqf
     * @date 2022/1/19 14:03
     */
    public static byte[] initKey() throws Exception {
        //实例化密钥生成器,若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        //初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
        kg.init(56, new SecureRandom());
        // 生成秘密密钥
        SecretKey secretKey = kg.generateKey();
        // 获得密钥的二进制编码形式
        return secretKey.getEncoded();
    }

    public static byte[] initKey(String seed) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));
        kg.init(secureRandom);
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }
}

MD5工具类

package pers.darcy.flower.utils.util;

import org.apache.commons.codec.digest.DigestUtils;
 
/**
 * MD5加密组件
 * 
 * @author wbw
 * @version 1.0
 * @since 1.0
 */
public abstract class MD5Util {

    /**
     * 方法描述: MD5加密
     *
     * @param data 待加密数据
     * @return byte[]
     * @author wqf
     * @date 2022/1/19 11:54
     */
    public static byte[] encodeMD5(String data) throws Exception {
        // 执行消息摘要
        return DigestUtils.md5(data);
    }

    /**
     * 方法描述: MD5加密
     *
     * @param data 待加密数据
     * @return java.lang.String
     * @author wqf
     * @date 2022/1/19 11:54
     */
    public static String encodeMD5Hex(String data) {
        // 执行消息摘要
        return DigestUtils.md5Hex(data);
    }
}

RSA加、解密算法工具类

package cn.huanzi.ims.util;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA加、解密算法工具类
 */
public class RSAUtil {

    /**
     * 加密算法AES
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 算法名称/加密模式/数据填充方式
     * 默认:RSA/ECB/PKCS1Padding
     */
    private static final String ALGORITHMS = "RSA/ECB/PKCS1Padding";

    /**
     * Map获取公钥的key
     */
    private static final String PUBLIC_KEY = "publicKey";

    /**
     * Map获取私钥的key
     */
    private static final String PRIVATE_KEY = "privateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写:  245 256
     */
    private static final int INITIALIZE_LENGTH = 1024;

    /**
     * 后端RSA的密钥对(公钥和私钥)Map,由静态代码块赋值
     */
    private static Map<String, Object> genKeyPair = new HashMap<>();

    static {
        try {
            genKeyPair.putAll(genKeyPair());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥对(公钥和私钥)
     */
    private static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(INITIALIZE_LENGTH);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        //公钥
        keyMap.put(PUBLIC_KEY, publicKey);
        //私钥
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
        //base64格式的key字符串转Key对象
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

        //设置加密、填充方式
        /*
            如需使用更多加密、填充方式,引入
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk16</artifactId>
                <version>1.46</version>
            </dependency>
            并改成
            Cipher cipher = Cipher.getInstance(ALGORITHMS ,new BouncyCastleProvider());
         */
        Cipher cipher = Cipher.getInstance(ALGORITHMS);
        cipher.init(Cipher.DECRYPT_MODE, privateK);

        //分段进行解密操作
        return encryptAndDecryptOfSubsection(encryptedData, cipher, MAX_DECRYPT_BLOCK);
    }

    /**
     * 公钥加密
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        //base64格式的key字符串转Key对象
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);

        //设置加密、填充方式
        /*
            如需使用更多加密、填充方式,引入
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk16</artifactId>
                <version>1.46</version>
            </dependency>
            并改成
            Cipher cipher = Cipher.getInstance(ALGORITHMS ,new BouncyCastleProvider());
         */
        Cipher cipher = Cipher.getInstance(ALGORITHMS);
        cipher.init(Cipher.ENCRYPT_MODE, publicK);

        //分段进行加密操作
        return encryptAndDecryptOfSubsection(data, cipher, MAX_ENCRYPT_BLOCK);
    }

    /**
     * 获取私钥
     */
    public static String getPrivateKey() {
        Key key = (Key) genKeyPair.get(PRIVATE_KEY);
        return Base64.encodeBase64String(key.getEncoded());
    }

    /**
     * 获取公钥
     */
    public static String getPublicKey() {
        Key key = (Key) genKeyPair.get(PUBLIC_KEY);
        return Base64.encodeBase64String(key.getEncoded());
    }

    /**
     * 分段进行加密、解密操作
     */
    private static byte[] encryptAndDecryptOfSubsection(byte[] data, Cipher cipher, int encryptBlock) throws Exception {
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > encryptBlock) {
                cache = cipher.doFinal(data, offSet, encryptBlock);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * encryptBlock;
        }
        byte[] toByteArray = out.toByteArray();
        out.close();
        return toByteArray;
    }
//
//    public static void main(String[] args) {
//        //字符串
//        String str = "huanzi.qch@qq.com:欢子";
//        try {
//            System.out.println("私钥:" + RSAUtil.getPrivateKey());
//            System.out.println("公钥:" + RSAUtil.getPublicKey());
//
//            //公钥加密
//            byte[] ciphertext = RSAUtil.encryptByPublicKey(str.getBytes(), RSAUtil.getPublicKey());
//            //私钥解密
//            byte[] plaintext = RSAUtil.decryptByPrivateKey(ciphertext, RSAUtil.getPrivateKey());
//
//            System.out.println("公钥加密前:" + str);
//            System.out.println("公钥加密后:" + Base64.encodeBase64String(ciphertext));
//            System.out.println("私钥解密后:" + new String(plaintext));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public static void main(String[] args) {
        //复杂对象
        Map<String,Object> userMap = new HashMap<>(2);
        userMap.put("username","123456");
        userMap.put("password","111111");
        try {
            System.out.println("私钥:" + RSAUtil.getPrivateKey());
            System.out.println("公钥:" + RSAUtil.getPublicKey());

            //公钥加密
            byte[] ciphertext = RSAUtil.encryptByPublicKey(userMap.toString().getBytes(), RSAUtil.getPublicKey());
            //私钥解密
            byte[] plaintext = RSAUtil.decryptByPrivateKey(ciphertext, RSAUtil.getPrivateKey());

            System.out.println("公钥加密前:" + userMap.toString());
            System.out.println("公钥加密后:" + Base64.encodeBase64String(ciphertext));
            System.out.println("私钥解密后:" + new String(plaintext));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

------------------------------------------------------------------------------------

package com.lakala.boss.api.utils;

import com.lakala.boss.api.security.CAP12CertTool;
import com.lakala.boss.api.security.RSASignUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @Project: boss-sdk
 * @Package: com.lakala.boss.api.utils
 * @Description: 加解密工具类
 * @author: LXF
 * @date Date: 2019年10月23日 18:00
 * @version: V1.0.0
 */
public class KeyUtil {

    private KeyUtil(){}

    /**
     * 加密敏感数据
     * @param str
     * @param secretKey
     * @return
     * @throws InvalidEncryptedKeyException
     */
    public static String encryptPrivateData(String str, String secretKey) throws InvalidEncryptedKeyException {
        if(StringUtils.isNotBlank(str) && StringUtils.isNotBlank(secretKey)) {
            return AESUtil.aesEncrypt(str, secretKey);
        } else {
            return null;
        }

    }

    /**
     * 解密敏感数据
     * @param str
     * @param secretKey
     * @return
     * @throws InvalidEncryptedKeyException
     */
    public static String decryptPrivateData(String str, String secretKey) throws InvalidEncryptedKeyException {
        if(StringUtils.isNotBlank(str) && StringUtils.isNotBlank(secretKey)) {
            return AESUtil.aesDecrypt(str, secretKey);
        } else {
            return null;
        }

    }

    /**
     * 加密临时密钥
     * @param client
     * @param secretKey
     * @return
     */
    public static String encryptSecretKey(BossClient client, String secretKey){
        if(ObjectUtils.isEmpty(client) || StringUtils.isBlank(secretKey)){
            return null;
        }

        CAP12CertTool cap12CertTool = client.getRsaSignUtil().getCap12CertTool();
        return RSASignUtil.rsaEcbEncryptBase64((RSAPrivateKey) cap12CertTool.getPrivateKey(), secretKey.getBytes());
    }

    /**
     * 解密临时密钥
     * @param client
     * @param encryptSecretKey
     * @return
     */
    public static String decryptSecretKey(BossClient client, String encryptSecretKey){
        if(ObjectUtils.isEmpty(client) || StringUtils.isBlank(encryptSecretKey)){
            return null;
        }
        CAP12CertTool cap12CertTool = client.getRsaSignUtil().getCap12CertTool();
        return RSASignUtil.rsaEcbDecryptBase64((RSAPublicKey) cap12CertTool.getPublicKey(), encryptSecretKey);
    }

    /**
     * 解密临时密钥
     * @param client
     * @param encryptSecretKey
     * @return
     */
    public static String decryptSecretKeyByPrivateKey(BossClient client, String encryptSecretKey){
        if(ObjectUtils.isEmpty(client) || StringUtils.isBlank(encryptSecretKey)){
            return null;
        }
        CAP12CertTool cap12CertTool = client.getRsaSignUtil().getCap12CertTool();
        return RSASignUtil.rsaEcbDecryptBase64((RSAPrivateKey) cap12CertTool.getPrivateKey(), encryptSecretKey);
    }



}

package com.lakala.boss.api.security;

import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

/**
 * 密钥工具类
 */
public class CAP12CertTool {

    private SignedPack signedPack;

    public CAP12CertTool(InputStream fileInputStream, String keyPass) throws SecurityException {
        signedPack = this.getP12(fileInputStream, keyPass);
    }

    public CAP12CertTool(String path, String keyPass) throws SecurityException, FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(new File(path));
        signedPack = this.getP12(fileInputStream, keyPass);
    }

    public static SignedPack getKeyPkcs12(String keyfile, String keypwd) {
        KeyStore keyStore = getKeyStore(keyfile, keypwd, "PKCS12");
        PrivateKey privateKey = null;

        try {
            Enumeration<String> aliasenum = keyStore.aliases();
            String keyAlias = null;
            if (aliasenum.hasMoreElements()) {
                keyAlias = (String) aliasenum.nextElement();
            }

            privateKey = (PrivateKey) keyStore.getKey(keyAlias, keypwd.toCharArray());
            Certificate cert = keyStore.getCertificate(keyAlias);
            PublicKey publicKey = cert.getPublicKey();
            SignedPack sp = new SignedPack();
            sp.setCert((X509Certificate) cert);
            sp.setPubKey(publicKey);
            sp.setPriKey(privateKey);
            return sp;
        } catch (Exception e) {
            throw new IllegalArgumentException("Fail: get private key from private certificate", e);
        }
    }

    private static KeyStore getKeyStore(String keyfile, String keypwd, String type) {
        FileInputStream fis = null;

        KeyStore keyStoreOut;
        try {
            KeyStore keyStore = null;
            keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(keyfile);
            char[] nPassword = null != keypwd && !"".equals(keypwd.trim()) ? keypwd.toCharArray() : null;
            keyStore.load(fis, nPassword);
            fis.close();
            keyStoreOut = keyStore;
        } catch (Exception e) {
            if (Security.getProvider("BC") == null) {
                throw new IllegalArgumentException("BC Provider not installed.", e);
            }

            throw new IllegalArgumentException("Fail: load privateKey certificate", e);
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (Exception ignored) {
                }
            }
        }

        return keyStoreOut;
    }

    private SignedPack getP12(InputStream fileInputStream, String keyPass) throws SecurityException {
        SignedPack sp = new SignedPack();

        try {
            KeyStore ks = KeyStore.getInstance("PKCS12");
            char[] nPassword = (char[]) null;
            if (keyPass != null && !keyPass.trim().equals("")) {
                nPassword = keyPass.toCharArray();
            } else {
                nPassword = (char[]) null;
            }

            ks.load(fileInputStream, nPassword);
            Enumeration enum2 = ks.aliases();
            String keyAlias = null;
            if (enum2.hasMoreElements()) {
                keyAlias = (String) enum2.nextElement();
            }

            PrivateKey priKey = (PrivateKey) ks.getKey(keyAlias, nPassword);
            Certificate cert = ks.getCertificate(keyAlias);
            PublicKey pubKey = cert.getPublicKey();
            sp.setCert((X509Certificate) cert);
            sp.setPubKey(pubKey);
            sp.setPriKey(priKey);
        } catch (Exception var13) {
            var13.printStackTrace();
            throw new SecurityException(var13.getMessage());
        }

        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException var12) {
                ;
            }
        }

        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException var11) {
                ;
            }
        }

        return sp;
    }

    public X509Certificate getCert() {
        return signedPack.getCert();
    }

    public PublicKey getPublicKey() {
        return signedPack.getPubKey();
    }

    public PrivateKey getPrivateKey() {
        return signedPack.getPriKey();
    }

    public byte[] getSignData(byte[] indata) throws SecurityException {
        byte[] res = (byte[]) null;

        try {
            Signature signet = Signature.getInstance("SHA256WITHRSA");
            signet.initSign(this.getPrivateKey());
            signet.update(indata);
            res = signet.sign();
            return res;
        } catch (InvalidKeyException var4) {
            throw new SecurityException(var4.getMessage());
        } catch (NoSuchAlgorithmException var5) {
            throw new SecurityException(var5.getMessage());
        } catch (SignatureException var6) {
            throw new SecurityException(var6.getMessage());
        }
    }

}

package com.lakala.boss.api.security;

import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.*;

public class RSASignUtil {
    private String hexCert = null;

    private CAP12CertTool cap12CertTool;

    public RSASignUtil(String certFilePath, String password) {
        try {
            cap12CertTool = new CAP12CertTool(certFilePath, password);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static PublicKey getPublicKeyfromPath(String svrCertpath) throws SecurityException {
        X509Certificate cert = null;
        FileInputStream inStream = null;

        try {
            inStream = new FileInputStream(new File(svrCertpath));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = (X509Certificate) cf.generateCertificate(inStream);
        } catch (CertificateException var4) {
            throw new SecurityException(var4.getMessage());
        } catch (FileNotFoundException var5) {
            throw new SecurityException(var5.getMessage());
        }

        return cert.getPublicKey();
    }

    public static byte[] checkPEM(byte[] paramArrayOfByte) {
        String str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+= \r\n-";

        for (int i = 0; i < paramArrayOfByte.length; ++i) {
            if (str1.indexOf(paramArrayOfByte[i]) == -1) {
                return null;
            }
        }

        StringBuffer localStringBuffer = new StringBuffer(paramArrayOfByte.length);
        String str2 = new String(paramArrayOfByte);

        for (int j = 0; j < str2.length(); ++j) {
            if (str2.charAt(j) != ' ' && str2.charAt(j) != '\r' && str2.charAt(j) != '\n') {
                localStringBuffer.append(str2.charAt(j));
            }
        }

        return localStringBuffer.toString().getBytes();
    }

    /**
     * RSA 加密
     *
     * @param privateKey 私钥
     * @param data       待加密数据
     * @return 加密结果
     */
    public static String rsaEcbEncryptBase64(RSAPrivateKey privateKey, byte[] data) {
        byte[] res = rsaEcbEncrypt(privateKey, data);
        return com.lakala.boss.api.utils.Base64.encode(res);
    }

    /**
     * 加密
     *
     * @param privateKey 私钥
     * @param data       加密数据
     * @return 加密结果
     */
    public static byte[] rsaEcbEncrypt(RSAPrivateKey privateKey, byte[] data) {
        String algorithm = "RSA/ECB/PKCS1Padding";
        if (privateKey == null) {
            throw new IllegalArgumentException("publicKey is null");
        } else {
            try {
                Cipher cipher = Cipher.getInstance(algorithm);
                cipher.init(1, privateKey);
                return cipher.doFinal(data);
            } catch (Exception e) {
                throw new IllegalArgumentException("Fail: RSA Ecb Encrypt", e);
            }
        }
    }

    /**
     * 解密
     *
     * @param publicKey 公钥
     * @param data      待解密数据
     * @return 解密后数据
     */
    public static String rsaEcbDecryptBase64(RSAPublicKey publicKey, String data) {
        byte[] res = rsaEcbDecrypt(publicKey, com.lakala.boss.api.utils.Base64.decode(data));
        return new String(res);
    }

    /**
     * 解密
     *
     * @param privateKey 私钥
     * @param data       待解密数据
     * @return 解密后数据
     */
    public static String rsaEcbDecryptBase64(RSAPrivateKey privateKey, String data) {
        byte[] res = rsaEcbDecrypt(privateKey, com.lakala.boss.api.utils.Base64.decode(data));
        return new String(res);
    }

    /**
     * 解密
     *
     * @param publicKey 公钥
     * @param data      待解密数据
     * @return 解密后数据
     */
    public static byte[] rsaEcbDecrypt(RSAPublicKey publicKey, byte[] data) {

        if (publicKey == null) {
            throw new IllegalArgumentException("privateKey is null");
        } else {
            Object var3 = null;

            try {
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(2, publicKey);
                return cipher.doFinal(data);
            } catch (Exception e) {
                throw new IllegalArgumentException("Fail: RSA Ecb Decrypt", e);
            }
        }
    }

    /**
     * 解密
     *
     * @param privateKey 私钥
     * @param data       待解密数据
     * @return 解密后数据
     */
    public static byte[] rsaEcbDecrypt(RSAPrivateKey privateKey, byte[] data) {

        if (privateKey == null) {
            throw new IllegalArgumentException("privateKey is null");
        } else {
            Object var3 = null;

            try {
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
                cipher.init(2, privateKey);
                return cipher.doFinal(data);
            } catch (Exception e) {
                throw new IllegalArgumentException("Fail: RSA Ecb Decrypt", e);
            }
        }
    }

    public CAP12CertTool getCap12CertTool() {
        return cap12CertTool;
    }

    public String sign(String indata, String encoding) {
        String singData = null;

        try {
            X509Certificate cert = cap12CertTool.getCert();
            byte[] si = cap12CertTool.getSignData(indata.getBytes(encoding));
            byte[] cr = cert.getEncoded();
            this.hexCert = HexStringByte.byteToHex(cr);
            singData = HexStringByte.byteToHex(si);
        } catch (CertificateEncodingException var8) {
            var8.printStackTrace();
        } catch (UnsupportedEncodingException var10) {
            var10.printStackTrace();
        } catch (SecurityException var11) {
            var11.printStackTrace();
        }

        return singData;
    }

    public String getCertInfo() {
        return this.hexCert;
    }

    public boolean verify(String oriData, String signData, String svrCert, String encoding) {
        boolean res = false;

        try {
            byte[] signDataBytes = HexStringByte.hexToByte(signData.getBytes());
            byte[] inDataBytes = oriData.getBytes(encoding);
            byte[] signaturepem = checkPEM(signDataBytes);
            if (signaturepem != null) {
                signDataBytes = Base64.decode(signaturepem);
            }

            X509Certificate cert = this.getCertFromHexString(svrCert);
            if (cert != null) {
                PublicKey pubKey = cert.getPublicKey();
                Signature signet = Signature.getInstance("SHA256WITHRSA");
                signet.initVerify(pubKey);
                signet.update(inDataBytes);
                res = signet.verify(signDataBytes);
            }
        } catch (InvalidKeyException var12) {
            var12.printStackTrace();
        } catch (NoSuchAlgorithmException var13) {
            var13.printStackTrace();
        } catch (SignatureException var14) {
            var14.printStackTrace();
        } catch (SecurityException var15) {
            var15.printStackTrace();
        } catch (UnsupportedEncodingException var16) {
            var16.printStackTrace();
        }

        return res;
    }

    public X509Certificate getCertfromPath(String crt_path) throws SecurityException {
        X509Certificate cert = null;
        FileInputStream inStream = null;

        try {
            inStream = new FileInputStream(new File(crt_path));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = (X509Certificate) cf.generateCertificate(inStream);
            return cert;
        } catch (CertificateException var5) {
            throw new SecurityException(var5.getMessage());
        } catch (FileNotFoundException var6) {
            throw new SecurityException(var6.getMessage());
        }
    }

    public boolean verifyCert(X509Certificate userCert, X509Certificate rootCert) throws SecurityException {
        boolean res = false;

        try {
            PublicKey rootKey = rootCert.getPublicKey();
            userCert.checkValidity();
            userCert.verify(rootKey);
            res = true;
            if (!userCert.getIssuerDN().equals(rootCert.getSubjectDN())) {
                res = false;
            }

            return res;
        } catch (CertificateExpiredException var5) {
            throw new SecurityException(var5.getMessage());
        } catch (CertificateNotYetValidException var6) {
            throw new SecurityException(var6.getMessage());
        } catch (InvalidKeyException var7) {
            throw new SecurityException(var7.getMessage());
        } catch (CertificateException var8) {
            throw new SecurityException(var8.getMessage());
        } catch (NoSuchAlgorithmException var9) {
            throw new SecurityException(var9.getMessage());
        } catch (NoSuchProviderException var10) {
            throw new SecurityException(var10.getMessage());
        } catch (SignatureException var11) {
            throw new SecurityException(var11.getMessage());
        }
    }

    private X509Certificate getCertFromHexString(String hexCert) throws SecurityException {
        ByteArrayInputStream bIn = null;
        X509Certificate certobj = null;
        byte[] cert = HexStringByte.hexToByte(hexCert.getBytes());
        CertificateFactory fact = null;

        try {
            fact = CertificateFactory.getInstance("X.509");
        } catch (CertificateException var13) {
            var13.printStackTrace();
        }

        bIn = new ByteArrayInputStream(cert);

        try {
            certobj = (X509Certificate) fact.generateCertificate(bIn);
            bIn.close();
            bIn = null;
        } catch (CertificateException var11) {
            var11.printStackTrace();
        } catch (IOException var12) {
            var12.printStackTrace();
        }

        try {
            if (bIn != null) {
                bIn.close();
            }
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        try {
            if (bIn != null) {
                bIn.close();
            }
        } catch (IOException var9) {
            ;
        }

        try {
            if (bIn != null) {
                bIn.close();
            }
        } catch (IOException var8) {
            ;
        }

        try {
            if (bIn != null) {
                bIn.close();
            }
        } catch (IOException var7) {
            ;
        }

        return certobj;
    }

    public String getFormValue(String respMsg, String name) {
        String[] resArr = StringUtils.split(respMsg, "&");
        Map<String, String> resMap = new HashMap<String, String>();

        for (int i = 0; i < resArr.length; ++i) {
            String data = resArr[i];
            int index = StringUtils.indexOf(data, '=');
            String nm = StringUtils.substring(data, 0, index);
            String val = StringUtils.substring(data, index + 1);
            resMap.put(nm, val);
        }

        return resMap.get(name) != null ? resMap.get(name) : "";
    }

    public String getValue(String respMsg, String name) {
        String[] resArr = StringUtils.split(respMsg, "&");
        Map<String, String> resMap = new HashMap<String, String>();

        for (int i = 0; i < resArr.length; ++i) {
            String data = resArr[i];
            int index = StringUtils.indexOf(data, '=');
            String nm = StringUtils.substring(data, 0, index);
            String val = StringUtils.substring(data, index + 1);
            resMap.put(nm, val);
        }

        return resMap.get(name) != null ? resMap.get(name) : "";
    }

    public Map<String, String> coverString2Map(String respMsg) {
        String[] resArr = StringUtils.split(respMsg, "&");
        Map<String, String> resMap = new HashMap<String, String>();

        for (int i = 0; i < resArr.length; ++i) {
            String data = resArr[i];
            int index = StringUtils.indexOf(data, '=');
            String nm = StringUtils.substring(data, 0, index);
            String val = StringUtils.substring(data, index + 1);
            resMap.put(nm, val);
        }

        return resMap;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public String coverMap2String(Map data) {
        TreeMap tree = new TreeMap();
        Iterator it = data.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry en = (Map.Entry) it.next();
            if (!"merchantSign".equals(((String) en.getKey()).trim()) && !"serverSign".equals(((String) en.getKey()).trim()) && !"serverCert".equals(((String) en.getKey()).trim())) {
                tree.put(en.getKey(), en.getValue());
            }
        }

        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();

        while (it.hasNext()) {
            Map.Entry en = (Map.Entry) it.next();

            String tmp;
            if (en.getValue() instanceof String) {
                tmp = (String) en.getValue();
            } else if (en.getValue() instanceof List) {
                tmp = JSONArray.fromObject(en.getValue()).toString();
            } else {
                tmp = String.valueOf(en.getValue());
            }

            if (!StringUtils.equals(tmp, "null") && !StringUtils.isBlank(tmp)) {
                sf.append((String) en.getKey()).append("=").append(tmp).append("&");
            }
        }

        return sf.substring(0, sf.length() - 1);
    }

    public String encryptData(String dataString, String encoding, String svrCertPath) {
        try {
            byte[] data = encryptedPin(getPublicKeyfromPath(svrCertPath), dataString.getBytes(encoding));
            return new String(base64Encode(data), encoding);
        } catch (Exception var5) {
            var5.printStackTrace();
            return "";
        }
    }

    public byte[] encryptedPin(PublicKey publicKey, byte[] plainPin) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
            cipher.init(1, publicKey);
            int blockSize = cipher.getBlockSize();
            int outputSize = cipher.getOutputSize(plainPin.length);
            int leavedSize = plainPin.length % blockSize;
            int blocksSize = leavedSize == 0 ? plainPin.length / blockSize : plainPin.length / blockSize + 1;
            byte[] raw = new byte[outputSize * blocksSize];

            for (int i = 0; plainPin.length - i * blockSize > 0; ++i) {
                if (plainPin.length - i * blockSize > blockSize) {
                    cipher.doFinal(plainPin, i * blockSize, blockSize, raw, i * outputSize);
                } else {
                    cipher.doFinal(plainPin, i * blockSize, plainPin.length - i * blockSize, raw, i * outputSize);
                }
            }

            return raw;
        } catch (Exception var9) {
            throw new Exception(var9.getMessage());
        }
    }

    public byte[] base64Encode(byte[] inputByte) throws IOException {
        return Base64.encode(inputByte);
    }

}

------------------------------------------------------------------------------------

------------------------------------------------------------------------------------

posted @ 2022-12-05 09:55  hanease  阅读(51)  评论(0)    收藏  举报