kjur / jsrsasign

The 'jsrsasign' (RSA-Sign JavaScript Library) is an opensource free cryptography library supporting RSA/RSAPSS/ECDSA/DSA signing/validation, ASN.1, PKCS#1/5/8 private/public key, X.509 certificate, CRL, OCSP, CMS SignedData, TimeStamp, CAdES and JSON Web Signature/Token in pure JavaScript.
https://kjur.github.io/jsrsasign
Other
3.27k stars 643 forks source link

pkcs#8 Private Key DER binary input file #572

Closed gdjorgeluis closed 1 year ago

gdjorgeluis commented 1 year ago

Hi, I'm using Jsrsasign in a new project with React. I am wondering if there is a way to read a private key in DER format and then convert it to PEM format for use.

I´m using this for read a certificate in DER format after read it with FileReader API with readAsBinaryString()

var hexDerFileContents = rstrtohex(contenido); // raw string to hex var private_key= KJUR.asn1.ASN1Util.getPEMStringFromHex(hexDerFileContents, "CERTIFICATE"); // with PEM Header. And it worked!

I tried using something similar substituting "CERTIFICATE" with "RSA PRIVATE KEY" and then: KEYUTIL.getKey(private_key, pass_code)

but got this error:

Uncaught (in promise) Error: unsupported PKCS#1/5 hexadecimal key

I hope you can help me. Thanks!

kjur commented 1 year ago

Hi,

When the key is PKCS8, you should use "PRIVATE KEY" PEM header not "RSA PRIVATE KEY". The "RSA PRIVATE KEY" PEM header will be used for PKCS1 or PKCS5 private key.

gdjorgeluis commented 1 year ago

I changed as you said var private_key = KJUR.asn1.ASN1Util.getPEMStringFromHex(hexDerFileContents, "PRIVATE KEY"); and then var key= KEYUTIL.getKey(private_key,pass_code); And got this error:
Uncaught Error: malformed plain PKCS8 private key(code:001) at Object.parsePlainPrivatePKCS8Hex (jsrsasign.js:238:1) at Object.getKeyFromPlainPrivatePKCS8Hex (jsrsasign.js:238:1) at Object.getKeyFromPlainPrivatePKCS8PEM (jsrsasign.js:238:1) at KEYUTIL.getKey (jsrsasign.js:238:1) at FR.onload (Util.js:61:1)

I think the key isn't malformed because with this command: openssl pkcs8 -inform DER -in der_format_key.key | openssl rsa -out pem_format_pkcs5.cve -aes128 I convert the key and can sign with it

Thanks!

kjur commented 1 year ago

Sorry but It seems unsupported encryption algorithm of PKCS8.