Skip to content

Instantly share code, notes, and snippets.

@tak1827
Last active October 9, 2022 19:35
Show Gist options
  • Save tak1827/1c1aa56eaf0f6f77896df29aa8a8b7dc to your computer and use it in GitHub Desktop.
Save tak1827/1c1aa56eaf0f6f77896df29aa8a8b7dc to your computer and use it in GitHub Desktop.
Can not use 'secp256k1' which is common on Crypto Currency to create JWT, Use 'secp256r1'
/* Common variables */
const JWT = require('jsonwebtoken');
// Payload
const payload = {
sub: 'Subject',
iss: 'Issuer',
exp: 1639248876
}
let privateKey, token;
/******************************
Wrong case using 'secp256k1'
*******************************/
const Elliptic = require('elliptic').ec;
const EC = new Elliptic('secp256k1');// Use 'secp256k1'
// Generate private key
privateKey = EC.genKeyPair().getPrivate().toString(16);
// Create token
token = JWT.sign(payload, privateKey, { algorithm: 'ES256'});
// Expected result is as follow.
/*
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Sign.sign (crypto.js:331:26)
at sign (/work/node_modules/jwa/index.js:76:45)
at Object.sign (/work/node_modules/jwa/index.js:96:27)
at Object.jwsSign [as sign] (/work/node_modules/jws/lib/sign-stream.js:32:24)
at Object.module.exports [as sign] (/work/node_modules/jsonwebtoken/sign.js:188:21)
at Object.<anonymous> (/work/jwt.js:24:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
*/
/******************************
Correct case using 'secp256r1'
*******************************/
const ECDSA = require('ecdsa-secp256r1');// Use 'secp256r1'
// Genarate private key
privateKey = ECDSA.generateKey();
// Retrive public key
const publicKey = privateKey.asPublic();
// Create token
token = JWT.sign(payload, privateKey.toPEM(), { algorithm: 'ES256'});
// Verify token
const decoded = JWT.verify(token, publicKey.toPEM());
console.log({
privateKey: privateKey.toPEM(),
publicKey: publicKey.toPEM(),
token,
decoded
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment