module Base64

Overview

TheBase64 module provides for the encoding (#encode,#strict_encode, #urlsafe_encode) and decoding (#decode) of binary data using a base64 representation.

Example

A simple encoding and decoding.

require "base64"

enc = Base64.encode("Send reinforcements") # => "U2VuZCByZWluZm9yY2VtZW50cw==\n"
plain = Base64.decode_string(enc)          # => "Send reinforcements"

The purpose of using base64 to encode data is that it translates any binary data into purely printable characters.

Extended Modules

Defined in:

base64.cr

Instance Method Summary

Instance Method Detail

def decode(data, io : IO) #

Writes the base64-decoded version ofdata toio. Thiswill decode either the normal or urlsafe alphabets.


def decode(data) : Bytes #

Returns the base64-decoded version ofdata as aBytes. Thiswill decode either the normal or urlsafe alphabets.


def decode_string(data) : String #

Returns the base64-decoded version ofdata as a string. Thiswill decode either the normal or urlsafe alphabets.


def encode(data, io : IO) #

Writes the base64-encoded version ofdata toio. This method complieswithRFC 2045. Line feeds are added to every 60 encoded characters.

Base64.encode("Now is the time for all good coders\nto learn Crystal", STDOUT)

def encode(data) : String #

Returns the base64-encoded version ofdata. This method complieswithRFC 2045. Line feeds are added to every 60 encoded characters.

puts Base64.encode("Now is the time for all good coders\nto learn Crystal")

Generates:

Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
Q3J5c3RhbA==

def strict_encode(data, io : IO) #

Writes the base64-encoded version ofdatawith no newlines toio. This method complieswithRFC 4648.

Base64.strict_encode("Now is the time for all good coders\nto learn Crystal", STDOUT)

def strict_encode(data) : String #

Returns the base64-encoded version ofdatawith no newlines. This method complieswithRFC 4648.

puts Base64.strict_encode("Now is the time for all good coders\nto learn Crystal")

Generates:

Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4gQ3J5c3RhbA==

def urlsafe_encode(data, io : IO) #

Writes the base64-encoded version ofdata using a urlsafe alphabet toio. This method complieswith"Base 64 Encodingwith URL and Filename Safe Alphabet" inRFC 4648.

The alphabet uses'-' instead of'+' and'_' instead of'/'.


def urlsafe_encode(data, padding = true) : String #

Returns the base64-encoded version ofdata using a urlsafe alphabet. This method complieswith"Base 64 Encodingwith URL and Filename Safe Alphabet" inRFC 4648.

The alphabet uses'-' instead of'+' and'_' instead of'/'.

Thepadding parameter defaults totrue. Whenfalse, enough= characters are not added to make the output divisible by 4.