require 'digest/sha1'
require 'base64'
Base64.encode64(Digest::SHA1.digest('password'))
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g=\n"
这会添加一个换行符,因此您可能需要使用
Base64.encode64(Digest::SHA1.digest('password')).chop
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
甚至更简单,如@FrederickCheung
建议的那样:
Digest::SHA1.base64digest('password')
编辑
当您只有 SHA-1 编码密码的十六进制字符串时,请执行
require 'base64'
pass = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
Base64.encode64([pass].pack('H*')).chop
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="
或者您甚至可以绕过base64
库并完全依赖pack
:
[[pass].pack('H*')].pack('m0')
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="