package com.dk.mdm.infrastructure.util;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * RSA加密算法工具类
 */
@Component
public class RSAUtils {

    private RSAUtils() {
    }

    /**
     * 生成公钥私钥对
     *
     * @return 公钥私钥对
     */
    public static RSAKeyPair generateKeyPair() {

        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        keyPairGenerator.initialize(2048);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());

        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

        return new RSAKeyPair(keyPair, publicKey, privateKey);
    }

    /**
     * RSA公钥私钥对
     */
    public static class RSAKeyPair implements java.io.Serializable {

        private static final long serialVersionUID = 1L;

        /**
         * 原始密钥对
         */
        private KeyPair keyPair;

        /**
         * 公钥（Base64编码）
         */
        private String publicKey;

        /**
         * 私钥（Base64编码）
         */
        private String privateKey;

        public RSAKeyPair(KeyPair keyPair, String publicKey, String privateKey) {
            this.keyPair = keyPair;
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public KeyPair getKeyPair() {
            return keyPair;
        }

        public void setKeyPair(KeyPair keyPair) {
            this.keyPair = keyPair;
        }

        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;
        }
    }

}
