![](/img/trans.png)
[英]How to convert java.security.PrivateKey object to org.bouncycastle.asn1.pkcs.RSAPrivateKey object
[英]How to convert Base64 encoded pkcs12 content to java.security.PrivateKey?
我正在通过服务帐户使用Google Directory API,并且在创建服务帐户时收到了pkcs12
密钥。
Google确实支持两种不同的使用方式,即使用密钥作为java.io.File
或java.security.PrivateKey
,对于PoC,我使用的第一种方式是使用java.io.File
创建GoogleCredential
对象,
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
.setServiceAccountUser(serviceAccountUser)
.setServiceAccountPrivateKeyFromP12File(serviceAccountPrivateKeyFile)
.build();
它按预期工作,但在我的实际用例中,我不能依赖文件系统,因此无法使用第一种方法。 所以我想用第二种方法来实现实际用例,即使用java.security.PrivateKey
,完成后看起来像下面的样子。
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
.setServiceAccountUser(serviceAccountUser)
.setServiceAccountPrivateKey(serviceAccountPrivateKey)
.build();
在我的用例中,我需要上载私钥并将其以base64编码存储在数据库中。 现在,我需要传递pkcs12
键的内容并创建Googlecredential
对象。 我想第二种选择是最合适的方法,但是找不到任何示例来从上传密钥的base64编码内容创建java.security.PrivateKey。
是否可以从pkcs12
密钥的base64编码内容创建java.security.PrivateKey
对象?
还是有其他方法可以实现我的用例?
提前致谢
DarRay
java.securty.KeyStore将任何InputStream用作load()方法,因此您可以使用获取.p12字节的任何方法来创建它。 这是我使用的另一种方法。 尽管这仍然使用.p12字节的文件,但是您可以引入ByteArrayInputStream或任何InputStream子类:
private PrivateKey getPrivateKeyFromP12() {
// Google p12 files all have "notasecret" as the pass and "privatekey" as the PK name
String p12p = "notasecret"; // not cool! Change this before exporting your .p12
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
// This is where you'd adjust to bring in your .p12 bytes or chars
// as an input stream. Passwords are a char array!
keystore.load(
this.getClass().getClassLoader()
.getResourceAsStream("the.p12"),
p12p.toCharArray());
// This key name is fixed by Google, but could be changed
PrivateKey key = (PrivateKey) keystore.getKey("privatekey",
p12p.toCharArray());
return key;
} catch (Exception e) {
LOG.error("Exception while trying to obtain private key",e);
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.