2017-05-17 317 views
-1

這裏我們試圖在RunTime期間使用客戶機私鑰創建密鑰庫。 我們正在將privateKey加載到密鑰庫中時遇到。使用RSA私鑰創建密鑰庫

JKS類型:

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) 

請幫助解決這個問題。

+0

私鑰不是一個基石,任何格式。不清楚你在問什麼,或者試圖,或者你爲什麼會認爲這會起作用。 – EJP

回答

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.