3

我有一个密码在 SHA1 中加密的数据库,我需要将它们转换为 SHA1 二进制形式并使用 base64 进行编码,我怎样才能得到它?

这就是我所拥有的:

# echo -n "password" | openssl sha1
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

这就是我需要的:

# echo -n "password" | openssl sha1 -binary | base64
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
4

3 回答 3

4
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="
于 2012-07-09T12:12:35.480 回答
2

Python 3 方法:

import sys, base64

def hex_to_b64(word):
    number = int(word, base=16)
    bytestr = number.to_bytes(20, 'big')
    b64 = base64.b64encode(bytestr).decode('ascii')
    return b64

if __name__ == '__main__':
    for word in sys.argv[1:]:
        print(hex_to_b64(word))

这使

localhost-2:coding $ python3 shaswitch.py 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
于 2012-07-09T12:19:42.240 回答
2

为什么要求助于python;OP想要bash:

% openssl sha1 -binary <(echo -n 'password') | base64
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
于 2016-04-21T20:35:27.577 回答