How can I convert a Blowfish encoded binary string to ASCII in Ruby?

徘徊边缘 提交于 2019-12-25 04:32:18

问题


I would like to encode some plain text using Ruby and the Crypt library. I would like to then transmit this encrypted text (along with some other data) as an ASCII hexadecimal string within an XML file.

I have the following code snippet:

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

Which outputs:

This is the plain text
????;

I believe I need to call enc.unpack() but I'm not sure what parameters are required to the unpack method call.


回答1:


When you say "ASCII hexadecimal" do you mean that it merely needs to be readable ASCII or does it need to be strictly hexadecimal?

Here's two approaches to encoding binary data:

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=



回答2:


If you use decrypt_string and its counterpart encrypt_string it outputs it pretty easily. :)


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)

Also found this blogpost that talks about speed concerns using the Crypt library, added just for reference. :)
http://basic70tech.wordpress.com/2007/03/09/blowfish-decryption-in-ruby/



来源:https://stackoverflow.com/questions/808536/how-can-i-convert-a-blowfish-encoded-binary-string-to-ascii-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!