Domanda

I have a database with passwords encrypted in SHA1, I need to convert them to the SHA1 binary form and encode with base64, how can I get that?

This is what I have:

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

This is what I need:

# echo -n "password" | openssl sha1 -binary | base64
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
È stato utile?

Soluzione

require 'digest/sha1'
require 'base64'

Base64.encode64(Digest::SHA1.digest('password'))
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g=\n"

this adds a newline though so you may need to use

Base64.encode64(Digest::SHA1.digest('password')).chop
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="

or even simpler, as @FrederickCheung suggested:

Digest::SHA1.base64digest('password')

Edit

when you only have the hex string of the SHA-1 encoded password, then do

require 'base64'

pass = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
Base64.encode64([pass].pack('H*')).chop
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="

or you can even bypass the base64 library and solely rely on pack:

[[pass].pack('H*')].pack('m0')
# => "W6ph5Mm5Pz8GgiULbPgzG37mj9g="

Altri suggerimenti

Python 3 approach:

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))

which gives

localhost-2:coding $ python3 shaswitch.py 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
W6ph5Mm5Pz8GgiULbPgzG37mj9g=

Why resort to python; OP wanted bash:

% openssl sha1 -binary <(echo -n 'password') | base64
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top