【发布时间】: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