在Ruby中将十六进制摘要转换为base64

时间:2021-03-17 17:08:25

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?

我有一个文件的MD5十六进制摘要的字符串表示,我想转换为base64,以便在上传时使用Content-MD5 HTTP标头。是否有比以下更清晰或更有效的机制?

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

1 个解决方案

#1


20  

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)

对我来说似乎非常清晰和有效。您可以通过为'm'包格式指定0计数来保存对strip的调用(如果count为0,则不添加换行,请参阅RFC 4648)

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

#1


20  

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)

对我来说似乎非常清晰和有效。您可以通过为'm'包格式指定0计数来保存对strip的调用(如果count为0,则不添加换行,请参阅RFC 4648)

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