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.28k stars 645 forks source link

Convert EC hexadecimal string public key to PEM #574

Closed hnamzian closed 1 year ago

hnamzian commented 1 year ago

I have generated keypair using ECDSA generateKeyPairHex function the generates hexadecimal string EC key pair.

var ec = new KJUR.crypto.ECDSA({'curve': 'secp256k1'}); var keypair = ec.generateKeyPairHex(); I want to convert the public key or private key to PubKeyObj or PEM format. But I cannot understand how to do that. I have tried several ways but all failed.

kjur commented 1 year ago

try this:

let keypair = KEYUTIL.generateKey("EC", "secp256k1");
let pubpem = KEYUTIL.getPEM(keypair.pubKeyObj, "PKCS8PUB");
let prvpem = KEYUTIL.getPEM(keypair.prvKeyObj, "PKCS8PRV");
hnamzian commented 1 year ago

try this:

let keypair = KEYUTIL.generateKey("EC", "secp256k1");
let pubpem = KEYUTIL.getPEM(keypair.pubKeyObj, "PKCS8PUB");
let prvpem = KEYUTIL.getPEM(keypair.prvKeyObj, "PKCS8PRV");

I know this one but in my case the public key is generated in a remote wallet and I have public key in hex format.

kjur commented 1 year ago

Can you show me your public key in hex? I may take a look further.

hnamzian commented 1 year ago

Can you show me your public key in hex? I may take a look further.

here is an example of ECDSA secp256k1 keys

public key: 04b4700a66cd814ae01f79593314e049af253b879fc82a444df87d58b8b0a691aaad3386e3bd436c99a9681fd9827284eea01a7f99f28aab94919350e51babedcf

private key: 9e6301a24a4f7bcf2be2dd767af99ef243aa057956eff826591bf44615fc5b79

kjur commented 1 year ago

For public key:

var pub = new rs.KJUR.crypto.ECDSA({name: "secp256k1"});
pub.setPublicKeyHex("04b4700a66cd814ae01f79593314e049af253b879fc82a444df87d58b8b0a691aaad3386e3bd436c99a9681fd9827284eea01a7f99f28aab94919350e51babedcf");
console.log(rs.KEYUTIL.getPEM(pub, "PKCS8PUB"));

For private key:

var prv = new rs.KJUR.crypto.ECDSA({name: "secp256k1"});
prv.setPrivateKeyHex("9e6301a24a4f7bcf2be2dd767af99ef243aa057956eff826591bf44615fc5b79");
console.log(rs.KEYUTIL.getPEM(prv, "PKCS8PRV"));

Note that setPublicKeyHex method only supports an uncompressed public key format (i.e. starting with "04...").

hnamzian commented 1 year ago

great thanks, that works, but what about compressed public key like 03dd1acaf93086ce535359c9133a8df2ea736fb7ca94c7007560ff5268dec0dbcc ?

kjur commented 1 year ago

compressed format is not supported yet. I'll wait for PR

hnamzian commented 1 year ago

great thanks for your help