Score:0

OpenSSL: How to convert ec private key(32byte raw key) to pem type private key?

cn flag

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?

Maarten Bodewes avatar
in flag
I don't think you can do this with a single command from a command line, you'd have to program it.
Score:2
cn flag

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
Erik Aronesty avatar
br flag
these days 90% of cryptography is formatting bytes and base 64 encoded things in the right ways, and the other 10% is cryptography
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.