【问题标题】:Authenticating password encrypted in PHP using Blowfish with Ruby使用 Blowfish 和 Ruby 验证 PHP 中加密的密码
【发布时间】:2012-01-22 03:27:02
【问题描述】:

有一个用 PHP 编写的应用程序,我正在将其转换为 Ruby。加密密码时,PHP 应用程序使用以下代码:

if($method == 2 && CRYPT_BLOWFISH) return crypt($pass, '$2a$07$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxx$');

我假设这是使用 Blowfish 实现。这里的 x 都是 a-zA-Z0-9 字符。

Ruby 中的 Blowfish 实现使用以下语法(取自 http://crypt.rubyforge.org/blowfish.html):

blowfish = Crypt::Blowfish.new("A key up to 56 bytes long")
plainBlock = "ABCD1234"
encryptedBlock = blowfish.encrypt_block(plainBlock)

我没有 56 字节或更少字节长的字符串,不清楚 PHP 版本应该是什么。那么如何编写一个 Ruby 函数来加密密码以提供与 PHP 相同的结果呢?

【问题讨论】:

    标签: php ruby authentication encryption blowfish


    【解决方案1】:

    如果设置了CRYPT_BLOWFISH (CRYPT_BLOWFISH == 1),PHP 代码将使用盐$2a$07$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxx$ 散列$pass。 salt 必须遵循 PHP 文档 ("$2a$", a two digit cost parameter, "$", and 22 digits from the alphabet "./0-9A-Za-z") 中指示的格式。

    我不确定您是否可以使用您所引用的库来执行此操作,但您可以改用 bcrypt-ruby

    对于您的代码,它将是这样的,我使用 PHP 示例中的相同数据 (http://php.net/manual/en/function.crypt.php),我只取 salt 的前 29 个字符,因为除此之外 PHP 会忽略它:

    require 'bcrypt-ruby'
    pass = "rasmuslerdorf" # Here you should put the $pass from your PHP code
    salt = '$2a$07$usesomesillystringfors' # Notice no $ at the end. Here goes your salt
    hashed_password = BCrypt::Engine.hash_secret(pass,salt) # => "$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi"
    

    这为您提供与 PHP 示例相同的输出。如果你的 salt 太长,取前 29 个字符($2a$07$ 加上接下来的 22 个额外字符)。

    我测试了 PHP 的行为,如果 salt 太长(总共超过 29 个字符)则忽略其余部分,如果 salt 太短则返回 0。例如在 PHP 中:

    <?php
      crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') 
      // returns $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
    
      crypt('rasmuslerdorf', '$2a$07$usesomesillystringfors')
      // returns $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
    
      crypt('rasmuslerdorf', '$2a$07$usesomesilly')
      // returns 0 because the salt is not long enough
    ?>
    

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2016-07-25
      • 2014-08-09
      • 2017-12-26
      相关资源
      最近更新 更多