我无法使用X509证书获取公钥。在尝试生成认证时,我收到错误“签名字段无效”。请帮忙
用于生成密钥的代码:
public static PublicKey getPublicKey() throws CertificateException,FileNotFoundException {
InputStream certFileIs = new FileInputStream("E:\\TA_Private.pfx");
CertificateFactory certfactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certfactory.generateCertificate(certFileIs);
PublicKey key = cert.getPublicKey();
return key;
}
控制台输出:
java.security.cert.CertificateParsingException: signed fields invalid
at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1768)
at sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:196)
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:97)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
at Keygenerator.getPublicKey(Keygenerator.java:45)
at KeyMain.main(KeyMain.java:20)
答案 0 :(得分:0)
解析文件失败。实际上,由于您的文件名为TA_Private.pfx,因此我认为该文件不是X509证书而是PKCS#12文件(即可以包含密钥和证书的文件,用于交换秘密材料)系统之间)
要阅读PKCS#12文件,您可以使用public PublicKey loadPKCS#12(String filePath, char[] password) throws Exception {
InputStream is = null;
KeyStore ks = KeyStore.getInstance("PKCS12");
try {
is = new FileInputStream(filePath);
ks.load(is, password);
for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
String alias = e.nextElement();
if (ks.isCertificateEntry(alias)) {
Certificate cert = ks.getCertificate(alias);
return cert.getPublicKey();
}
}
return null;
} finally {
if (is != null) {
is.close();
}
}
}
类:
private void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData==null){
updateDisplayForError();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i=0; i<jsonPosts.length(); i++){
JSONObject posts = jsonPosts.getJSONObject(i);
String title = posts.getString(KEY_TITLE); //"title"
title = Html.fromHtml(title).toString();
String author = posts.getString(KEY_AUTHOR); //"author"
author = Html.fromHtml(author).toString();
String time = posts.getString((KEY_TIME)); //"time"
time = Html.fromHtml(time).toString();
String icon = posts.getString(KEY_ICON); //"icon" (icons url)
icon = Html.fromHtml(icon).toString();
这是一个非常简单的示例,它提取第一个找到的证书的公钥。但是,PKCS#12可以包含多个证书。