从 Java 中的 .p12 文件获取 PrivateKey 对象 [英] Getting a PrivateKey object from a .p12 file in Java

查看:23
本文介绍了从 Java 中的 .p12 文件获取 PrivateKey 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的,我有 .p12 文件,用于访问 google 服务帐户 api.为了获得连接到 api 的凭据,有一个字段 .setServiceAccountPrivateKey(PrivateKey privateKey).那么,我可以做到这一点的最简单方法是什么?我有一个资源文件夹,它在我的类路径中,所以如果我在那里添加 p12 文件,我可以从 getClass().getResource() 获取资源作为 inputStream 或 URL.我已经尝试了 URL 方法,但它不起作用(尝试从 URL.toURI() 创建 File 对象时出现URI 不是分层的"错误).

As the title suggests, I have .p12 file required for google service account api access. In order to get the credential to connect to the api, there's a field .setServiceAccountPrivateKey(PrivateKey privateKey). So, what's the easiest way in which I can do this? I have a resources folder which is in my classpath so if I add the p12 file there, I can get the resource from getClass().getResource() as either an inputStream or a URL. I've tried the URL method but it doesn't work (I get a "URI is not hierarchical" error trying to create a File object from URL.toURI()).

推荐答案

您可以使用 ClassLoader.getResourceAsStream(String) 方法加载您的 .p12 文件,将其加载到 KeyStore 并获得来自 KeyStore 的密钥.

You can load your .p12 file using the ClassLoader.getResourceAsStream(String) method, load it to a KeyStore and them get the key from the KeyStore.

KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(this.getClass().getClassLoader().getResourceAsStream("keyFile.p12"), p12Password.toCharArray());
PrivateKey key = (PrivateKey)keystore.getKey(keyAlias, p12Password.toCharArray());

ClassLoader.getResourceAsStream(String) 从任何位置加载资源,前提是它们已经在类路径上,无需指定文件路径.

ClassLoader.getResourceAsStream(String) loads resources from any location provided they're already on the classpath, there's no need to specify a path to the file.

keyAlias 是 p12 文件中与私钥对应的条目的名称.PKCS12 文件可以包含多个条目,因此您需要某种方式来指示要访问的条目.别名是如何实现的.

keyAlias is the name of the entry in your p12 file that corresponds to the private key. PKCS12 files can contain multiple entries, so you need some way to indicate which entry you want to access. The alias is how this is achieved.

如果您不确定您的私钥的别名是什么,您可以从命令行使用 keytool 实用程序来列出您的 p12 文件的内容.此工具包含在所有 JRE 和 JDK 安装中.

If you're not sure what the alias for your private key is, you can use the keytool utility from the command line to list the contents of your p12 file. This tool is included with all JRE and JDK installations.

keytool -list -keystore keyFile.p12 -storepass password -storetype PKCS12

输出

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

yourKeyAlias, Sep 4, 2013, PrivateKeyEntry,
Certificate fingerprint (MD5): 48:A8:C4:12:8E:4A:8A:AD:58:81:26:90:E7:3D:C8:04

这篇关于从 Java 中的 .p12 文件获取 PrivateKey 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆