Created
July 30, 2018 09:28
-
-
Save Leask/8372f566668283b054d109ecc869a171 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { randomBytes } = require('crypto') | |
const secp256k1 = require('secp256k1') | |
const createKeccakHash = require('keccak') | |
const signToPubAddress = (msghash, sig) => { | |
// TODO: verify msghash and sig | |
const v = Number(sig.slice(128)); | |
const sigObj = {r: sig.slice(0, 64), s: sig.slice(64, 128)}; | |
const point = secp256k1.recoverPubKey(msghash, sigObj, v); | |
const pub = point.encode('hex'); | |
// TODO: verify pubkey | |
const pubkey = pub.slice(2); | |
const addresshash = keccak256(hex2ab(pubkey)); | |
return addresshash.slice(-40); | |
} | |
let privKey | |
do { | |
privKey = randomBytes(32) | |
} while (!secp256k1.privateKeyVerify(privKey)) | |
let pubKey = secp256k1.publicKeyCreate(privKey) | |
const privatekeyhex = privKey.toString('hex'); | |
const publickeyhex = pubKey.toString('hex'); | |
if(pubKey.length!=64) | |
pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1) | |
let publickey_keccak256 = createKeccakHash('keccak256').update(pubKey).digest(); | |
let address = publickey_keccak256.slice(-20).toString('hex'); | |
console.log("privateKey: "+ privatekeyhex) | |
console.log("publicKey: " + publickeyhex); | |
console.log("address: " +address); | |
let msg = "my test message"; | |
let msghash = createKeccakHash('keccak256').update(new Buffer(msg, 'utf8')).digest(); | |
//============ recovery public and address from the signature | |
const EC = require('elliptic').ec; | |
const ec = new EC('secp256k1'); | |
const ethUtil= require('ethereumjs-util'); | |
var key = ec.keyFromPrivate(privatekeyhex, 'hex'); | |
var signature = key.sign(msghash); | |
let combinedHex =signature.r.toString(16)+ signature.s.toString(16) + signature.recoveryParam.toString(); | |
let sig = combinedHex; | |
var v = Number(sig.slice(128)); | |
console.log("sig:" + combinedHex); | |
var sigbuff = new Buffer(sig.slice(0,128), "hex"); | |
var senderPubKey = secp256k1.recover(new Buffer(msghash, "hex"), sigbuff, v); | |
var publickey = secp256k1.publicKeyConvert(senderPubKey, false).slice(1); | |
var pubaddress = ethUtil.pubToAddress(publickey).toString('hex'); | |
console.log("address from sign: "+pubaddress); | |
console.log("v= "+v); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment