Skip to content

Instantly share code, notes, and snippets.

@JakeLin
Created March 21, 2018 22:43
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 JakeLin/bb869a0290a9b120d019e0de67b364c7 to your computer and use it in GitHub Desktop.
Save JakeLin/bb869a0290a9b120d019e0de67b364c7 to your computer and use it in GitHub Desktop.
const EC = require('elliptic').ec
const BN = require('bn.js')
const ec = new EC('secp256k1')
const G = ec.g; // Generator point
const keccak256 = require('js-sha3').keccak256
// Refer to https://etherworld.co/2017/11/17/understanding-the-concept-of-private-key-public-key-and-address-in-ethereum-blockchain
/// Get public key from private key. `privateKey` is private key in buffer
const getPublickKeyFromPrivateKey = (privateKey) => {
if (!(privateKey instanceof Buffer)) {
throw new TypeError('param privateKey must be of Buffer type');
}
const pk = new BN(privateKey) // private key as big number
const publicPoint = G.mul(pk) // EC multiplication to determine public point
const x = publicPoint().toBuffer() //32 bit x co-ordinate of public point
const y = publicPoint().toBuffer() //32 bit y co-ordinate of public point
const publicKey = Buffer.concat([x,y])
return publicKey
}
/// Get address from public key. `publicKey` is public key in buffer
const getAddressFromPublicKey = (publicKey) => {
if (!(publicKey instanceof Buffer)) {
throw new TypeError('param privateKey must be of Buffer type');
}
const hash = keccak256(publicKey)
const address = Buffer.from(hash, 'hex').slice(-20)
return address
}
/// Get address from private key. `privateKey` is private key in buffer
const getAddressFromPrivateKey = (privateKey) => {
if (!(privateKey instanceof Buffer)) {
throw new TypeError('param privateKey must be of Buffer type');
}
const publicKey = getPublickKeyFromPrivateKey(privateKey)
const address = getAddressFromPublicKey(publicKey)
return address
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment