0

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.

mlambie
  • 7,467
  • 6
  • 34
  • 41

2 Answers2

0

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/

gaqzi
  • 3,707
  • 3
  • 30
  • 30
  • That'll recover the plaintext and output it, the question is, I believe, requesting how to take the buffer containing the ciphertext and output it. – animal Apr 30 '09 at 19:28
  • That's right holychao. The string that is generated by blowfish.encrypt_string() contains control characters. I want to further convert this string to readable ASCII. – mlambie Apr 30 '09 at 19:42
  • I clearly missunderstood the purpose above, looking at the Crypt source it seems they are using N as a parameter to pack/unpack to get the correct values. But using N just creates a BigNum and then I can't convert that easily to hex. But using the code below I can send the encrypted string across different instances.
    
    tmp = env.unpack('N*')
    p blowfish.decrypt_string(tmp.pack('N*'))
    Not sure if this is any helpful at all, but good luck! :)
    – gaqzi Apr 30 '09 at 19:49
0

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=
tadman
  • 208,517
  • 23
  • 234
  • 262