使用RSA私钥创建密钥库

时间:2017-05-17 09:47:39

标签: java keystore

这里我们尝试在RunTime期间使用客户端私钥创建密钥库。 我们在将privateKey加载到密钥库时面临着。

JKS TYPE:

clientKey=-----BEGIN RSA PRIVATE KEY----- ...-----END RSA PRIVATE KEY-----"
KeyStore keyStore = KeyStore.getInstance("JKS");

keyStore.load(new ByteArrayInputStream(clientKey.getBytes()), "*********".toCharArray());

Exception:
java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:658)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:56)
at sun.security.provider.KeyStoreDelegator.engineLoad(KeyStoreDelegator.java:224)
at sun.security.provider.JavaKeyStore$DualFormatJKS.engineLoad(JavaKeyStore.java:70)

PKCS12类型:

clientKey=-----BEGIN RSA PRIVATE KEY----- ...-----END RSA PRIVATE KEY-----"

KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new ByteArrayInputStream(clientKey.getBytes()), "*********".toCharArray());

Exception:
java.io.IOException: toDerInputStream rejects tag type 45
at sun.security.util.DerValue.toDerInputStream(DerValue.java:847)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1915)
at java.security.KeyStore.load(KeyStore.java:1445)

请帮助解决此问题。

1 个答案:

答案 0 :(得分:0)

您的clientKey有首尾标题。您必须将其删除,然后解码密钥并将其提供给ByteArrayInputStream

您可以删除-----BEGIN RSA PRIVATE KEY----------END RSA PRIVATE KEY-----

clientKey = clientKey.replace("-----BEGIN RSA PRIVATE KEY-----", "");
clientKey = clientKey.replace("-----END RSA PRIVATE KEY-----", "");

然后你剩下的就是Base64编码格式(PEM)。如果它不是base64编码格式,则需要识别编码类型并对其进行解码。如果是base64编码,您可以执行以下操作来解码:

new ByteArrayInputStream(Base64.decode(clientKey)); // <-- clientKey here is without the headers.