package com.ztmap.common.utils;

import org.apache.commons.codec.binary.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.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil {
    //public static String PRIVATE_KEY="MIIEoQIBAAMMMMMMMMMMMMMMMMFbuiAmYG/VOym6ZDftCy2R4oJvkP7MgS1nsxBRdnb0eAU/abVy1Wk2y1d6ZsiF35Shpy235WfkIVc9cRX71LpNxetfMiFAJSqSZ2XbNJTBWZEah/r0rBgRSAkC6NbFsgdWi6VbPGDVM+Y2pM8wQjrUi3ZCTE9SSchv/grbl/OJm/T5uaYP0VqoOV0Zzi89bqjby9XexInyCj+1hxy7+9NP1brx5qHRAuiidbtqHzVOyKpsKGPh2fJugbVhzUoqM6ebL/j1y8w92obMj3snsgykqj5T2kfSiiMxAgMBAAECggEALujqfMixJEyl+IP6TV3kG61S63EFdHrmFv+GW3b8TdUWA3VABEF9p1nHH29SirBwG1Kqd5A9Wxg2v37hVSz2Mx2gaFv4HsFna4eZfY6ZoJmfr7ag7gw1+aqit9opmmNOcVBNUoLjiZLkQiihZpATvofJZEY/epnmKudABg+9ZN86vnbA2DFnYmVLbZvWwhGyr7AnvDO+678PtpIaWL4yxRA+p+6CxQd5ZkQf8E6VGeU4qSmbksjN+fav1SwDm4hGSBvHP6r2dWZ7MITg4DomavOwCJseh9AVX9LUtygumjY/NdYoUXkyoSeniQwL/uMd1ewB9Qi8jrJj9NAxUbsXDQKBgQCe2zRMi+R5u35FL2jWs/gAgT7KQ8d0vlv/eAOD2filiEGRoTgdzAXuGY0vytICf11HZ/y0qhPuiDuNIOnvIa9kj2zHawVBbm6Fl6J6GP874V894Bh3J3oWn9ilMIfEjvM4Jlg6aKPiht1EiykLgvIim4qaFj8UTBMMkaqUZJjw6wKBgQCWBurdYj59dZ6XOlYZTDNjJriTm4MdOZrvxA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0NAQJBANpkI6GIe2bclAg5G62gwiBR6VLB/UsESiDf9WOdw5Wtdsjr2F/Be1VuE40yMDGD88j8RdOquUw3KvKXMBJLVy0CQQCwHzbzc4llfz80R0am54+qHjxQGuF0BTD6ebnSJgeP9P7zOxXUtfYoK8UApCKkcPzG7Otd7DotKMn2QxuryGOhAkBBojbTJSFxGHmkvwUCeX3eGL/2jzaAhRmCJ8yn05IkOa2pVLgCjzNxyVM27A5v0yhBDxAtPPHTZgESRz27QclBAkAi0JjROSaQ3L2GvQw3VBDvJPjxMM8eWyRabxOPehsGlvyK4kQnfyzAth5ESS3b6cXeINlKALdjU+vQdWWT6JHhAkAsfeZrgJQq61MBT/baYbavNQL6kB18whnxGnMxpXJ3tzON4Pcz9Z9j2vxJHCicJ1jm0bX+Sj+lapoEgUo11lrw";
    public static String PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWP3mALYZ09mC53gDB9qwiziZyNWlagunrJ7YxUd3GrNUsAFaaMdAuDPpTeUEaYzdkH2b0EuHlWP5vNfxAHNWWWa4urNI6VkNUE7ZFLgwsbgpCWgD4auq6UfkiPHhPDBq0l7l3L7kpVqGTdfDqJ8Ke2mbKM83Mp4zM0EMkzkA6TQIDAQAB";
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
    public static void main(String[] args) throws Exception {
        //生成公钥和私钥
        genKeyPair();
        //加密字符串
        String message = "testmsg";
        System.out.println("随机生成的公钥为:" + keyMap.get(0));
        System.out.println("随机生成的私钥为:" + keyMap.get(1));
        String messageEn = encrypt(message,keyMap.get(0));
        System.out.println("明文："+message);
        System.out.println("加密后的字符串为:" + messageEn);
        String messageDe = decrypt(messageEn,keyMap.get(1));
        System.out.println("还原后的字符串为:" + messageDe);
    }

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    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.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(0,publicKeyString);  //0表示公钥
        keyMap.put(1,privateKeyString);  //1表示私钥
    }
    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

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