Skip to content

Instantly share code, notes, and snippets.

@sydneyitguy
Last active August 10, 2018 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sydneyitguy/4f46d08e2e88aae8fd24ce5b7e41812c to your computer and use it in GitHub Desktop.
Save sydneyitguy/4f46d08e2e88aae8fd24ce5b7e41812c to your computer and use it in GitHub Desktop.
Generate a Ethereum key pair / Get public key from a given private key (if a parameter passed)
#!/usr/bin/env ruby
# gem install digest-sha3
require 'openssl'
require 'digest/sha3'
require 'open-uri'
require 'json'
def decode(s, base)
syms = '0123456789abcdef'.freeze
s = s.downcase if base == 16
result = 0
while s.size > 0
result *= base
result += syms.index(s[0])
s = s[1..-1]
end
result
end
def encode(v, base)
syms = 256.times.map {|i| i.chr }.join.freeze
result = ''
while v > 0
result = syms[v % base] + result
v /= base
end
result
end
def public_to_address(str)
str = str[2, 128]
Digest::SHA3.hexdigest(encode(decode(str, 16), 256), 256)[-40..-1]
end
private_key = ARGV[0]
if private_key
group = OpenSSL::PKey::EC::Group.new('secp256k1')
public_key = group.generator.mul(private_key.hex).to_bn.to_s(16)
else
curve = OpenSSL::PKey::EC.new('secp256k1')
curve.generate_key
private_key = curve.private_key.to_s(16)
public_key = curve.public_key.to_bn.to_s(16)
end
public_key = public_to_address(public_key)
puts "Private Key: #{private_key}"
puts "Address: 0x#{public_key}"
# Just in case 😉
url = "https://api.etherscan.io/api?module=account&action=balance&address=0x#{public_key}&tag=latest"
eth_balance = JSON.load(open(url))['result'].to_f / 10**18
puts "Balance: #{eth_balance} ETH"
@sydneyitguy
Copy link
Author

sydneyitguy commented Aug 8, 2018

Usage:

~$ ethKey
Private Key: E0D46700050E218B448C945B5E19C1E89A536068298E4938909537A35A38A939
Address: 0x5b268746ececf276e5502ec586172ae949ee96bb
Balance: 0.0 ETH

~$ ethKey E0D46700050E218B448C945B5E19C1E89A536068298E4938909537A35A38A939
Private Key: E0D46700050E218B448C945B5E19C1E89A536068298E4938909537A35A38A939
Address: 0x5b268746ececf276e5502ec586172ae949ee96bb
Balance: 0.0 ETH

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