encoding and decoding in Ruby using Base64 Module

By: Emiley J. Emailed: 1786 times Printed: 2608 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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

Ruby Home | All Ruby Tutorials | Latest Ruby Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J.
Error generating R.java from manifest
ERROR 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client
IIS and Tomcat - how to configure to work together
PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......
Adding your own Application icon for your J2ME application (jar file)
Creating Menus in Code using VB.net
Traversing all files in a directory using Ruby
Using Proxy to connect to URLs in Ruby
POST a form in Ruby
Reading URL content using Ruby (HTTP)
dRuby client/server mode sample program
Benchmark module in Ruby
encoding and decoding in Ruby using Base64 Module
Module Abbrev in Ruby
Standard Library Packages in Ruby

More Tutorials in Ruby
Standard Library Packages in Ruby
Module Abbrev in Ruby
encoding and decoding in Ruby using Base64 Module
Benchmark module in Ruby
benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) {|report| ...} in Ruby
bm(label_width = 0, *labels) {|report| ...} in Ruby
bmbm(width = 0) {|job| ...} in Ruby
CGI class in Ruby
URL encode a string in Ruby
escapeElement() in Ruby
escapeHTML() in Ruby
new(type = "query") in Ruby
parse(query) in Ruby
pretty() in Ruby
Format a Time object as a String in Ruby

More Latest News
Most Viewed Articles (in Ruby )
encoding and decoding in Ruby using Base64 Module
URL decode a string in Ruby
URL encode a string in Ruby
Open and manipulate CSV files in Ruby
Using Proxy to connect to URLs in Ruby
if . . . elsif . . . else in Ruby on rails
Reading URL content using Ruby (HTTP)
Reading emails using POP3 in Ruby
escapeHTML() in Ruby
POST a form in Ruby
Action Pack - Ruby On rails from request to response
Sending emails and Receiving emails using Ruby On rails
Benchmark module in Ruby
Standard Library Packages in Ruby
header() in Ruby
Most Emailed Articles (in Ruby)
Methods in Ruby on rails
The Question Mark Operator in Ruby on rails
Defining tables and classes (using MySQL) in Ruby on Rails
if . . . elsif . . . else in Ruby on rails
Naming conventions in Ruby on rails
unless in Ruby on rails
URL encode a string in Ruby
parse(query) in Ruby
unescapeHTML() in Ruby
Reading emails using POP3 in Ruby
Using Observer in Ruby
Action Pack - Ruby On rails from request to response
Getting started with Ruby on rails
Prompts, Command Lines, Prompts, and irb in Ruby on rails
encoding and decoding in Ruby using Base64 Module