stacks-network / key-encoder-js

Library for encoding and decoding ecdsa private keys and converting between formats
MIT License
44 stars 27 forks source link

Cannot convert PEM file to DER by using openssl tool #32

Open hailq opened 2 years ago

hailq commented 2 years ago

I'm trying to convert ethereum private key to DER format but get an error. Below are the steps:

First I use web3 to create new ethereum account that has the following key: private key = 0x45a84f0899393274a9aa0ba3b86277543fc7f3ac508390a3b492fb88ac189dd1

Run key-encoder code:

var KeyEncoder = require('key-encoder').default,
    keyEncoder = new KeyEncoder('secp256k1')

var rawPrivateKey = '0x45a84f0899393274a9aa0ba3b86277543fc7f3ac508390a3b492fb88ac189dd1',

var pemPrivateKey = keyEncoder.encodePrivate(rawPrivateKey, 'raw', 'pem', 'pkcs8') //default is 'pkcs1'

console.log(pemPrivateKey)

It outputs:

-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIEWoTwiZOTJ0qaoLo7hid1Q/x/OsUIOQo7SS+4isGJ3RoAcGBSuBBAAK
oUQDQgAEQ29JqkXW6Bi9Hq1n2frYRNDnt5LUivt6lH36sXh61b4rQADSMvagnjlx
R0zS2n8Ue5t0bm/1W3h63JOCC68N5w==
-----END EC PRIVATE KEY-----

I save it to eth_private.pem file. Then I try to use openssl tool to covnert it to DER with this command: openssl pkcs8 -inform PEM -outform DER -topk8 -nocrypt -in eth_private.pem -out eth_private.der

It raises this error:

unable to load key
4669285888:error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag:crypto/asn1/tasn_dec.c:1149:
4669285888:error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error:crypto/asn1/tasn_dec.c:309:Type=X509_ALGOR
4669285888:error:0D08303A:asn1 encoding routines:asn1_template_noexp_d2i:nested asn1 error:crypto/asn1/tasn_dec.c:646:Field=pkeyalg, Type=PKCS8_PRIV_KEY_INFO
4669285888:error:0907B00D:PEM routines:PEM_read_bio_PrivateKey:ASN1 lib:crypto/pem/pem_pkey.c:88:

I'm not sure if the problem with the private key cause it works when I try the private key in project sample.

john-nv commented 4 months ago

you use openssl req -new -key .\privateKey.pem -out privateCRS.der