Decoding a string of hexadecimal characters into a binary fragment is currently not part of the standard crystal library, so I wrote the decoding function myself:
def hex_decode(hex)
return unless hex.size % 2 == 0
slice = Slice(UInt8).new(hex.size / 2)
0.step(to: hex.size - 1, by: 2) do |i|
high_nibble = hex.to_unsafe[i].unsafe_chr.to_u8?(16)
low_nibble = hex.to_unsafe[i + 1].unsafe_chr.to_u8?(16)
return unless high_nibble && low_nibble
slice[i / 2] = (high_nibble << 4) | low_nibble
end
slice
end
String, , Slice(UInt8) ( nil, ).
, , :
def hash256(hex_string)
data = hex_decode(hex_string)
raise "Invalid hexadecimal" unless data
hash = OpenSSL::Digest.new("SHA256")
hash.update(data)
hash1 = hash.digest
hash = OpenSSL::Digest.new("SHA256")
hash.update(hash1)
hash.hexdigest
end
, SHA256 . - :
def hash256(hex_string)
data = hex_decode(hex_string)
raise "Invalid hexadecimal" unless data
hash = OpenSSL::Digest.new("SHA256")
hash.update(data)
hash.hexdigest
end