Encodes binary data to plain text as Base64 : Base64 « Development Class « Java






Encodes binary data to plain text as Base64

     
//package com.thoughtworks.xstream.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

/**
 * Encodes binary data to plain text as Base64.
 *
 * <p>Despite there being a gazillion other Base64 implementations out there, this has been written as part of XStream as
 * it forms a core part but is too trivial to warrant an extra dependency.</p>
 *
 * <p>This meets the standard as described in RFC 1521, section 5.2 <http://www.freesoft.org/CIE/RFC/1521/7.htm>, allowing
 * other Base64 tools to manipulate the data.</p>
 *
 * @author Joe Walnes
 */
public class Base64Encoder {

    // Here's how encoding works:
    //
    // 1) Incoming bytes are broken up into groups of 3 (each byte having 8 bits).
    //
    // 2) The combined 24 bits (3 * 8) are split into 4 groups of 6 bits.
    //
    // input  |------||------||------| (3 values each with 8 bits)
    //        101010101010101010101010
    // output |----||----||----||----| (4 values each with 6 bits)
    //
    // 3) Each of these 4 groups of 6 bits are converted back to a number, which will fall in the range of 0 - 63.
    //
    // 4) Each of these 4 numbers are converted to an alphanumeric char in a specified mapping table, to create
    //    a 4 character string.
    //
    // 5) This is repeated for all groups of three bytes.
    //
    // 6) Special padding is done at the end of the stream using the '=' char.

    private static final char[] SIXTY_FOUR_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
    private static final int[] REVERSE_MAPPING = new int[123];

    static {
        for (int i = 0; i < SIXTY_FOUR_CHARS.length; i++) REVERSE_MAPPING[SIXTY_FOUR_CHARS[i]] = i + 1;
    }

    public String encode(byte[] input) {
        StringBuffer result = new StringBuffer();
        int outputCharCount = 0;
        for (int i = 0; i < input.length; i += 3) {
            int remaining = Math.min(3, input.length - i);
            int oneBigNumber = (input[i] & 0xff) << 16 | (remaining <= 1 ? 0 : input[i + 1] & 0xff) << 8 | (remaining <= 2 ? 0 : input[i + 2] & 0xff);
            for (int j = 0; j < 4; j++) result.append(remaining + 1 > j ? SIXTY_FOUR_CHARS[0x3f & oneBigNumber >> 6 * (3 - j)] : '=');
            if ((outputCharCount += 4) % 76 == 0) result.append('\n');
        }
        return result.toString();
    }

    public byte[] decode(String input) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            StringReader in = new StringReader(input);
            for (int i = 0; i < input.length(); i += 4) {
                int a[] = {mapCharToInt(in), mapCharToInt(in), mapCharToInt(in), mapCharToInt(in)};
                int oneBigNumber = (a[0] & 0x3f) << 18 | (a[1] & 0x3f) << 12 | (a[2] & 0x3f) << 6 | (a[3] & 0x3f);
                for (int j = 0; j < 3; j++) if (a[j + 1] >= 0) out.write(0xff & oneBigNumber >> 8 * (2 - j));
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new Error(e + ": " + e.getMessage());
        }
    }

    private int mapCharToInt(Reader input) throws IOException {
        int c;
        while ((c = input.read()) != -1) {
            int result = REVERSE_MAPPING[c];
            if (result != 0) return result -1;
            if (c == '=') return -1;
        }
        return -1;
    }
}

   
    
    
    
    
  








Related examples in the same category

1.Base64 encoding/decoding.
2.Decodes Base64 data into octects
3.Implementation of MIME's Base64 encoding and decoding conversions.
4.Encode/decode for RFC 2045 Base64 as defined by RFC 2045
5.Encode/decode for RFC 2045 Base64 as defined by RFC 2045, N. Freed and N. Borenstein.
6.Encodes and decodes to and from Base64 notation.
7.Encodes hex octects into Base64
8.Helper class to provide Base64 encoding routines.
9.Represents a collection of 64 boolean (on/off) flags.
10.byte to be tested if it is Base64 alphabet
11.to Base64
12.One of the fastest implementation of the Base64 encoding. Jakarta and others are slower
13.array of byte to encode
14.Codes number up to radix 62
15.A Base64 Encoder/Decoder
16.A fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045
17.BASE64 encoder implementation
18.Base-64 Encoder - translates from base-64 text into binary
19.Base64 Character encoder as specified in RFC1113
20.Base64 Utils
21.Base64 encoder/decoder
22.Base64 from by Funambol, Inc.
23.Convert to hex from byte arrays and back
24.Converting hexadecimal strings
25.Encode and decode data in Base64 format as described in RFC 1521
26.Encode and decode integers, times, and internationalized strings to and from popular binary formats
27.Encoding of raw bytes to base64-encoded characters, and decoding of base64 characters to raw bytes
28.Performs Base64 encoding and/or decoding
29.Provides Base64 encoding and decoding as defined by RFC 2045
30.Provides Base64 encoding and decoding with URL and filename safe alphabet as defined by RFC 3548, section 4.
31.Provides utility methods to Base64 encode data
32.QP Decoder Stream
33.QP Encoder Stream
34.A class to decode Base64 streams and strings.
35.A class to encode Base64 streams and strings.
36.A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045.
37.Decodes InputStreams which contain binary data in base64 form
38.Base 64 Converter
39.Base64 from org.cspoker.common.util
40.Base64 converted from code at http://iharder.sourceforge.net/base64/
41.Encodes and decodes to and from Base64 notation.
42.Simple Base64 string decoding function
43.Class to represent unsigned 64-bit numbers.
44.A Base64 encoder/decoder.
45.The Base64 utility class implements Base-64 and Base-85 encoding and decoding algorithms.
46.Provides Base64 encoding and decoding
47.Code to read and write Base64-encoded text.
48.Base32 encoding/decoding class.