package com.ho.user.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author fancl
 * @desc: RSA组件类
 * @date 2022/11/14
 */
@Component
@Slf4j
public class RsaConfig {

    //
    @Value("${rsa.pubKey}")
    private String rsaPubKey;

    @Value("${rsa.privateKey}")
    private String rsaPrivateKeyPath;

    //@Bean
    //todo 后续需要读取文件内容
    RSAPrivateKey rsaPrivateKey() throws Exception{
        log.info("初始化RSA私钥");
        File f = new File(rsaPrivateKeyPath);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int)f.length()];
        dis.readFully(keyBytes);
        dis.close();
        PKCS8EncodedKeySpec spec =new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        log.info("RSA私钥初始化完毕");

        return (RSAPrivateKey)kf.generatePrivate(spec);
    }



}
