为什么我得到的哈希不是我预期的哈希?

时间:2012-12-20 04:00:14

标签: ruby openssl sha1

当我从http://ruby.about.com/od/advancedruby/ss/Cryptographic-Hashes-In-Ruby.htm

输入此代码时
#!/usr/bin/env ruby
require 'digest'

password = "A user's password"
hash = Digest::SHA1.hexdigest(password)
puts hash

# This will produce the hash
# 62018390552aaba3d344e3b43bfa14e49e535dfc

我得到他们说的答案。

但是当我输入这个shell命令时

echo "A user's password" | openssl dgst -sha1 -hex

我得到95f33732bafc1744bf24e0cae4e014ab2e5f1580

为什么,拜托?

1 个答案:

答案 0 :(得分:11)

您的命令行示例包含一个换行符,该换行符未在Ruby字符串中指定。尝试使用-n,以便echo跳过换行符:

$ echo "A user's password" | openssl dgst -sha1 -hex
95f33732bafc1744bf24e0cae4e014ab2e5f1580
$ echo -n "A user's password" | openssl dgst -sha1 -hex
62018390552aaba3d344e3b43bfa14e49e535dfc