RSA读取公钥/私钥

1、首先创建一个接口类IKeyReader

public interface IKeyReader {
    /**
     * 从keystore文件里读取公钥
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件类型,一般为JKS 
     * @param kstorepwd keystore文件密码
     * @param alias 密钥别名
     * @return 公钥
     */    
    public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias);
    
    /**
     * 从keystore文件里读取私钥
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件类型,一般为JKS 
     * @param kstorepwd keystore文件密码
     * @param alias 密钥别名
     * @param keypwd 密钥密码
     * @return 私钥
     */
    public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias,String keypwd);
    /**
     * 从DER编码公钥文件里读取公钥
     * @param CRTfile DER编码公钥文件
     * @return 公钥
     */
    public PublicKey getPublickey(String CRTfile);
    /**
     * 从DER编码私钥文件里读取私钥
     * @param DERfile DER编码私钥文件
     * @return  私钥
     */
    public PrivateKey getPrivatekey(String DERfile);
    /**
     * 从keystore文件里读取公钥内容,以Base64编码输出
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件类型,一般为JKS 
     * @param kstorepwd keystore文件密码
     * @param alias 密钥别名
     * @return  公钥内容(经Base64编码)
     */
    public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias);


2、 创建一个接口实现类

public class KeyReader implements IKeyReader {

    private static final Logger log = LoggerFactory.getLogger(KeyReader.class);

    public KeyReader() {
        log.info("构造函数=====555555555555555555555555555555555");
    }

    /**
     * 从密钥文件中读取公钥
     *
     * @param kstorefile 密钥文件
     * @param kstoretype 密钥文件类型,例如:JKS
     * @param kstorepwd 密钥文件访问密码
     * @param alias 别名
     * @return 公钥
     */
    @Override
    public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias) {

        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            Certificate cert = ks.getCertificate(alias);
            return cert.getPublicKey();
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }

    /**
     * 从密钥文件中读取私钥
     *
     * @param kstorefile 密钥文件
     * @param kstoretype 密钥文件类型,例如:JKS
     * @param kstorepwd 密钥文件访问密码
     * @param alias 别名
     * @return 私钥
     */
    @Override
    public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias, String keypwd) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            return (PrivateKey) ks.getKey(alias, keypwd.toCharArray());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        }
    }

    @Override
    public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            X509Certificate cert = (X509Certificate) ks.getCertificate(alias);

            return Base64.encodeBase64String(cert.getEncoded());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }

    @Override
    public PrivateKey getPrivatekey(String DERfile) {
        PrivateKey privateKey = null;
        try {
            InputStream in = null;
            byte[] key = new byte[2048];
            in = new FileInputStream(DERfile);
            in.read(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
            log.error("私钥证书文件格式错误",ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(),ex);
        } 
        return privateKey;
    }

    @Override
    public PublicKey getPublickey(String CRTfile) {
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            FileInputStream bais = new FileInputStream(CRTfile);
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
            return Cert.getPublicKey();
        } catch (CertificateException | FileNotFoundException ex) {
            log.warn("getPublicKey failure", ex);
        }
        return null;
    }

    private byte[] getPemFileBytes(String fileName) {
        BufferedReader br;
        byte[] key = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
            String s = br.readLine();
            String str = "";
            s = br.readLine();
            while (s.charAt(0) != '-') {
                str += s + "\r";
                s = br.readLine();
            }
            key = Base64.decodeBase64(str);
        } catch (Exception ex) {
            log.warn("read pem file failure.", ex);
        }

        return key;
    }



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值