Skip to content

Instantly share code, notes, and snippets.

@MatthieuLemoine
Created January 23, 2017 14:36
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthieuLemoine/ea7e5fa658d6a9ba69b6e098bb704dbc to your computer and use it in GitHub Desktop.
Save MatthieuLemoine/ea7e5fa658d6a9ba69b6e098bb704dbc to your computer and use it in GitHub Desktop.
Node crypto sign & verify
const id = '__JUNK__';
// Public key need to be in PKCS8 format
// ssh-keygen -e -m PKCS8 -f id_rsa.pub > id_rsa.pkcs8
const publicKey = fs.readFileSync(path.join(__dirname, 'id_rsa.pkcs8'), { encoding : 'utf8' });
const privateKey = fs.readFileSync(path.join(__dirname, 'id_rsa'), { encoding : 'utf8' });
// Sign
const signer = crypto.createSign('RSA-SHA512');
signer.update(id);
const signature = signer.sign(privateKey, 'hex');
// ...
// Verify
const verifier = crypto.createVerify('RSA-SHA512');
verifier.update(ruid);
const publicKeyBuf = new Buffer(publicKey, 'utf-8');
const signatureBuf = new Buffer(signature, 'hex');
const result = verifier.verify(publicKeyBuf, signatureBuf);
@anthonybudd
Copy link

Where does the variable ruid get defined on line 16?

@ndunks
Copy link

ndunks commented Jan 10, 2020

Where does the variable ruid get defined on line 16?

ruid should be id

@kutekrish
Copy link

kutekrish commented Jan 22, 2020

This is great, thanks !. You'd have to change new Buffer(variable, 'utf-8'); to Buffer.from(variable, 'utf-8');

Otherwise, you would get below warning

DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment