在Ruby中将十六进制摘要转换为base64 [英] Converting a hexadecimal digest to base64 in Ruby

查看:278
本文介绍了在Ruby中将十六进制摘要转换为base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

对我来说似乎很清楚且有效.您可以通过将'm'包格式指定为0 count

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

这篇关于在Ruby中将十六进制摘要转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆