节点JS,如何从P12文件中提取X.509证书? [英] Node JS, how to extract X.509 Certificate from P12 file?

查看:182
本文介绍了节点JS,如何从P12文件中提取X.509证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 p12 文件,该文件应获得X.509证书.为了使用此文件,我使用了 forge 库:

I have p12 file, where I should get X.509 Certificate. In order to work with this file I use forge library:

var forge = require('node-forge');
var fs = require('fs');

var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'binary');
var p12Asn1 = forge.asn1.fromDer(keyFile);

var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password');

var bags = p12.getBags({bagType: forge.pki.oids.certBag});

var cert = bags[forge.pki.oids.certBag][0];

console.log(cert);

控制台向我输出这种信息:

Console outputs to me this kind of information:

{ type: '1.2.840.113549.1.12.10.1.3',
  attributes:
  { localKeyId: [ 'aoa ??xx\u0015-?]%m§ §\f,\u0013' ],
    friendlyName: [ 'e56fe5a0899f787815adaf5d256da7a0a70c2c13' ] },
    cert: null,
    asn1:
    { tagClass: 0,
      type: 16,
      constructed: true,
      composed: true,
      value: [ [Object], [Object], [Object] ] } }

此结果意味着我有一个别名为 e56fe5a0899f787815adaf5d256da7a0a70c2c13 的别名,但是为什么 cert null ?

This result means that I have an alias with name e56fe5a0899f787815adaf5d256da7a0a70c2c13, but why cert is null?

有Java的安全性api,它可以通过其别名从此p12文件中提取X.509证书.

There is Java's security api's, which is able to extract X.509 certificate from this p12 file by it's alias.

X509Certificate x509Certificate = (X509Certificate) ks.getCertificate(alias);

如何使用 forge p12 文件中提取X.509证书?

How it is possible to extract X.509 certificate from p12 file by using forge?

节点版本 5.4.1

伪造版本 0.6.45

您可以在此处下载我的测试p12文件:链接

There you can download my testing p12 file: link

密码是 123456

推荐答案

根据[

如果forge无法识别密钥格式,则它将为返回null.密钥包中的key属性,并用raw设置asn1属性密钥的ASN.1表示形式.

If forge doesn't recognize the key format, it will return null for the key property in the key bag, and set an asn1 property with the raw ASN.1 representation of the key.

因此,您需要 转换为ASN.1,然后转换为DER,然后进行PEM编码 :

So, you need convert to ASN.1, then DER, then PEM-encode:

var forge = require('node-forge');
var fs = require('fs');

var keyFile = fs.readFileSync("./gost.p12", 'binary');
var p12Asn1 = forge.asn1.fromDer(keyFile);

var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, '123456');

var bags = p12.getBags({bagType: forge.pki.oids.certBag});

var bag = bags[forge.pki.oids.certBag][0];

// convert to ASN.1, then DER, then PEM-encode
var msg = {
  type: 'CERTIFICATE',
  body: forge.asn1.toDer(bag.asn1).getBytes()
};
var pem = forge.pem.encode(msg);

console.log(pem);

这篇关于节点JS,如何从P12文件中提取X.509证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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