【问题标题】:How to programmatically generate a self signed certificate?如何以编程方式生成自签名证书?
【发布时间】:2014-01-29 03:23:26
【问题描述】:

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

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

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

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)

有没有办法做到这一点?

【问题讨论】:

标签: java cryptography


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    异常告诉你问题! => Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys

    您正在尝试使用PKCS8EncodedKeySpec,不支持,请创建RSAPublicKeySpecX509EncodedKeySpec

    例子

    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);
    

    【讨论】:

    • 以及负责创建证书的代码在哪里?
    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多