[英]Authenticating password encrypted in PHP using Blowfish with Ruby
有一個用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代碼是散列法$pass
與鹽$2a$07$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxx$
如果CRYPT_BLOWFISH
設定( CRYPT_BLOWFISH == 1
)。 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 ),我只使用了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示例相同的輸出。 如果您的鹽太長,請使用前29個字符($ 2a $ 07 $加上接下來的22個額外字符)。
我測試了PHP的行為,如果鹽太長(總共超過29個字符),其余部分將被忽略,如果鹽太短,它將返回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
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.