Morning Musings

I'm not ready to wake up yet...

Bitcoin Address to Hash

| Comments

In the previous post, I walked through how to store a hash in the Bitcoin blockchain, by converting the hash to a valid Bitcoin address and sending a small amount of bitcoin to it. I neglected to include a script that goes the other way, so here it is.

Below is a script that will take a valid Bitcoin address and convert it back to the hash it came from. This can be used to validate Blockchain Identities.

(address-to-hash.rb) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env ruby

# address-to-hash.rb
# Copyright (C) 2015 Joe Ruether jrruethe@gmail.com
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# Get the address
address = ARGV[0]

def decode_base58(base58_val)
   alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
   int_val, base = 0, alpha.size
   base58_val.reverse.each_char.with_index do |char,index|
      raise ArgumentError, 'Value not a valid Base58 String.' unless char_index = alpha.index(char)
      int_val += char_index*(base**index)
   end
   s = int_val.to_s(16)
   s = (s.bytesize.odd? ? '0'+s : s)
   s = '' if s == '00'
   leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size
   s = ("00"*leading_zero_bytes) + s  if leading_zero_bytes > 0
   s
end

# Get the hex payload
payload = decode_base58(address)

# Print out the first 20 bytes of the sha256 hash
puts payload[2..41]

Grab the sending address from the transaction:

1BESV3iP1x1HAMDGhsYiQE3do6aiywGZ3K

Run the script using this address:

./address-to-hash.rb 1BESV3iP1x1HAMDGhsYiQE3do6aiywGZ3K 
703bf01d7df0a110c9b2ce1e8984f545831bffaa

As you can see, the resulting hash matches the sha256 hash of key.json.asc generated in the previous post.

Comments