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.25k stars 204 forks source link

Adding an externally produced signature into certificate #272

Closed jefjos closed 4 years ago

jefjos commented 4 years ago

Hello,

I have a scenario where I need to create a X.509 certificate from scratch, have it signed externally. This is the way I have gone about doing this

  1. Created a key-pair for this certificate which I am going to create.
  2. Created a certificate object and added fields like issuer, subject, extensions etc
    
    const cert = new Certificate();
    cert.version = 3;
    cert.serialNumber = new asn1js.Integer({ value: Date.now() });
    // more code to add fields to certificate.

3. Got the TBS portion of this certificate.
`const tbs = cert.encodeTBS().toBER(false);`

4. Then I used nodejs crypto library to calculate digest.
5. Then I get the tbs signed.
6. Since the signing algorithm used is ECDSA,  I also did the following on the signature
`      const signatureArrayBuf = createCMSECDSASignature(toArrayBuffer(signature));`
7. Now I add the signature value to the certificate        
`cert.signatureValue = new asn1js.BitString({ valueHex: signatureArrayBuf });`
8. Now I encode the cert tin PEM 
  const certBase64 = Buffer.from(cert.toSchema(true).toBER(false)).toString('base64');
  const certPem = [
    "-----BEGIN CERTIFICATE-----",
    certBase64,
    "-----END CERTIFICATE-----"
  ].join("\n");

9. Loading this using openssl 
`openssl x509 -in cert2.pem -noout -text`

Now I get the error
`9288:error:0D0BD098:asn1 encoding routines:c2i_ASN1_BIT_STRING:string too short:crypto\asn1\a_bitstr.c:137:`

It appears I may not have set the signature correctly. Could you please help me understand what I'm doing wrong?
YuryStrozhevsky commented 4 years ago

@jefjos After a first inspection seems you done almost same as standard sign() function. So, any additional comment I can give only if you provide me your certificate for analysis.

jefjos commented 4 years ago

@YuryStrozhevsky Well, it seems I didnt test it correctly yesterday. It is working as expected. Thanks!