3
$\begingroup$

I have a 32 byte octet string ec private key.

And I want to convert this to pem type private key.

I use the secp256r1 curve.

How can I do that?

Is any command or method for that?

$\endgroup$
1
  • $\begingroup$ I don't think you can do this with a single command from a command line, you'd have to program it. $\endgroup$
    – Maarten Bodewes
    Jan 7, 2022 at 2:55

1 Answer 1

5
$\begingroup$

Meta: this is not really about cryptography, but use of a tool for data processing only partly related to crypto; but since no one voted to close (that I can see) I'll go ahead. This can be deleted if necessary.

Not exactly, but there is a command option to build arbitrary ASN.1 data, which can be adapted for this with a little work, if you have the desired private-value in 'plain' hex: on Unix (if it isn't already hex) you can convert with xxd -p -c32 or od -An -tx1 | tr -d ' \n' or similar, on Windows you're on your own. Given a file with the following contents except substituting your desired private value:

asn1=SEQ:pkcs8c
[pkcs8c]
ver=INT:0
algid=SEQ:algid
data=OCTWRAP,SEQ:sec1
[algid]
alg=OID:id-ecPublicKey
parm=OID:prime256v1
[sec1]
ver=INT:1
privkey=FORMAT:HEX,OCT:0123456789ABCDEFFEDCBA98765432100123456789ABCDEFFEDCBA9876543210

then openssl asn1parse -genconf filename -noout [-out derfile] will create the PKCS8-clear format in DER, and appending | openssl pkey -inform der will convert it to PEM. Or on Unix you can convert to PEM 'manually' with ... | { printf '%s\n' '-----BEGIN PRIVATE KEY-----'; openssl base64; printf '%s\n' '-----END PRIVATE KEY-----'; }

Alternatively and more hackily, the DER encoding of the structure described above is all constant except for the private-value which occurs last, so you can simply concatenate the constant part with the private-value to get PKC8-clear DER, then convert to PEM as above:

# on Unix, given the 32 bytes in binary in file rawfile:
printf '\x30\x41\x02\x01\x00\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x04\x27\x30\x25\x02\x01\x01\x04\x20'; cat rawfile;
# creates DER, and putting that in { } or ( ) and piping the result to
# pkey -inform der or the manual alternative above converts to PEM
$\endgroup$
1
  • $\begingroup$ these days 90% of cryptography is formatting bytes and base 64 encoded things in the right ways, and the other 10% is cryptography $\endgroup$ Feb 8 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.