All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.text.Base64Encode Maven / Gradle / Ivy

/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.text;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Encode a string or a stream in base 64.
 */
public class Base64Encode {

	private static final int END_MARKER = -1;

	protected static final byte[] LOOKUP_MAP = {
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
		'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
		'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
		'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
		'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
		'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
		'w', 'x', 'y', 'z', '0', '1', '2', '3',
		'4', '5', '6', '7', '8', '9', '+', '/',
	};

	/**
	 * Encode a String in Base64 using default character encoding.
	 *
	 * @param string The string to encode.
	 * @return A base 64 encoded String.
	 */
	public static String encode(String string) {
		return encode(string.getBytes());
	}

	/**
	 * Encode bytes in Base64.
	 *
	 * @param bytes The data to encode.
	 * @return Encoded base 64 string.
	 */
	public static String encode(byte[] bytes) {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		int length = bytes.length;
		int mod;

		// Size of output buffer will be (bytes * (4/3)).
		if ((mod = length % 3) != 0){
			length += 3 - mod;
		}
		length = length * 4 / 3;
		ByteArrayOutputStream out = new ByteArrayOutputStream(length);
		try {
			encode(in, out);
		} catch (IOException x) {
			// Reading/writing to from Input/OutputStream should not
			// ever fail, so passing up (and hence requiring handling of)
			// an IOException is not useful. IF an IOException ever occurs
			// something really strange is going on. (Hence RuntimeException)
			throw new RuntimeException(x);
		}
		return new String(out.toByteArray());
	}

	/**
	 * Encode data from the InputStream to the OutputStream in Base64.
	 *
	 * @param in Stream from which to read data that needs to be encoded.
	 * @param out Stream to which to write encoded data.
	 * @throws IOException if there is a problem reading or writing.
	 *
	 */
	public static void encode(InputStream in, OutputStream out) throws IOException {
		int[] inBuffer = new int[3];

		boolean done = false;
		while (!done && (inBuffer[0] = in.read()) != END_MARKER) {
			// Fill the buffer
			inBuffer[1] = in.read();
			inBuffer[2] = in.read();

			/*
			 * The first byte of input is valid but must check other two bytes
			 * are not equal to END_MARKER. Each set of three bytes add up to 24
			 * bits, the 24 bits are split up into 4 bytes of 6 bits and
			 * converted to ascii characters.
			 *
			 * If there are not enough bytes to make a 24 bit group, the
			 * remaining ascii characters are converted to the = character.
			 */

			// Byte 1: first six bits of first byte
			out.write(LOOKUP_MAP[inBuffer[0] >> 2]);
			if (inBuffer[1] != END_MARKER) {
				// Byte 2: last two bits of first byte, first four bits of
				// second byte
				out.write(LOOKUP_MAP[((inBuffer[0] << 4) & 0x30) | (inBuffer[1] >> 4)]);
				if (inBuffer[2] != END_MARKER) {
					// Byte 3: last four bits of second byte, first two bits of
					// third byte
					out.write(LOOKUP_MAP[((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6)]);
					// Byte 4: last six bits of third byte
					out.write(LOOKUP_MAP[inBuffer[2] & 0x3F]);
				} else {
					// Byte 3: last four bits of second byte
					out.write(LOOKUP_MAP[((inBuffer[1] << 2) & 0x3c)]);
					// Output = if no more characters to write
					out.write('=');
					done = true;
				}
			} else {
				// Byte 2: last two bits of first byte
				out.write(LOOKUP_MAP[((inBuffer[0] << 4) & 0x30)]);
				// Output = if no more characters to write
				out.write('=');
				out.write('=');
				done = true;
			}
		}
		out.flush();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy