如何以编程方式生成自签名证书? [英] How to programmatically generate a self signed certificate?

查看:469
本文介绍了如何以编程方式生成自签名证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HSM生成的RSA公钥(2048位),该键已保存在一个文件(大小为256字节)中,并编码为DER。

I have a RSA public key (2048 bit) generated by a HSM, that key has been saved in a file (with a size of 256 byte) and is encoded as DER.

是否可以使用JDK API(无BouncyCastle)从该文件开始以编程方式创建自签名证书?

Is it possibile to programmatically create a self-signed certificate using JDK API (without BouncyCastle) starting from that file?

我坚持使用第一个步骤,因为我正在尝试加载密钥文件以创建PublicKey对象:

I'm stuck with the first step, because I'm trying to load the key file to create a PublicKey object:

import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.commons.io.IOUtils;

public class Crypto {
public static void main(String[] args) throws Exception {

    byte[] byteArray = IOUtils.toByteArray(new FileInputStream("/tmp/pub.key"));

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(byteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey pub = kf.generatePublic(spec);
    ....
}
}

这个异常:

Exception in thread "main" java.security.spec.InvalidKeySpecException: Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys
    at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:289)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:184)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:304)
    at org.alex.Crypto.main(Crypto.java:17)

有办法吗?

推荐答案

使用 X509EncodedKeySpec (内部实际使用PKCS#1编码RSA密钥)。保持代码的其余部分相同。 PKCS#8用于私钥,而不是公钥(因为它使用PKCS#8内部结构,用另一个密钥包装密钥,包装公钥是没有意义的)。

Use X509EncodedKeySpec (which internally actually used PKCS#1 encoding for RSA keys) instead. Keep the rest of the code identical. PKCS#8 is for private keys, not public keys (because it uses the PKCS#8 internal structure required to wrap a key with another key, and wrapping public keys makes no sense).

这篇关于如何以编程方式生成自签名证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆