elliptic icon indicating copy to clipboard operation
elliptic copied to clipboard

how save and load private / publick key in pem or other format

Open fturiot opened this issue 5 years ago • 3 comments

not found solution for save key (private and public key) in pem or other format wy not key.save or key.load ?

regards

fturiot avatar Jan 27 '20 12:01 fturiot

@fturiot I've been trying to figure this out as well. I have the following code, but when I try to sign with jsonwebtoken it fails. Here is the code where I am attempting this in Typescript:

    import { ec as EllipticCurve, ec } from 'elliptic';
    const ecurve = new EllipticCurve('secp256k1');
    import * as jwt from 'jsonwebtoken'; 
    var jwkToPem = require('jwk-to-pem'); 

    const keyPair = ecurve.genKeyPair();
    const priv = keyPair.getPrivate(); 
    const pub = keyPair.getPublic(); 
    const x = pub.getX(); 
    const y = pub.getY(); 
    let jwk = {
        "kty": "EC", 
        "crv": "P-256", 
        "x": x.toBuffer().toString('base64'), 
        "y": y.toBuffer().toString('base64'), 
        "d": priv.toBuffer().toString('base64')
    }

    // I fail at this step: 
    // error: "Error: Invalid key for curve: "Public key is not a point""
      let pem = jwkToPem(jwk); 

    // I want to sign with JWT
    const token = jwt.sign({ foo: 'bar' }, pem, { algorithm: 'ES256'});

I would love to hear what other folks are doing to generate a PEM.

AcidLeroy avatar Jan 31 '20 14:01 AcidLeroy

I solved it by adding the options private

const pem = jwkToPem(jwk, { private: true });

dannydeut avatar Apr 07 '20 11:04 dannydeut

  • 1 we need at least a key load from PEM.

davidkhala avatar Aug 07 '22 04:08 davidkhala