2009-04-30 105 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

相关问题