package com.qmth.boot.tools.crypto;

import com.qmth.boot.tools.models.RsaKeyPair;

import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.WeakHashMap;

/**
 * RSA加解密工具
 */
public class RSA {

    private static final String ALGORITHM = "RSA";

    private static final int KEY_SIZE = 1024;

    private static WeakHashMap<String, RSAPublicKey> publicKeyMap = new WeakHashMap<>();

    private static WeakHashMap<String, RSAPrivateKey> privateKeyMap = new WeakHashMap<>();

    /**
     * 生成公钥私钥组，长度默认1024
     *
     * @return
     * @throws Exception
     */
    public static RsaKeyPair generateKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM);
        generator.initialize(KEY_SIZE);
        return new RsaKeyPair(generator.generateKeyPair());
    }

    /**
     * 使用二进制内容构造公钥
     *
     * @param key
     * @return
     */
    public static RsaHelper getPublicKey(byte[] key) {
        return () -> (RSAPublicKey) (KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(key)));
    }

    /**
     * 使用二进制内容构造私钥
     *
     * @param key
     * @return
     */
    public static RsaHelper getPrivateKey(byte[] key) {
        return () -> (RSAPrivateKey) (KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(key)));
    }

}
