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
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).
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.
Encoding to/from Base64 is completely lossless. The quality loss happens probably when you save it. To prevent that, use an ImageWriter directly ( ImageIO.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With