Skip to content

Instantly share code, notes, and snippets.

@miguelmota

miguelmota/keys

Last active Feb 25, 2021
Embed
What would you like to do?
Generate Ethereum Private key, Public key, and Address using Bash and OpenSSL
# Generate the private and public keys
openssl ecparam -name secp256k1 -genkey -noout | openssl ec -text -noout > key
# Extract the public key and remove the EC prefix 0x04
cat key | grep pub -A 5 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^04//' > pub
# Extract the private key and remove the leading zero byte
cat key | grep priv -A 3 | tail -n +2 | tr -d '\n[:space:]:' | sed 's/^00//' > priv
# Generate the hash and take the address part
cat pub | keccak-256sum -x -l | tr -d ' -' | tail -c 41 > address
# (Optional) import the private key to geth
geth account import priv
@ciscolxh

This comment has been minimized.

Copy link

@ciscolxh ciscolxh commented Mar 10, 2018

How to get keccak-256sum command in mac os?

@miguelmota

This comment has been minimized.

Copy link
Owner Author

@miguelmota miguelmota commented May 12, 2018

@ciscolxh https://github.com/maandree/sha3sum

on OSX, you can do brew install sha3sum to get the keccak-256sum command.

@Cheny-chen

This comment has been minimized.

Copy link

@Cheny-chen Cheny-chen commented Mar 7, 2019

How to convert from existing key to publicKey.pem. The pem format.

@KasraAhmadi

This comment has been minimized.

Copy link

@KasraAhmadi KasraAhmadi commented Jul 6, 2019

How to format public key to "secp256 compressed form - 66 characters" form?

@miguelmota

This comment has been minimized.

Copy link
Owner Author

@miguelmota miguelmota commented Jul 7, 2019

@Cheny-chen not sure how to do it with OpenSSL; here's an example using Node:

const KeyEncoder = require('key-encoder').default
const keyEncoder = new KeyEncoder('secp256k1')

const pubKey = Buffer.from('04997d9778d772bee04e01522c00d7d52371bd1a27cd87f6cf6f9c828d3a6d0d0da661b58f035aef01db4d7ad1c837ac28f3dec50f54bd351d090db6cb85069cc7', 'hex')

const pem = keyEncoder.encodePublic(pubKey.toString('hex'), 'raw' ,'pem').toString()
console.log(pem)
/*
-----BEGIN PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEmX2XeNdyvuBOAVIsANfVI3G9GifNh/bP
b5yCjTptDQ2mYbWPA1rvAdtNetHIN6wo897FD1S9NR0JDbbLhQacxw==
-----END PUBLIC KEY-----
*/

const raw = keyEncoder.encodePublic(pem, 'pem' ,'raw').toString('hex')
console.log(raw)
// 04997d9778d772bee04e01522c00d7d52371bd1a27cd87f6cf6f9c828d3a6d0d0da661b58f035aef01db4d7ad1c837ac28f3dec50f54bd351d090db6cb85069cc7
@avhacker

This comment has been minimized.

Copy link

@avhacker avhacker commented Nov 7, 2019

The letters in public address in this script is all lower cased. Can you make it right? (I know lower case key still works)

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