2009-04-30 104 views
0

我想使用Ruby和Crypt library編碼一些純文本。然後我想將這個加密的文本(連同其他一些數據)作爲一個ASCII十六進制字符串傳送到一個XML文件中。如何在Ruby中將Blowfish編碼的二進制字符串轉換爲ASCII?

我有下面的代碼片段:

require 'rubygems' 
require 'crypt/blowfish' 

plain = "This is the plain text" 
puts plain 

blowfish = Crypt::Blowfish.new("A key up to 56 bytes long") 
enc = blowfish.encrypt_block(plain) 
puts enc 

,輸出:

This is the plain text 
????;

我相信我需要調用enc.unpack(),但我不知道需要解包方法調用的參數是什麼。

回答

0

當您說「ASCII十六進制」是否意味着它只需要可讀的ASCII或它需要嚴格十六進制?

這裏有兩種方法來編碼的二進制數據:

require 'rubygems' 
require 'crypt/blowfish' 

plain = "This is the plain text" 
puts plain 

blowfish = Crypt::Blowfish.new("A key up to 56 bytes long") 
enc = blowfish.encrypt_string(plain) 

hexed = '' 
enc.each_byte { |c| hexed << '%02x' % c } 

puts hexed 
# => 9162f6c33729edd44f5d034fb933ec38e774460ccbcf4d451abf4a8ead32b32a 

require 'base64' 

mimed = Base64.encode64(enc) 

puts mimed 
# => kWL2wzcp7dRPXQNPuTPsOOd0RgzLz01FGr9Kjq0ysyo= 
0

如果您使用decrypt_string及其對應encrypt_string它會很容易輸出。 :)


require 'rubygems' 
require 'crypt/blowfish' 

plain = "This is the plain text" 
puts plain 

blowfish = Crypt::Blowfish.new("A key up to 56 bytes long") 
enc = blowfish.encrypt_string(plain) 
p blowfish.decrypt_string(enc) 

也發現這篇博文討論使用Crypt庫的速度問題,僅供參考。 :)
http://basic70tech.wordpress.com/2007/03/09/blowfish-decryption-in-ruby/

+0

那將恢復明文和輸出過,問題是,我相信,請求如何服用含有密文和輸出它的緩衝區。 – animal 2009-04-30 19:28:13

相關問題