Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a hexadecimal digest to base64 in Ruby

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
like image 719
steveh7 Avatar asked Apr 03 '12 04:04

steveh7


People also ask

Is BTOA same as Base64?

The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).

Is Base64 the same as hex?

The difference between Base64 and hex is really just how bytes are represented. Hex is another way of saying "Base16". Hex will take two characters for each byte - Base64 takes 4 characters for every 3 bytes, so it's more efficient than hex.

Does converting to Base64 reduce quality?

Encoding to/from Base64 is completely lossless. The quality loss happens probably when you save it. To prevent that, use an ImageWriter directly ( ImageIO.


1 Answers

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
like image 104
dbenhur Avatar answered Oct 23 '22 11:10

dbenhur