我有一个由 HSM 生成的 RSA 公钥(2048 位),该 key 已保存在文件中(大小为 256 字节)并编码为 DER。
是否可以从该文件开始使用 JDK API(不带 BouncyCaSTLe)以编程方式创建自签名证书?
我坚持第一步,因为我正在尝试加载 key 文件来创建 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):
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
(内部实际上使用 RSA key 的 PKCS#1 编码)。保持其余代码相同。 PKCS#8 适用于私钥,而不是公钥(因为它使用用另一个 key 包装 key 所需的 PKCS#8 内部结构,并且包装公钥没有任何意义)。
关于java - 如何以编程方式生成自签名证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21410695/