使用Ruby生成openssl密码

时间:2013-12-09 21:07:43

标签: ruby openssl

我想使用ruby openssl库生成与此openssl命令相同的内容:

$ openssl passwd -1 mypassword

现在,在我的代码中,我正在这样做:

mypass = `openssl passwd -1 mypassword`

......这很有效,但看起来很傻。我觉得你应该能够使用OpenSSL :: Digest来实现相同的结果。但是,我似乎无法让它发挥作用。

3 个答案:

答案 0 :(得分:3)

openssl passwd -1实施UNIX crypt(3) algorithm。实现(md5crypt)驻留在apps/passwd.c中。因此,实现代码不是OpenSSL库函数。正如功能评论所说:

  

基于MD5的密码算法(应该可以作为一个   图书馆功能;那么静态缓冲区是不可接受的。)

所以你不会在OpenSSL :: Digest中找到它。

但是,您可能会发现其他库有用,例如unix-crypt

答案 1 :(得分:0)

require 'openssl'
OpenSSL::Digest::MD5.hexdigest(mypassword)

答案 2 :(得分:0)

这与shared resource

兼容
openssl passwd -1

使用字符串调用require 'openssl' module CryptMD5 refine String do def crypt_md5 salt = OpenSSL::Random.random_bytes(6) crypt ['$1$', salt].pack('a3m0').tr(?+, ?.).delete(?=) end end end using CryptMD5 pass = '$1$i7VbAY.b$uy5kgtLn8m2daMxOBEz6p.' salt = pass[3..10].tr(?., ?+).unpack1 'm0' puts pass == 'secret'.crypt_md5(salt) # => true puts pass == 'secret'.crypt_md5(salt + 'ignored extra') # => true puts 'secret'.crypt_md5 # => $1$bMylNdtr$/fxt7r7gzdossTabWD/xT/ puts 'secret'.crypt_md5 # => $1$y6O7OsY7$bDl3yEKJXM0lhg3DYye6Z1 pass = `openssl passwd -1 secret`.chomp salt = pass[3..10].tr(?., ?+).unpack1 'm0' puts pass == 'secret'.crypt_md5(salt) # => true 通常仅将前两个字符用作盐,但是如果以String#crypt作为前缀,它将使用后6个字节/ 8个字符作为盐,并带有修改的base64字母(交换$1$+)。任何其他字节/字符都将被截断。