从PHP中的PKCS7签名中提取证书 [英] Extract certificate from a PKCS7 signature in php
问题描述
我需要从pkcs7签名文件中提取用户证书.我可以使用以下命令通过命令行进行操作:
I need to extract the user certificate from a pkcs7 signature file. I can do it via the command line using the following:
openssl pkcs7 -in somesign.pks7 -inform PEM -print_certs
这将为我提供整个证书链,我可以处理生成的文件以提取所需的文件.
This will give me the entire certificate chain and I can process the resulting file to extract what I want.
openssl_pkcs7_命令有没有办法做到这一点?我看到openssl_pkcs7_verify具有$ outfilename用来存储证书的位置,但是我没有签名的消息,但是似乎$ filename应该同时具有签名和消息,这不是我的情况(签名位于单独的位置)文件).
Is there any way to do that with the openssl_pkcs7_ commands? I saw that openssl_pkcs7_verify has the $outfilename where the certs would be stored but I don't have the signed message, but it seems the $filename should have both the signature and the message, which is not my case (signature is in a separate file).
推荐答案
我不知道有一个带有直接API的PHP库.
I'm not aware of a PHP library with straightforward API for this.
我已经实现了几个库,但是可以帮助完成该任务. asn1 , x509 是可通过作曲家获得.
I've implemented several libraries however that could help with the task. asn1, crypto-util and x509 are available via composer.
这是一个准概念证明,可从PKCS7 PEM文件中提取所有证书:
Here's a barebones proof of concept that extracts all certificates from a PKCS7 PEM file:
<?php
use ASN1\Element;
use ASN1\Type\Constructed\Sequence;
use CryptoUtil\PEM\PEM;
use X509\Certificate\Certificate;
require __DIR__ . "/vendor/autoload.php";
$pem = PEM::fromFile("path-to-your.p7b");
// ContentInfo: https://tools.ietf.org/html/rfc2315#section-7
$content_info = Sequence::fromDER($pem->data());
// SignedData: https://tools.ietf.org/html/rfc2315#section-9.1
$signed_data = $content_info->getTagged(0)->asExplicit()->asSequence();
// ExtendedCertificatesAndCertificates: https://tools.ietf.org/html/rfc2315#section-6.6
$ecac = $signed_data->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet();
// ExtendedCertificateOrCertificate: https://tools.ietf.org/html/rfc2315#section-6.5
foreach ($ecac->elements() as $ecoc) {
$cert = Certificate::fromASN1($ecoc->asSequence());
echo $cert->toPEM() . "\n";
}
ASN.1处理非常容易出错.我已经从上面的示例中省略了所有的健全性检查,但是基础库将在错误时引发异常.
ASN.1 handling is very error-prone. I've omitted all sanity checks from the above example, but the underlying library will throw exceptions on errors.
我希望这能提供一些指导,以防有人需要解析PKCS#7结构而不依赖外部程序.
I hope this gives some pointers in case someone needs to parse PKCS #7 structures without relying on external programs.
这篇关于从PHP中的PKCS7签名中提取证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!