package com.bootdo.common.utils;

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.Base64;

/**
 * @author 宋显哲
 * @version 1.0.0 创建于 2018/1/18
 **/
public final class RsaUtil {

    /**
     * 创建签名公私密钥对
     *
     * @return 返回公私要对数组，第一个元素为私钥，第二个元素为公钥
     * @throws Exception 异常信息
     */
    public static String[] createSecretPriPubKey() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(512);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

        String[] keyPairArr = {
                Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()),
                Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded())
        };

        System.out.println("私钥==>" + keyPairArr[0]);
        System.out.println("公钥==>" + keyPairArr[1]);
        return keyPairArr;
    }

    /**
     * 对文本内容进行数字签名
     *
     * @param sigContent 带签名内容
     * @param priKey     签名私钥
     * @return 返回签名
     * @throws Exception 异常
     */
    public static String signature(String priKey, String sigContent) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(
                new PKCS8EncodedKeySpec(Base64.getDecoder().decode(priKey))
        );
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey);
        signature.update(sigContent.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    /**
     * 用公钥验证签名
     *
     * @param pubKey  公钥
     * @param content 待验证内容
     * @param sig     签名
     * @return 返回验证结果，true为验证通过，false为验证失败
     * @throws Exception 异常信息
     */
    public static boolean verifySig(String pubKey, String content, String sig) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                Base64.getDecoder().decode(pubKey)
        );
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(publicKey);
        signature.update(content.getBytes());
        return signature.verify(Base64.getDecoder().decode(sig));
    }

    public static void main(String[] ars){
        try {
            createSecretPriPubKey();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
