indutny / elliptic

Fast Elliptic Curve Cryptography in plain javascript
1.7k stars 376 forks source link

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

Open fturiot opened 4 years ago

fturiot commented 4 years ago

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

regards

AcidLeroy commented 4 years ago

@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.

dannydeut commented 4 years ago

I solved it by adding the options private

const pem = jwkToPem(jwk, { private: true });
davidkhala commented 2 years ago