14

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
steveh7
  • 6,606
  • 2
  • 18
  • 12
  • 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. – maerics Apr 03 '12 at 04:54

1 Answers1

29

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
dbenhur
  • 20,008
  • 4
  • 48
  • 45
  • Thanks, looks like that may be the case. Just seems that wrapping each parameter in array is untidy. – steveh7 Apr 03 '12 at 08:27
  • 2
    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* ``` – Rahul Dess Oct 10 '19 at 18:05