This is related to my question from yesterday (which got great results): Encrypting a string with Blowfish in ruby returns a shorter string than the same process in php
Now I have what I believe to be a similar problem in the opposite direction. I use php to encrypt a string:
php > require_once 'Crypt/Blowfish.php';
php > $input = "input string";
php > $key = "some key";
php > $crypt = new Crypt_Blowfish($key);
php > echo bin2hex($crypt->encrypt($input));
79af8c8ee9220bdec2d1c9cfca7b13c6
And this is exactly the expected result. However, when I attempt to decrypt the string in ruby, it only gives me a subset of the input:
irb(main):001:0> require 'rubygems'
r=> true
irb(main):002:0> require 'crypt/blowfish'
=> true
irb(main):003:0> key = "some key"
=> "some key"
irb(main):004:0> input = "79af8c8ee9220bdec2d1c9cfca7b13c6"
=> "79af8c8ee9220bdec2d1c9cfca7b13c6"
irb(main):005:0> block = input.gsub(/../) { |match| match.hex.chr }
=>开发者_如何学Go; "y\257\214\216\351\"\v\336\302\321\311\317\312{\023\306"
irb(main):006:0> blowfish = Crypt::Blowfish.new(key)
=> #<Crypt::Blowfish:0xb73acbd8 @sBoxes=[[3156471959, 1769696695, 1443271708, 181204541,
... 1894848609], @key="some key">
irb(main):008:0> blowfish.decrypt_block(block)
=> "input st"
Any idea what foolish thing I'm doing now?
A blowfish block is 8-bytes long. Note that's exactly the number of characters you're getting back when you ask to decrypt one block.
There must be more code to get the final block, or you need to call decrypt_block again on the next 8-bytes.
Instead of calling decrypt_block you might want to try decrypt_string.
From the tests:
userkey = "A BIG KEY"
bf = Crypt::Blowfish.new(userkey)
string = "This is a string which is not a multiple of 8 characters long"
encryptedString = bf.encrypt_string(string)
decryptedString = bf.decrypt_string(encryptedString)
assert_equal(string, decryptedString)
精彩评论