/**
 * <p>Title: RSAUtil.java</p>
 * <p>Description: </p>
 * <p>Company:asiainfo-sec</p>
 *
 * @author zhxiaojing
 * @date 2019年12月31日
 */

package com.ankaibei.workFlow.webadmin.ankaibei.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * <p>Title: RSAUtil</p>
 * <p>Description: </p>
 * @author zhxiaojing
 * @date 2019年12月31日
 */

@Slf4j
public class RSAUtil {
    static final String privateStr = "MIIEowIBAAKCAQEAsgDq4OqxuEisnk2F0EJFmw4xKa5IrcqEYHvqxPs2CHEg2kolhfWA2SjNuGAHxyDDE5MLtOvzuXjBx/5YJtc9zj2xR/0moesS+Vi/xtG1tkVaTCba+TV+Y5C61iyr3FGqr+KOD4/XECu0Xky1W9ZmmaFADmZi7+6gO9wjgVpU9aLcBcw/loHOeJrCqjp7pA98hRJRY+MML8MK15mnC4ebooOva+mJlstW6t/1lghR8WNV8cocxgcHHuXBxgns2MlACQbSdJ8c6Z3RQeRZBzyjfey6JCCfbEKouVrWIUuPphBL3OANfgp0B+QG31bapvePTfXU48TYK0M5kE+8LgbbWQIDAQABAoIBABSRoJKO7CxkUXYVdTIEhnCNakbrucBDV5qilxVeBfdhwy8WRFG/db0iRutYRW3QLlqTslWcslQrTREkJeGPG7g6TsMH0LADLvUbOUXrM7k1OGL2VnVXphwxPDXFgbJ6yWN7pXjM4UggFL6U1JwhIUf9Zx6C3EnnZCKmpH+tBYZAsxp2emqka87/lVBIXgVp0YBO6SsTXCi7I1jFZPK4R5VsiAk+YP2xKQlkpQCRO+IWD2el+NwRnhaEcxnSn+YjoAyOX1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FJjWLMbruRcfChB6GVCfazvi1k2Q2fxRMAWQ5qUqVhgGLNpJ0VuBzOTiwGKErbqMX7vJA0vbukLr6ZKn86tpuBh/kcN7G2wCfAU4xhQkZ2/W2Yzuvu0xprRjXEiHxIWEf70/OiJoNAgMBAAECgYBv+vph0pEB3KkBbdGtPsL4QNGJY6cWBSuqpNkk7/nzhQIn/foBUjzgS8840LsboP8CRxIG0oLEcsSO6U+zOToVvSpgetdrrmhHnCgnQISfD4Y1ex0v7IDFf6iV7Pz0wwGjYhCtJnFnWpGQaw7zhEkv6eYDeuhMLGKQxHrlZmTdbQJBAM+vhAVFI09FbdTbQ1DMS38ygYl15LoiYHE26FTDgWubOv50h4NNU6SnWO7onwMyvDjM+xEyHk3lIT9bz1jgy0sCQQCzhownjBU6gB/tSLyV3l0DGMJQA049/7TSg5nzrUERjLqhIkSYKmDxvQ8Ly1FHTSqZ8KVv71TYdbBHBUOuL0EHAkAoUAhPQZFOBMsB4yGY4F7TLMmKFhE0tBGGSEMmmOBZM8NqutHHAc53imgvz4V2CHYSjG87ckABnLUsaDTCKrgrAkEAhy/vhKxJJBdtc1qNoHGlKvrPAD+tAKT4vnmZSdUSpauKsmJCsy9ed0s99EyztPSX+vorKmJYSvQ8vQ5qy9ULqwJAfhORwiSdDaQMNuzHD1WB9qhQOKZikGb6u/qvISCiLrfhUPtgtvBHhKhCpUtQqXYGuFUlcm/sYxyk2EEY67j4uw==\n";
    static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRpODi268UlE2uT2c8TWg9wdWRpeKNSg51RSY1izG67kXHwoQehlQn2s74tZNkNn8UTAFkOalKlYYBizaSdFbgczk4sBihK26jF+7yQNL27pC6+mSp/OrabgYf5HDextsAnwFOMYUJGdv1tmM7r7tMaa0Y1xIh8SFhH+9PzoiaDQIDAQAB";

    /* .
     * 用私钥解密 .
     * @author wangp
     * @since 2018年1月24日
     * @parameters @param password
     * @parameters @return 参数说明
     * @returns  返回说明
     * @throws
     */
    public static String decryptByPrivateKey(String password) {
        String pwd = "";
        try {
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(Base64.decode(privateStr)));
            RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(),
                    asn1PrivKey.getPrivateExponent());
            PrivateKey rsaPriKey = kf.generatePrivate(rsaPrivKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, rsaPriKey);
            byte[] deTestByte = cipher.doFinal(Base64.decode(password));
            pwd = new String(deTestByte);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("decryptByPrivateKey error");
        }
        return pwd;
    }


    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param
     *
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt(String str) {
        //base64编码的公钥
        String outStr = null;
        try {
            byte[] decoded = Base64.decode(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = new String(Base64.encode(cipher.doFinal(str.getBytes("UTF-8"))));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("RSA加密失败");
        }
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param
     *
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str) {
        //64位解码加密后的字符串
        String outStr = null;
        try {
            byte[] inputByte = Base64.decode(str.getBytes("UTF-8"));
            //base64编码的私钥
            byte[] decoded = Base64.decode(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("RSA解密失败");
        }
        return outStr;
    }


    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encode(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encode((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        System.out.println("11111111111=====" + privateKeyString);
        System.out.println("2222222222=====" + publicKeyString);
    }


    public static void main(String[] args) {
//		try {
//			genKeyPair();
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		}
        System.out.println(encrypt("8845696"));
        System.out.println(decrypt("NoHalvO7gIRHf0QjDqRF0xBwwkSfpGH9EQfZt1rGsKWe96Lztt42Z1xI2s30CwxUK+WGGeCFEpRoW6oEZYBf3tRAYVP95iYwKIAx93ziF8xmyQGcor96vmeM8MLD/VzGGiD0xrwfvvrmckrI0btFZBhlFUMSIQLNcVXgKnCknTY="));
    }


}
