Last active
August 10, 2018 05:30
-
-
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)
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
#!/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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: