package com.group.service;
 
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
 
/**
 * Created By Rock-Ayl on 2020-10-14
 * RSA工具包
 * 0.生成秘钥
 * 1.加密
 * 2.解密
 */
public class RSAUtils {
 
    protected static Logger logger = LoggerFactory.getLogger(RSAUtils.class);
 
    //RSA-公钥
    private static String PublicKey="MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmZLmb4paD13E2uOueFStT1g8OnA4JQYkN4PZl/il7Nb05EbZrRbQz/5VbiZxc+S4asfFrrU0d++gjiluiAbBBhgtQSi+eNZuJ2wrBxjvN3W9d14XMmZKDg21Knu7tDUwOlEfCPVMZ/nJ+9YU6mnEvme29UgpI4RbEIIWPuDW3DavbaOvZ/cYP+0m2pxU3mETwDbVpbM3LimJ4JOBIs7XhV2UqEUfRVCYiuZUkydOCs1TgTJRJC5qgYpx4wUZ0ja7t9jP3klg/vjjyA1SDnC98bQLR5QzVJE1LvI2Rr3AHfZS0hckg0WAR87D1R8sGjmQ0TUi4qanpQYhEL4dBH8a6TX/xssobM7M+XgFsGiT4fWG18JhJM98rhVEk2AUaXgnFNf3OyLP+NuYrqjYamuug00s2azCl/rQCkvnLWO4W+lPn27ZinnBRg1+r2fNws7dPPa/8tWScRcTtfaidYsQP2lnYJvFgc299HdQL7iFgL336NihUxll09Hhm7vf8+N0ZP5TLE8SRoSfHNgHup6k9YG5e+V9bW4VckQFgPPBlHSS0mDEOvD9d54+F1cBg/sG8XMduW5WhfroYsMbRzB9a4rIfctn6yqpM+ot2EW8CKgiOVM5lJQhBwX5rMKnMTaApt6EIigY6jRVFNCOtQPDZ9prLBsp3asQxf7Vg9kfrVUCAwEAAQ==";
    //RSA-私钥
    private static String PrivateKey="MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoIC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AgkQ7H9SmC1dCPxOSnq1JLfC7x4+VYFnO6F45K8PhTTLV3stj+e0FFMaghL/gCaIjayEG4r3BDNLKT95aqzctYVjqeXRCd7iY+dWv2bhWWWSoNJaZ5X8cG6qeJtcvUaAfOIfurWu+eeA3nzxyxBVU9XgqFBPnH32dZ4U4b7/mlJPRHIHTfObliOjRia//HIlSQHw7gNzPuSxvDhMxosmkbWk6gtY3CmkeF4vbl2/X/fJGWFT0sE09AoIBADL79bz0p7N9EMMVHbZoW3dUP5VMJFwY8sukCOIQDMXIFQtqquIxtZ0KDGYNbWxF0F9PLQle2x2SUu9LbzHgazduayCBYWGMzs6BfOO+9qoXK56UB//YTmB7glyyNpO4zCeBakU37plzZnFG5ehVI6FIojXm4wqcG/HsRSY7YOD4FEgV9QKJL/0IxrPGK3ue+PRgiKNek7wwzh1v8X+1KtE27EE/BWevbxEKTm+8mKhu0Ii1/CXteaqrFowFH7m1hZAltrabG+7WvcxjgWndJQpgG+CspiEM4hesAPkrNAdPGsahS03FzN+fv27X8HKcpG3wzcSfEJrHFGmc0DOqwqsCggEAJ+ICyEbmQ94Ibtha4QJSeFCgVO29eM0/O8e8beGv3+zrxrt5kQLFrrvJIke2iAnRbmBkX0BDyTMQ5LdexGp1R1272Q9HAysjsWitw4GHV4CZK6dezm7slDTx/8z6bD1B2oeFboyuevB04sFZVUY3qzbuIEQYpvU9nwThxP/sVq+1v2ilXPD2iSXdVScGkNUVmpF4asiteYvS6feohV/HMMm71D/CeENcHfgSiqZyW1hHsDxgSwYOQcCpEdrXTF7ly/SpKDjYfmljCPvFwpECO8pNG90/e/CY+6H7jpAS00AFRzK+/bs6JW5gQE1zC/O05DB77oREVfk9NI6eElY4ZA==";
 
//    //初始化
//    static {
//        try {
//            //KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
//            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//            //初始化密钥对生成器，密钥大小为96-1024位
//            keyPairGen.initialize(4096, new SecureRandom());
//            //生成一对密钥
//            KeyPair keyPair = keyPairGen.generateKeyPair();
//            //公钥存储
//            PublicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
//            //私钥存储
//            PrivateKey = new String(Base64.encodeBase64((keyPair.getPrivate().getEncoded())));
//        } catch (NoSuchAlgorithmException e) {
//            logger.error("RSA生成秘钥异常:[{}]", e);
//        }
//    }
 
    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey))));
        return Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
    }
 
    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(PrivateKey))));
        return new String(cipher.doFinal(Base64.decodeBase64(str.getBytes("UTF-8"))));
    }
 
    //测试
    public static void main(String[] args) throws Exception {
        //加密字符串
        String message = "{\"acc\":\"mwxtest1000001\",\"nick\":\"mwxtest1000001\",\"sex\":2,\"deviceCode\":\"281a228fac1c29d25c1a3e572b15ad47d5f66811\",\"portrait\":\"\"}";
        System.out.println("随机生成的公钥为:" + PublicKey);
        System.out.println("随机生成的私钥为:" + PrivateKey);
        String messageEn = encrypt(message, PublicKey);
        System.out.println("加密前:" + message);
        System.out.println("加密后:" + messageEn);
        String messageDe = decrypt(messageEn);
        System.out.println("还原后:" + messageDe);
    }
 
}