package com.chaozhanggui.admin.system.util;


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

import javax.crypto.Cipher;
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;

/**
 * @author admin
 * @date 2021/4/28 15:02
 */
public class RSAUtil {

    public static String RSA_ALGORITHM = "RSA";

    public static String UTF8 = "UTF-8";


    /**
     * 创建公钥私钥
     *
     * @return
     * @throws Exception
     */
    public static KeyStore createKeys() throws Exception {
        KeyPairGenerator keyPairGeno = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGeno.initialize(1024);
        KeyPair keyPair = keyPairGeno.generateKeyPair();

        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        KeyStore keyStore = new KeyStore();
        keyStore.setPublicKey(Base64.encodeBase64String(publicKey.getEncoded()));
        keyStore.setPrivateKey(Base64.encodeBase64String(privateKey.getEncoded()));
        return keyStore;
    }

    /**
     * 获取公钥对象
     *
     * @param pubKeyData
     * @return
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(byte[] pubKeyData) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKeyData);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    /**
     * 获取公钥对象
     *
     * @param pubKey
     *            公钥
     * @return
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String pubKey) throws Exception {
        return getPublicKey(Base64.decodeBase64(pubKey));

    }

    /**
     * 获取私钥对象
     *
     * @param priKey
     *            私钥
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String priKey) throws Exception {
        return getPrivateKey(Base64.decodeBase64(priKey));
    }

    /**
     * 通过私钥byte[]将公钥还原，适用于RSA算法
     *
     * @param keyBytes
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(byte[] keyBytes) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

    }

    public static String encryptByPublicKey(String data, String publicKey) throws Exception {
        return encryptByPublicKey(data, getPublicKey(publicKey));
    }

    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(data.getBytes(UTF8));
        return Base64.encodeBase64String(bytes);
    }

    public static String decryptByPublicKey(String data, String rsaPublicKey) throws Exception {
        return decryptByPublicKey(data, getPublicKey(rsaPublicKey));
    }

    /**
     * 公钥解密
     *
     * @param data
     * @param rsaPublicKey
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String data, RSAPublicKey rsaPublicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey);
        byte[] inputData = Base64.decodeBase64(data);
        byte[] bytes = cipher.doFinal(inputData);
        return new String(bytes, UTF8);
    }

    public static String encryptByPrivateKey(String data, String privateKey) throws Exception {
        return encryptByPrivateKey(data, getPrivateKey(privateKey));
    }

    /**
     * 私钥加密
     *
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(data.getBytes(UTF8));
        return Base64.encodeBase64String(bytes);
    }

    public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
        return decryptByPrivateKey(data, getPrivateKey(privateKey));
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] inputData = Base64.decodeBase64(data);
        byte[] bytes = cipher.doFinal(inputData);
        return new String(bytes, UTF8);
    }


    public static class KeyStore {
        private String publicKey;
        private String privateKey;

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }

    public static void main(String[] args) throws Exception {

//        KeyStore keyStore= createKeys();
//        System.out.println(keyStore.publicKey);
//        System.out.println(keyStore.privateKey);

        String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCt4B7TJ9vMml3p5qHEoYfZIuRqklbFSrI5jnq25vjjqpJp8Vc8Ir0n8QVCpfzaO5oU2tf4qZ4KIidwlysagdzLb73q8EQIf4ILt2BQFRS5RAGPnKNPA8BsWwqzbnAI2+GHCSWtixVatLbswfdmIQJEHMzDylLGHycbb3CG+mC/sQIDAQAB";

        String priKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK3gHtMn28yaXenmocShh9ki5GqSVsVKsjmOerbm+OOqkmnxVzwivSfxBUKl/No7mhTa1/ipngoiJ3CXKxqB3MtvverwRAh/ggu3YFAVFLlEAY+co08DwGxbCrNucAjb4YcJJa2LFVq0tuzB92YhAkQczMPKUsYfJxtvcIb6YL+xAgMBAAECgYA6qkO8OtaOUgcdxBMQpO+Q85Td4EImju1TPh9pVsTjC8oatLMaNx5bO5bqxdZqS3HRV4VHAPOxt5RXCKoiZ253JMvmcWXmiwYNFEr9iFXOLVT0H6q+TT4cpp5klAFM5xELaR4WFsYlxvCA6KGdNqHg4wYSPwj+WdYM12xEhBtjgQJBAPttT2LuIoEyLvjrqUr8bMuFKHRuYp3rMtl3nwU0es2OuOOsWH69w+L7oi4tgHr1gzpN8k2XExMcf0uDnk9eBrsCQQCxCbdegzCiSafUxrDwZpROlfL1duRXDinkLc9KC2HfS+w4/9Mjuc49SFo3grKczGN3t6AnlBasONehmNuDAAqDAkAeFND3tCgarwdhrshdeWAG5ZKWg5J29GnsDNzQwZujtly2mKsp1sh2Asc/oSALFg6yThscX2Pf2Hv+a+vn8Qb7AkAuDXD9zPKhxLc7ylPMtWJu7uK8p6jOXIjZKnF5uWxEQeO5EBNEf9j+aAvP1NfRofld8w5ePU+IjWDKUJEJisExAkEA+L6M96L3ICNF3sYtdvILO2ExYb4AuxF18MmPVWEy0jK9xxan3rggpIG+BQQuy8DoL1snc+JABALiSFEbAZjm6Q==";

        String data="hFAKmbWQ4mo/ARmGWPBUxPP0kbpiIukGrNWovZS3MJiq/wf63ZDtnfLlLDgGMbuNRxE0dX3sVM69O6Pndv1JNSGNs+NUsU8EAScg0gfWrBssoKFdi4ZFqla9uauoY7E/chsANvU3kwEoeMplloOilvvX4LTQueKnuNvHyt1WTYY=";
        System.out.println(decryptByPrivateKey(data,priKey));


//        JSONObject object=new JSONObject();
//        object.put("openId","xsaxmasomxoamxoamsxo");
//
//        System.out.println(RSAUtil.encryptByPublicKey(object.toString(),"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOUSIKUGRwvUFrDvD6s8PgL8hQoKQrzTTK6vKWzQ2MIQ09ArZOd0ndxaZVVygebA+6vb7lArn1rMwKPFvbCs/iQZtYyXe7l+sfaPp8VzWzmDyAqHgQjsD+0LAMsdqtLCpB6kzP/WojeKaxREGAalJNyVR3hX2UzW98qkAV40hepwIDAQAB"));
//        String ssss = "4AAB79960924E25BE1B626FB7B42917711E48FFBEFBCF29C0E47716514073F97AB2C0A97F95BD80168E1FBD9852ABC21038631F40A79B1142E11570430A0C03D896722433886222BED782A3DB82C156B246C9E8A7287AAB1BAFB1D520BC030514E82130FD1D20DDCE8C67E3A552A8EFE6784BF657614D7B6D16BBED16B899E00";
//        System.out.println(RSAUtil.decryptByPrivateKey(ssss,"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJx0zH5Q01roGe33mUP27K4rHrWZ9UoPYcA7TE4ufv8wPk7/i1JZCZojx9BDUwwihn9Hwbv2XR66FRzQ7UzHsrjqNt5QcFUcbXh3Wm0BGQ6aLoK3qRAUIasvegIUxWHTvubQEGvV4Nld4FI0kStjLF89QzFBiyjCYa9xmWt62TU1AgMBAAECgYApWuouvViQn+cyso7NmzhGdVlhsTdYAybYdBQgWkPxWiQuJ3gBJU3Xc3u+ff02qO2aOTJpZ56Hn7Iy8rq239ZKhqnGJcQSjFTIODZo6S8xaWCv+DFjpsnTMA8rZ/ohiR/BoCMJPTFA3sRpjH4RquzV9y1HkSVvz96I/RAn2UU0QQJBAM8Cdudm96P67iYTRX/zAXeueV8wlqPKJ8i35lNBSprfyv0+N2v8ARjev8LCx8ebFzLNsLfEByx327KlnAY29EUCQQDBe5eya8wIqVRCbnZKzulCkSi8ZPg7Vzucg/W619hWe35ddXtUgLj/uPZ+SNZrGlWmt+dT9Mf7WEAxb4xXm+QxAkBtZ1QH//cpBtkN7mlwsbE421Dx6e/zKEfWYLqtjXgsWdIh/Nu1ij3aMv8No3uKFoEwLF0VAdj4u2+0/qly72AxAkEAo9MFUBKMMS1G5fTn/lGSGkYUqugHcx9anxzwvOK0EA4Cohmuco+HlSdEtwrvWsJykXaXzXOuvLgtqm4b87ZQkQJAWkKoEiIPloAVELKWqRtcoHNzdsJGZ5pMTlfOP0GgufNhZxYXFByEo7eZ7b7sbyaJkQOR6ubDlvwoPGxU1jnVKQ=="));
    }
}
