Encrypt a password the same way mysql does

Some one-liners:

MySQL (may require you add -u(user) -p):

mysql -NBe "select password('right')"

Python:

python -c 'from hashlib import sha1; print "*" + sha1(sha1("right").digest()).hexdigest().upper()'

Perl:

perl -MDigest::SHA1=sha1_hex -MDigest::SHA1=sha1 -le 'print "*". uc sha1_hex(sha1("right"))'

PHP:

php -r 'echo "*" . strtoupper(sha1(sha1("right", TRUE))). "\n";'

Ruby:

ruby -e 'require "digest/sha1"; puts "*" + Digest::SHA1.hexdigest(Digest::SHA1.digest("right")).upcase'

All output:

*920018161824B14A1067A69626595E68CB8284CB


Well, the trivial (perhaps cheating) way would be to run:

mysql -NBe "select password('right')"

This will produce a password using whatever password hashing scheme your version of mysql uses. [EDIT: added -NB, which gets rid of the column names and ascii table art.]


One more using the shell:

echo -n 'right' | sha1sum | xxd -r -p |\
sha1sum | tr '[a-z]' '[A-Z]' | awk '{printf "*%s", $1}'

Explanation:

  1. echo -n print without linebreak
  2. sha1sum first SHA1
  3. xxd -r -p unhex the hash
  4. sha1sum second SHA1
  5. tr '[a-z]' '[A-Z]' convert to uppercase
  6. awk '{print "*" $1}' add leading *

More details:

Between 2. and 3. an optional awk '{printf "%s", $1}' step could be insterted for newline- and hyphen-removal. But xxd will ignore them anyway (Thanks to dave_thompson_085).

Furthermore step 5 and 6 could be done at once by replacing them with {print "*" toupper($1)} (Thanks to dave_thompson_085).