package com.chinacreator.process.util;

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

import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA工具类
 *
 * @author wjf
 * @version 2020-4-21
 */
public class RsaUtils {

    /**
     * 使用公钥加密
     *
     * @param content
     * @param publicKey
     * @param charset
     * @return
     * @throws GeneralSecurityException
     */
    public static String encryptWithPublicKey(String content, String publicKey, Charset charset)
            throws GeneralSecurityException {
        Key key = getPublicKey(publicKey);
        return encryptWithKey(content, key, charset);
    }

    /**
     * 使用密钥加密
     *
     * @param content
     * @param key
     * @param charset
     * @return
     * @throws GeneralSecurityException
     */
    public static String encryptWithKey(String content, Key key, Charset charset)
            throws GeneralSecurityException {
        if (content == null) {
            return null;
        }
        // 对数据加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        if (charset == null) {
            cipher.update(content.getBytes());
        } else {
            cipher.update(content.getBytes(charset));
        }
        byte[] signed = cipher.doFinal();
        return Base64.encodeBase64String(signed);
    }

    /**
     * 使用私钥解密
     *
     * @param content
     * @param privateKey
     * @param charset
     * @return
     * @throws GeneralSecurityException
     */
    public static String decryptWithPrivateKey(String content, String privateKey, Charset charset)
            throws GeneralSecurityException {
        Key key = getPrivateKey(privateKey);
        return decryptWithKey(content, key, charset);
    }

    /**
     * 使用密钥解密
     *
     * @param content
     * @param key
     * @param charset
     * @return
     * @throws GeneralSecurityException
     */
    public static String decryptWithKey(String content, Key key, Charset charset)
            throws GeneralSecurityException {
        if (content == null) {
            return null;
        }
        try {
            String result = null;
            // 对数据解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] data = Base64.decodeBase64(content);
            cipher.update(data);
            byte[] signed = cipher.doFinal();
            if (charset != null) {
                result = new String(signed, charset);
            } else {
                result = new String(signed);
            }
            return result;
        } catch (Exception e) {
            return null;
        }
    }

	/**
	 * 获取公钥密钥
	 * @param key
	 * @return
	 * @throws GeneralSecurityException
	 */
	public static PublicKey getPublicKey(String key) throws GeneralSecurityException {
		if (key == null) {
			return null;
		}
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] encodedKey = Base64.decodeBase64(key);
		return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
	}

	/**
	 * 获取私钥密钥
	 * @param key
	 * @return
	 * @throws GeneralSecurityException
	 */
	public static PrivateKey getPrivateKey(String key)
			throws GeneralSecurityException {
		if (key == null) {
			return null;
		}
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		byte[] encodedKey = Base64.decodeBase64(key);
		return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
	}

	public static void main(String[] args) throws GeneralSecurityException {
		String publicKey= "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyw5ghlH6GCIkM9Lt7uGcI/QuebfXgNq3CsOL0/DrbayGp+W/9Fz78n2ho3rQUvX4hw6WXxTxFSgQdZVhY9E+WAfYiW0qi8N+vwgZZ1awHQqJV6U91CeReR8FHOS9BOMxjirjpsja2m0hrrSItAOAyC/bH+d28NLveewYiPDx3OK0KWByOGBjI2TQFOHxjgYzLkFgd7ZbKUxmJ1KVrb/1qr4NUmqJhNqoWeXfRkNfEL7hp41d9uM6MC7YobBG+0azcIKm4bCOD1KkY3GpsTANJCt0X7aH/2irTW658qbshiZm8QEkWHx3rZAl5t+FLxDYTdZhoq3JBD4M4g8nmlOM8wIDAQAB";
		String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDLDmCGUfoYIiQz0u3u4Zwj9C55t9eA2rcKw4vT8OttrIan5b/0XPvyfaGjetBS9fiHDpZfFPEVKBB1lWFj0T5YB9iJbSqLw36/CBlnVrAdColXpT3UJ5F5HwUc5L0E4zGOKuOmyNrabSGutIi0A4DIL9sf53bw0u957BiI8PHc4rQpY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n41UY5OlhpU2NuLJZ9koEL9CGm9XZmWNGwKBgQDBlq8PavOVK4QmeeOOGzaqdZBhRbp717C9ENkUAiXJol45GC1YePgczSLQIZ61kraqVlIS/xwmZM8z0nzEs6NT4LyFUg6QkMcMWsuVHdgfL+M/mOnVIbuHuAbg8GYWVX7Fh7TklGvPmnwpTxHLmnPRczb3VKNs59VfA7/2QBzozQKBgGPpB7VWBVeQcrQk5uADXhZqzEj6ZZxNyK9FZDV7tAOTlHj1tv+nKrqvR6Z6ZxscbQbaUGl77bQK/RSjsCHFS23KmCzcXB7dVVdK9KuyYOTAPiFRIKy/cwpmnTulbogmCF66+RSt9k7BoQo+b0Setn6VJmJr6uC+tOJwqXkBRaDHAoGBAJ9oAdzTN6I0hAvewGcKt5fjWLEQZr+FWy5ECkw0fIMtJSMkamp4qe2laS4zEOn41lsq20hzMu3WgtvsTfr25N2zp+isKfwWiyD8PrkaKxV7LEf5FUsADNhzy447xgRMACiNV4IFSUVYszacuk2KcCYfFjrRQgTyXbtwbghKwMNdAoGBAJ3GG4ewzHLMUVcN78ueUFwBSBAWSWgJnNBkc8FegGbxHdyTj3XqupD6GeTuF8PGQKXINRMpoWlx/GDOIaJ08iF8K59b1Km/pIzQ6KkogVq8/fHI2tx6XK7gzSzCRZh+yLHvp1S6NVWeaO+lRDbBbPJJq4PyXb6zlfDEp7qxSC1b";
		String enr = RsaUtils.encryptWithPublicKey("appKey=3000004628&callNumber=16602020321", publicKey, Charset.defaultCharset());
		System.out.println(enr);
//        // BASE64加密
//        byte[] data = Base64.encodeBase64(enr.getBytes());
//        System.out.println("BASE64加密：" + new String(data));
//
//        // BASE64解密
//        byte[] bytes = Base64.decodeBase64(data);
//        System.out.println("BASE64解密：" + new String(bytes));
		String dec = RsaUtils.decryptWithPrivateKey(enr, privateKey, Charset.defaultCharset());
		System.out.println(dec);

	}
}
