繁体   English   中英

如何在不使用命令行工具的情况下从现有的证书和密钥集中创建Java KeyStore?

[英]How can I create a Java KeyStore from an existing set of certificates and keys without using command line tools?

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

为此,我正在尝试使用Java安全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

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

如果您的密钥位于base64表示形式中,则需要解码base64:

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

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

如果要生成keyPair,可以执行以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM