package com.schisandra.oss.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;
import java.util.HashMap;

/**
 * @ClassName RSAUtils
 * @Description TODO
 * @Author L
 * @Date 2024/1/26 17:28
 */
public class RSAUtils {

    /**
     * 公钥加密（解密就要用到对应的私钥）
     *
     * @param msg    明文信息
     * @param pubKey 公钥，用来加密明文
     * @return
     */
    public static String encryptByPublic(String msg, String pubKey) {
        RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), null, pubKey);
        return rsa.encryptBase64(msg, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     *
     * @param encryptMsg 公钥加密的密文
     * @param priKey     私钥，用来解密密文
     * @return
     */
    public static String decryptByPrivate(String encryptMsg, String priKey) {
        RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), priKey, null);
        return rsa.decryptStr(encryptMsg, KeyType.PrivateKey);
    }

    /**
     * 私钥加密（解密就要用到对应的公钥）
     *
     * @param msg    明文信息
     * @param priKey 私钥，用来加密明文
     * @return
     */
    public static String encryptByPrivate(String msg, String priKey) {
        RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), priKey, null);
        return rsa.encryptBase64(msg, KeyType.PrivateKey);
    }


    /**
     * 公钥解密
     *
     * @param encryptMsg 密文
     * @param pubKey     公钥，用来解密
     * @return
     */
    public static String decryptByPublic(String encryptMsg, String pubKey) {
        RSA rsa = new RSA(AsymmetricAlgorithm.RSA_ECB_PKCS1.getValue(), null, pubKey);
        return rsa.decryptStr(encryptMsg, KeyType.PublicKey);
    }

    /**
     * 获取公私钥集合
     *
     * @return
     */
    public static HashMap<String,String> getPriKeyAndPubKey() {
        KeyPair pair = SecureUtil.generateKeyPair("RSA");
        String privateKey = Base64.encodeBase64String(pair.getPrivate().getEncoded());
        String publicKey = Base64.encodeBase64String(pair.getPublic().getEncoded());
        HashMap<String,String> keys = new HashMap<>();
        keys.put("privateKey",privateKey);
        keys.put("publicKey",publicKey);
        return keys;
    }


}
