2 # = base64.rb: methods for base64-encoding and -decoding stings
4 # Author:: Yukihiro Matsumoto
5 # Documentation:: Dave Thomas and Gavin Sinclair
7 # Until Ruby 1.8.1, these methods were defined at the top-level. Now
8 # they are in the Base64 module but included in the top-level, where
9 # their usage is deprecated.
11 # See Base64 for documentation.
17 # The Base64 module provides for the encoding (#encode64) and decoding
18 # (#decode64) of binary data using a Base64 representation.
20 # The following particular features are also provided:
21 # - encode into lines of a given length (#b64encode)
22 # - decode the special format specified in RFC2047 for the
23 # representation of email headers (decode_b)
27 # A simple encoding and decoding.
31 # enc = Base64.encode64('Send reinforcements')
32 # # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
33 # plain = Base64.decode64(enc)
34 # # -> "Send reinforcements"
36 # The purpose of using base64 to encode data is that it translates any
37 # binary data into purely printable characters. It is specified in
38 # RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html).
43 # Returns the Base64-decoded version of +str+.
46 # str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
47 # 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
48 # 'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
49 # puts Base64.decode64(str)
63 # Decodes text formatted using a subset of RFC2047 (the one used for
64 # mime-encoding mail headers).
66 # Only supports an encoding type of 'b' (base 64), and only supports
67 # the character sets ISO-2022-JP and SHIFT_JIS (so the only two
68 # encoded word sequences recognized are <tt>=?ISO-2022-JP?B?...=</tt> and
69 # <tt>=?SHIFT_JIS?B?...=</tt>). Recognition of these sequences is case
73 str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
76 #str = Kconv::toeuc(str)
77 str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) {
80 #str = Kconv::toeuc(str)
86 # Returns the Base64-encoded version of +str+.
89 # Base64.b64encode("Now is the time for all good coders\nto learn Ruby")
93 # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
100 # _Prints_ the Base64 encoded version of +bin+ (a +String+) in lines of
101 # +len+ (default 60) characters.
104 # data = "Now is the time for all good coders\nto learn Ruby"
105 # Base64.b64encode(data)
109 # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
112 def b64encode(bin, len = 60)
113 encode64(bin).scan(/.{1,#{len}}/) do