Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created November 21, 2013 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ashmoran/7582071 to your computer and use it in GitHub Desktop.
Save ashmoran/7582071 to your computer and use it in GitHub Desktop.
Demo of generating a Bitcoin address in Ruby (not production quality code!)
require 'bitcoin'
def hex_string_to_bytes(string)
[string].pack("H*")
end
def bytes_to_hex_string(bytes)
bytes.unpack("H*").first
end
# https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses
private_key_hex_string = "18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725"
key = Bitcoin::Key.new(private_key_hex_string)
pub_key_bytes = hex_string_to_bytes(key.pub_uncompressed)
hash_step_1 = Digest::SHA256.digest(pub_key_bytes)
hash160 = Digest::RMD160.digest(hash_step_1)
hash160_hex_string = bytes_to_hex_string(hash160)
versioned_hash160_hex_string = "00" + hash160_hex_string
versioned_hash160 = hex_string_to_bytes(versioned_hash160_hex_string)
checksum_hash_round_1 = Digest::SHA256.digest(versioned_hash160)
checksum_hash_round_2 = Digest::SHA256.digest(checksum_hash_round_1)
checksum = checksum_hash_round_2[0,4]
binary_address = versioned_hash160 + checksum
binary_address_hex_string = bytes_to_hex_string(binary_address)
human_address = Bitcoin.encode_base58(binary_address_hex_string)
p human_address
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment