Skip to content

Instantly share code, notes, and snippets.

@xhliu
Forked from msinkec/unknownPrivkeySig.ts
Last active February 13, 2024 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xhliu/1e1bdfec41e6b03c243e33359d922e5e to your computer and use it in GitHub Desktop.
Save xhliu/1e1bdfec41e6b03c243e33359d922e5e to your computer and use it in GitHub Desktop.
Create Sig and PubKey with unknown PrivKey
import { bsv } from 'scrypt-ts'
async function main() {
const msg = 'I am Satoshi'
const hBuff = bsv.crypto.Hash.sha256(Buffer.from(msg))
const h = bsv.crypto.BN.fromBuffer(hBuff)
const G = bsv.crypto.Point.getG()
const n = bsv.crypto.Point.getN()
const s = bsv.PrivateKey.fromRandom().bn
let r: bsv.crypto.BN = new bsv.crypto.BN(0)
let R: bsv.crypto.Point = G
let isValidR = false
// find a `r` on the curve
while (!isValidR) {
r = bsv.PrivateKey.fromRandom().bn
try {
R = bsv.crypto.Point.fromX(false, r)
isValidR = true
} catch (e) {
isValidR = false
}
}
const sR = R.mul(s)
const hG = G.mul(h)
const sR_hG = sR.add(hG.neg())
const inv_r = r.invm(n)
const Y = sR_hG.mul(inv_r)
const pubKey = new bsv.PublicKey(Y)
const sig = new bsv.crypto.Signature(r, s)
const valid = bsv.crypto.ECDSA.verify(
hBuff,
sig,
pubKey
)
console.log(`Message: ${msg}`)
console.log(`Public key: ${pubKey.toString()}`)
console.log(`Signature: ${sig.toString()}`)
console.log(`Verified: \x1b[32m${valid}\x1b[0m`)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment