Skip to content

Instantly share code, notes, and snippets.

@defHLT
Created August 25, 2013 13:58
Show Gist options
  • Save defHLT/6333986 to your computer and use it in GitHub Desktop.
Save defHLT/6333986 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
# encoding: utf-8
# Created: 2013-04-19 17:51:52 +0300 by ice
# Generates beautiful bitcoin address
STDOUT.sync = true
%w{
openssl
benchmark
}.each { |r| require r}
exit if __FILE__ != $0
def sha256 str
OpenSSL::Digest::SHA256.hexdigest str
end
def rmd160 str
OpenSSL::Digest::RIPEMD160.hexdigest str
end
def pack str
[str].pack "H*"
end
def to_58 hex
# Bitcoin variant of Base58 encoding
code_string = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
x = hex.to_i(16)
output_string = ''
while x > 0
x, rem = x.divmod 58
output_string << code_string[rem]
end
# For every leading zero byte add '1'
if (l_zeros = hex[/^0+/])
(l_zeros.size/2).times { output_string << code_string[0] }
end
output_string.reverse
end
def to_WIF hex
# Converts private key from hex form to Wallet Import Format
# Prepend with 0x80
ekey = "80#{hex}"
# Double hash
dh = sha256(pack(sha256(pack(ekey))))
checksum = dh[0, 8] # First 4 bytes is the checksum
to_58(ekey << checksum)
end
def gen_key
data = []
# 0 - Private ECDSA Key
key = OpenSSL::PKey::EC.new("secp256k1")
key.generate_key
data << key.private_key
#1 - Public ECDSA Key
data << key.public_key.to_bn.to_s(16)
#2 - SHA-256 hash of 1
data << sha256(pack(data[1]))
#3 - RIPEMD-160 Hash of 2
data << rmd160(pack(data[2]))
#4 - Adding network bytes to 3
data << "00" + data[3]
#5 - SHA-256 hash of 4
data << sha256(pack(data[4]))
#6 - SHA-256 hash of 5
data << sha256(pack(data[5]))
#7 - First four bytes of 6
data << data[6][0, 8]
#8 - Adding 7 at the end of 4
data << data[4] + data[7]
#9 - Base58 encoding of 8
data << to_58(data[8])
data.values_at(0, 9)
end
if (arg = $*.first)
raise 'Unallowed symbols: [0OIl]' if arg[/[0OIl]/]
pattern = eval(arg)
else
puts "Usage: ruby ./gen-key.rb '/^1regex/i'"
exit
end
loop do
sec, addr = gen_key
if addr =~ pattern
puts addr
puts "importprivkey #{to_WIF(sec.to_s(16))}"
exit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment