Converting a hexadecimal digest to base64 in Ruby
Asked Answered
D

1

16

I have a string representation of a MD5 hex digest for a file, that I want to convert to base64 in order to use the Content-MD5 HTTP header when uploading it. Is there a clearer or more efficient mechanism to do than the following?

def hex_to_base64_digest(hexdigest)
  [[hexdigest].pack("H*")].pack("m").strip
end

hex_digest = "65a8e27d8879283831b664bd8b7f0ad4"
expected_base64_digest = "ZajifYh5KDgxtmS9i38K1A=="

raise "Does not match" unless hex_to_base64_digest(hex_digest) === expected_base64_digest
Dampproof answered 3/4, 2012 at 4:7 Comment(1)
Looks pretty clear and efficient to me. The only thing that might be faster/clearer is a native hook that does exactly the "hex_to_base64_digest" method.Shoshonean
O
31

Seems pretty clear and efficient to me. You can save the call to strip by specifying 0 count for the 'm' pack format (if count is 0, no line feed are added, see RFC 4648)

def hex_to_base64_digest(hexdigest)
  [[hexdigest].pack("H*")].pack("m0")
end
Orlon answered 3/4, 2012 at 5:13 Comment(2)
Thanks, looks like that may be the case. Just seems that wrapping each parameter in array is untidy.Dampproof
If anyone looking from Base64 to Hex below is the method i used. ``` def base64_to_hex(base64_string) base64_string.scan(/.{4}/).map do |b| b.unpack('m0').first.unpack('H') end.join end* ```Sesquialtera

© 2022 - 2024 — McMap. All rights reserved.