PeculiarVentures / PKI.js

PKI.js is a pure JavaScript library implementing the formats that are used in PKI applications (signing, encryption, certificate requests, OCSP and TSP requests/responses). It is built on WebCrypto (Web Cryptography API) and requires no plug-ins.
http://pkijs.org
Other
1.3k stars 204 forks source link

Convert certificate to PEM OR verify certificate chain help #225

Closed kate1012 closed 5 years ago

kate1012 commented 5 years ago

I had some code done verifying a certificate chain from certificates in PEM format. I would like to keep that piece of code if possible, and use the certificates retrieved from the SignedData and convert them to PKCS7 PEM format. Is that possible? If not, can someone please give me a simple example on how I could take those certificates and verify them against the root certificate? I'm looking through the examples but am having some difficulty understanding. Thanks!

rmhrisk commented 5 years ago

SignedData a message type in actually PKCS7 or CMS.

It sounds like you want to create a .p7b (application/x-pkcs7-certificates). e.g. a PKCS7/CMS that contains just certs.

The ASN.1 for this looks like:

   SignedData ::= SEQUENCE {
     version Version,
     digestAlgorithms DigestAlgorithmIdentifiers,
     contentInfo ContentInfo,
     certificates
        [0] IMPLICIT ExtendedCertificatesAndCertificates
          OPTIONAL,
     crls
       [1] IMPLICIT CertificateRevocationLists OPTIONAL,
     signerInfos SignerInfos }

Where the certificates contains the certs and nothing else is set.

You would base64 this and then add the appropriate PEM armor:

----BEGIN PKCS7-----
-----END PKCS7-----

This process is more-or-less what the following openssl command would do:

openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b

Here is a link that shows what such a file would look like.

You can see an example of working with this sample: https://pkijs.org/examples/P7BSimpleExample.html

The source of which is here: https://github.com/PeculiarVentures/PKI.js/tree/master/examples/P7BSimpleExample

YuryStrozhevsky commented 5 years ago

@kate1012 In order to convert to PEM from SignedData certificates you need something like this:

if("certificates" in signedData)
{
    for(const element of signedData.certificates)
    {
        let pem = formatPEM(toBase64(arrayBufferToString(element.toSchema().toBER(false))));
        pem = `-----BEGIN CERTIFICATE-----\n${pem}\n-----END CERTIFICATE-----`
    }
}

The formatPEM function you can get here, the toBase64 and arrayBufferToString functions are from pvutils package.

kate1012 commented 5 years ago

@YuryStrozhevsky thanks that was exactly what I needed :)