java - 如何在不使用命令行工具的情况下从现有的一组证书和 key 创建 Java KeyStore?

标签 java security ssl

我从另一个服务获得随机生成的 RSA 证书和私钥作为字符串,并且我想使用这些字符串创建 Java KeyStore。我看到的所有示例都涉及将这些字符串保存到文件中,使用 openssl 和 keytool 命令行工具在磁盘上创建 keystore ,然后将生成的 keystore 加载到内存中(例如 here )。然而,对于我的目的来说,完全在内存中创建 KeyStore 更有意义。

为此,我尝试使用 Java Security API。我能够将证书字符串转换为 java.security.cert.Certificate 的实例类,但我无法将私钥转换为 java.security.PrivateKey 的实例。这是我尝试创建的方法:

private PrivateKey generatePrivateKey (String newKey) 
    throws NoSuchAlgorithmException,
    InvalidKeySpecException, IOException {

//Configuring the KeyFactory to use RSA
KeyFactory kf = KeyFactory.getInstance("RSA");

//Convert the key string to a byte array
byte[] keyBytes = newKey.getBytes();

KeySpec ks = new PKCS8EncodedKeySpec(keyBytes);

PrivateKey key = kf.generatePrivate(ks);
return key;
}    

其中 newKey 的值类似于 "-----BEGIN RSA PRIVATE KEY-----\nMIIEow...gNK3x\n-----END RSA PRIVATE KEY-----"

当我运行代码时,我收到以下异常:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
... 30 more
Caused by: java.security.InvalidKeyException: invalid key format
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:341)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 32 more

此特定错误与 this 非常相似stackoverflow 问题,如果该问题得到解决,我将不胜感激,但我也想知道我的更高级别目标(使用 Java 以编程方式仅在内存中创建 JKS)是否可行,如果是,我是否是正确的路径。

最佳答案

如果您的 key 采用 Base64 表示形式,则需要解码 Base64:

KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodeBase64(newKey));

您可以使用 org.apache.commons.codec.binary.Base64 来执行此操作。

如果你想生成 key 对,你可以使用以下代码:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();

// extract the encoded private key, this is an unencrypted PKCS#8 private key
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
System.out.println(Base64.encodeBase64String(encodedprivkey));

关于java - 如何在不使用命令行工具的情况下从现有的一组证书和 key 创建 Java KeyStore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364894/

相关文章:

java - 我可以以某种方式从新的 Java 程序运行以前编译的 Java 字节码吗?

java - 使用 Maven- assembly-plugin 构建 Java 项目,并使用 tar 存储库更深的目录

c# - AWS SNS 从 Apple APNS 的 .p12 文件中获取证书和私钥

java - Java : Path does not chain with any of the trust anchors 上的 SSL 异常

Apache 2.2,(.htaccess 中的 MOD_SSL 和 Mod_rewrite

Java - 单元测试

java - 如何保存 JPanel 的特定部分?

linux - 为什么受密码保护的根账户是 Amazon EC2 中的安全问题?

ruby-on-rails - 在用户数据库中包含帐户信息

security - 摘要认证的概念——它真的有效吗?