Programming Tutorials

encoding and decoding in Ruby using Base64 Module

By: Emiley J. in Ruby Tutorials on 2009-03-03  

The Base64 module provides for the encoding (encode64) and decoding (decode64) of binary data using a Base64 representation.

The following particular features are also provided:

  • encode into lines of a given length (b64encode)
  • decode the special format specified in RFC2047 for the representation of email headers (decode_b)

Example

A simple encoding and decoding.

    require "base64"

    enc   = Base64.encode64('Send reinforcements')
                        # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
    plain = Base64.decode64(enc)
                        # -> "Send reinforcements"

The purpose of using base64 to encode data is that it translates any binary data into purely printable characters. It is specified in RFC 2045 (www.faqs.org/rfcs/rfc2045.html).

b64encode(bin, len = 60)

Prints the Base64 encoded version of bin (a String) in lines of len (default 60) characters.

   require 'base64'
   data = "Now is the time for all good coders\nto learn Ruby"
   puts Base64.b64encode(data)

Generates:

   Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
   UnVieQ==
# File base64.rb, line 112
  def b64encode(bin, len = 60)
    encode64(bin).scan(/.{1,#{len}}/o) do
      print $&, "\n"
    end
  end
decode64(str)

Returns the Base64-decoded version of str.

  require 'base64'
  str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
        'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
        'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
  puts Base64.decode64(str)

Generates:

   This is line one
   This is line two
   This is line three
   And so on...
# File base64.rb, line 58
  def decode64(str)
    str.unpack("m")[0]
  end
decode_b(str)

Decodes text formatted using a subset of RFC2047 (the one used for mime-encoding mail headers).

Only supports an encoding type of 'b" (base 64), and only supports the character sets ISO-2022-JP and SHIFT_JIS (so the only two encoded word sequences recognized are =?ISO-2022-JP?B?-= and =?SHIFT_JIS?B?-=). Recognition of these sequences is case insensitive.

# File base64.rb, line 72
  def decode_b(str)
    str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
      decode64($1)
    }
    str = Kconv::toeuc(str)
    str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) {
      decode64($1)
    }
    str = Kconv::toeuc(str)
    str.gsub!(/\n/, ' ') 
    str.gsub!(/\0/, '')
    str
  end
encode64(bin)

Returns the Base64-encoded version of str.

   require 'base64'
   Base64.b64encode("Now is the time for all good coders\nto learn Ruby")

Generates:

   Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
   UnVieQ==
# File base64.rb, line 96
  def encode64(bin)
    [bin].pack("m")
  end





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)