Java 如何以编程方式生成自签名证书?

Java 如何以编程方式生成自签名证书?,java,cryptography,Java,Cryptography,我有一个由HSM生成的RSA公钥(2048位),该密钥已保存在一个文件中(大小为256字节),并编码为DER 是否可以从该文件开始使用JDK API(不带BouncyCastle)以编程方式创建自签名证书 我被第一步卡住了,因为我正试图加载密钥文件以创建公钥对象: import java.io.FileInputStream; import java.security.KeyFactory; import java.security.PublicKey; import java.security

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

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

我被第一步卡住了,因为我正试图加载密钥文件以创建公钥对象:

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)

有办法吗?

例外情况是告诉您问题!=><代码>RSA公钥仅支持RSACublicKeySpec和X509EncodedKeySpec

您正在尝试使用不受支持的
PKCS8EncodedKeySpec
,请创建
RSAPublicKeySpec
X509EncodedKeySpec

范例

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");

KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
    "12345678", 16), new BigInteger("11", 16));
RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
    "12345678", 16), new BigInteger("12345678",
    16));

RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

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

链接可能会有所帮助:负责证书创建的代码在哪里?