Skip to content

Instantly share code, notes, and snippets.

@gregsantos
Created September 30, 2022 19:39
Show Gist options
  • Save gregsantos/e87b40a4eb6c8aac1aa858791f0763d5 to your computer and use it in GitHub Desktop.
Save gregsantos/e87b40a4eb6c8aac1aa858791f0763d5 to your computer and use it in GitHub Desktop.
const {randomBytes} = require("crypto")
const secp256k1 = require("secp256k1")
// or require('secp256k1/elliptic')
// if you want to use pure js implementation in node
// generate message to sign
// message should have 32-byte length, if you have some other length you can hash message
// for example `msg = sha256(rawMessage)`
const msg = randomBytes(32)
// generate privKey
let privKey
do {
privKey = randomBytes(32)
} while (!secp256k1.privateKeyVerify(privKey))
// get the public key in a compressed format
const pubKey = secp256k1.publicKeyCreate(privKey)
function toHex(buffer) {
return Array.from(buffer)
.map(byte => byte.toString(16).padStart(2, "0"))
.join("")
}
console.log("pub key", toHex(pubKey), pubKey.toString("hex"))
// sign the message
const sigObj = secp256k1.ecdsaSign(msg, privKey)
// verify the signature
console.log(secp256k1.ecdsaVerify(sigObj.signature, msg, pubKey))
// => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment