package com.unis.common.util;
 
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
 
/**
 * @description: Rsa非对称加密算法工具类
 * @author: chenwenrui
 * @date: 2023/7/14 15:14
 */
public final class RsaSecretUtils {
    private RsaSecretUtils() {
    }
 
    private static final String RSA = "RSA";
 
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
 
    private static final Base64.Decoder DECODER = Base64.getDecoder();
 
    private static final Base64.Encoder ENCODER = Base64.getEncoder();
 
 
    public static void main(String[] args) throws NoSuchAlgorithmException {
        String plaintext = "de123";

        // 生成密钥对
        KeyPair keyPair = getKeyPair();
        // 公匙
        String publicKey = getPublicKeyBase64(keyPair);
        System.out.println("公匙 -> " + publicKey);
        // 私匙
        String privateKey = getPrivateKeyBase64(keyPair);
        System.out.println("私匙 -> " + privateKey);
        // 明文

        System.out.println("明文 -> " + plaintext);
        // 密文base64（公匙加密）
        String ciphertext = publicKeyEncrypt(plaintext, publicKey);
        System.out.println("密文base64 -> " + ciphertext);
        // 解密后明文（私匙解密）
        String decryptString = privateKeyDecrypt(ciphertext, privateKey);
        System.out.println("解密后明文 -> " + decryptString);
     /*   // 数字签名
        String sign = sign(ciphertext, privateKey);
        System.out.println("数字签名 -> " + decryptString);
        // 验证签名
        boolean pass = verify(ciphertext, sign, publicKey);
        System.out.println("验证签名 -> " + pass);*/
    }
 
 
    /**
     * 生成秘钥对
     *
     * @return
     * @throws Exception
     */
    public static KeyPair getKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }
 
    /**
     * 获取公钥(Base64编码)
     *
     * @param keyPair 秘钥对
     * @return
     */
    public static String getPublicKeyBase64(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        // 先用base64编码，再转换为字符串
        return new String(ENCODER.encode(bytes), StandardCharsets.UTF_8);
    }
 
    /**
     * 获取私钥(Base64编码)
     *
     * @param keyPair 秘钥对
     * @return
     */
    public static String getPrivateKeyBase64(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        // 先用base64编码，再转换为字符串
        return new String(ENCODER.encode(bytes), StandardCharsets.UTF_8);
    }
 
    /**
     * 将Base64编码后的公钥转换成PublicKey对象
     *
     * @param publicKeyBase64 公钥base64
     * @return
     */
    public static PublicKey getPublicKey(String publicKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = DECODER.decode(publicKeyBase64);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return keyFactory.generatePublic(keySpec);
    }
 
    /**
     * 将Base64编码后的私钥转换成PrivateKey对象
     *
     * @param privateKeyBase64 私钥base64
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String privateKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] keyBytes = DECODER.decode((privateKeyBase64));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return keyFactory.generatePrivate(keySpec);
    }
 
    /**
     * 公钥加密
     *
     * @param plaintext       明文
     * @param publicKeyBase64 公钥base64
     * @return 密文数组base64编码后的字符串
     */
    public static String publicKeyEncrypt(String plaintext, String publicKeyBase64) {
        try {
            // 获取明文字节数组
            byte[] bytes = plaintext.getBytes(StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance(RSA);
            // 编码前设定编码方式及密钥
            PublicKey publicKey = getPublicKey(publicKeyBase64);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int keyBit = getKeySize(publicKey);
            int inputLen = bytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            int step = keyBit / 8 - 11;
            for (int i = 0; inputLen - offSet > 0; offSet = i * step) {
                byte[] cache;
                if (inputLen - offSet > step) {
                    cache = cipher.doFinal(bytes, offSet, step);
                } else {
                    cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                ++i;
            }
            // 密文字节数组
            byte[] ciphertextBytes = out.toByteArray();
            out.close();
            // 返回密文字节数组base64编码后的字符串
            return new String(ENCODER.encode(ciphertextBytes), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 公钥解密
     *
     * @param ciphertext      密文
     * @param publicKeyBase64 公钥base64
     * @return 明文
     */
    public static String publicKeyDecrypt(String ciphertext, String publicKeyBase64) {
        try {
            // 密文base64解码字节数组
            byte[] bytes = DECODER.decode(ciphertext.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance(RSA);
            PublicKey publicKey = getPublicKey(publicKeyBase64);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            int keyBit = getKeySize(publicKey);
            int inputLen = bytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            int step = keyBit / 8;
 
            for (int i = 0; inputLen - offSet > 0; offSet = i * step) {
                byte[] cache;
                if (inputLen - offSet > step) {
                    cache = cipher.doFinal(bytes, offSet, step);
                } else {
                    cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                ++i;
            }
            // 明文字节数组
            byte[] plaintextBytes = out.toByteArray();
            out.close();
            return new String(plaintextBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }
 
    /**
     * 私钥加密
     *
     * @param plaintext        明文
     * @param privateKeyBase64 私钥base64
     * @return
     */
    public static String privateKeyEncrypt(String plaintext, String privateKeyBase64) {
        try {
            // 获取明文字节数组
            byte[] bytes = plaintext.getBytes(StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance(RSA);
            // 编码前设定编码方式及密钥
            PrivateKey privateKey = getPrivateKey(privateKeyBase64);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            int keyBit = getKeySize(privateKey);
            int inputLen = bytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            int step = keyBit / 8 - 11;
 
            for (int i = 0; inputLen - offSet > 0; offSet = i * step) {
                byte[] cache;
                if (inputLen - offSet > step) {
                    cache = cipher.doFinal(bytes, offSet, step);
                } else {
                    cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                ++i;
            }
            // 密文字节数组
            byte[] ciphertextBytes = out.toByteArray();
            out.close();
            // 返回密文字节数组base64编码后的字符串
            return new String(ENCODER.encode(ciphertextBytes), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 私钥解密
     *
     * @param ciphertext       密文
     * @param privateKeyBase64 私钥base64
     * @return 明文
     */
    public static String privateKeyDecrypt(String ciphertext, String privateKeyBase64) {
        try {
            // 密文base64解码字节数组
            byte[] bytes = DECODER.decode(ciphertext.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance(RSA);
            PrivateKey privateKey = getPrivateKey(privateKeyBase64);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            int keyBit = getKeySize(privateKey);
            int inputLen = bytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            int step = keyBit / 8;
 
            for (int i = 0; inputLen - offSet > 0; offSet = i * step) {
                byte[] cache;
                if (inputLen - offSet > step) {
                    cache = cipher.doFinal(bytes, offSet, step);
                } else {
                    cache = cipher.doFinal(bytes, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                ++i;
            }
            // 明文字节数组
            byte[] plaintextBytes = out.toByteArray();
            out.close();
            return new String(plaintextBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 使用私钥对数据进行数字签名
     *
     * @param ciphertext       密文
     * @param privateKeyBase64 私钥Base64
     * @return 加密后的base64签名
     */
    public static String sign(String ciphertext, String privateKeyBase64) {
        try {
            // 密文字节数组
            byte[] ciphertextBytes = DECODER.decode(ciphertext.getBytes(StandardCharsets.UTF_8));
            PrivateKey privateKey = getPrivateKey(privateKeyBase64);
            Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
            signature.initSign(privateKey);
            signature.update(ciphertextBytes);
            byte[] signed = signature.sign();
            return new String(ENCODER.encode(signed), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 使用公钥验证数字签名
     *
     * @param ciphertext      密文
     * @param sign            签名
     * @param publicKeyBase64 公钥base64
     * @return 是否篡改了数据
     */
    public static boolean verify(String ciphertext, String sign, String publicKeyBase64) {
        try {
            // 密文base64解码字节数组
            byte[] ciphertextBytes = DECODER.decode(ciphertext.getBytes(StandardCharsets.UTF_8));
            // 签名base64解码字节数组
            byte[] signBytes = DECODER.decode(sign.getBytes(StandardCharsets.UTF_8));
            PublicKey publicKey = getPublicKey(publicKeyBase64);
            Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
            signature.initVerify(publicKey);
            signature.update(ciphertextBytes);
            return signature.verify(signBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * 获取公钥长度
     *
     * @param publicKey 公钥
     * @return
     */
    public static int getKeySize(PublicKey publicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        return rsaPublicKey.getModulus().bitLength();
    }
 
    /**
     * 获取私钥长度
     *
     * @param privateKey 私钥
     * @return
     */
    public static int getKeySize(PrivateKey privateKey) {
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
        return rsaPrivateKey.getModulus().bitLength();
    }
 
}