Java implementation of Base64_encode and Base64_decode _java

Source: Internet
Author: User
Tags base64

Base64 is one of the most common coding methods for transmitting 8Bit byte code on the network, and you can view the rfc2045~rfc2049, which has a MIME detail specification. BASE64 requires converting every three 8Bit bytes to four 6Bit bytes (3*8 = 4*6 = 24), and then adding 6Bit two-bit high 0 to form four 8Bit bytes, that is, the converted string is theoretically going to be longer than the original 1/3

PHP functions: Base64_encode () and Base64_decode ()

The principle of Base64 and decoding

The BASE64 encoding actually converts 3 8-bit bytes to 4 6-bit bytes, (3*8 = 4*6 = 24), and 4 six-bit bytes are still 8, but the high two bits are set to 0. When a byte is only 6 bits valid, its value space is 0 to 2 of 6 times minus 1 is 63, that is, the converted Base64 encoding each encoded value space is (0~63).

In fact, there are many invisible characters in the ASCII code between 0~63, so you should do another mapping, the mapping table is

' A ' ~ ' Z '? ASCII (0 ~ 25)

' A ' ~ ' Z '? ASCII (26 ~ 51)

' 0 ' ~ ' 9 '? ASCII (52 ~ 61)

' ' ? ASCII (62)

'/' ? ASCII (63)

This allows you to convert 3 8-bit bytes to 4 visible characters.

The specific byte splitting method is: (Picture not good, comprehend spirit:-))

Aaaaaabb ccccdddd eeffffff//abcdef is actually 1 or 0, in order to see clearly with abcdef instead

~~~~~~~~ ~~~~~~~~ ~~~~~~~~

Bytes 1 bytes 2 bytes 3

||
\/

00AAAAAA 00BBCCCC 00ddddee 00ffffff

Note: The three byte bits above, the four bytes below are BASE64 encoded, and the first two digits are 0.

In this way, the number of bytes in the original text should be a multiple of 3, when this condition is not satisfied, with full 0 bytes

To make up, the conversion of Base64 code with the = number instead, which is why some Base64 encoding with one or two equal sign knot

The reason for the bundle, but the equals sign has up to two, because: if f (Origin) represents the number of bytes in the original text, F (remain) generation

Table remainder, you

F (remain) = f (Origin) MOD 3 was established.

So the possible value of f (remain) is 0,1,2.

If you set n = [F (origin) –f (remain)]/3

When f (remain) = 0 o'clock, exactly converts to the Base64 encoding of 4*n bytes.

When f (remain) = 1 o'clock, a text byte can be split into two Base64 encoded bytes, in order to

Let the BASE64 encoding be a multiple of 4, so it should be a 2 equals sign.

When f (remain) = 2 o'clock, because two text bytes can be split into 3 Base64 encoded bytes,

An equal sign should be filled in.

There are 0 to 2 equal signs at the end of the base64 encoded string, which are not necessary to decode, so they can be deleted.
In the network get and post parameter list, ' + ' is not normal transmission, you can replace it with ' | '
So after the Base64 encoded string is only ' | ' and '/', so the string that handles the base64 encoding can be transmitted as a parameter value of the argument list.

========================================================================
The following is an implementation written by a foreigner:
Package com.meterware.httpunit;

/************************************************************************************************************** ******
* $Id: base64.java,v 1.4 2002/12/24 15:17:17 russgold EXP $
*
* Copyright (c) 2000-2002 by Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* Documentation Files (the "Software"), to deal in the Software without restriction, including without
* The rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* To permit persons to whom the Software are furnished to did, subject to the following:
*
* The above copyright notice and this permission notice shall is included in all copies or substantial portions
* of the Software.
*
* 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 or COPYRIGHT holders be liable to any CLAIM, damages or other liability, WHETHER in an ACTION of
* CONTRACT, TORT or otherwise, arising from, out to or in CONNECTION with the SOFTWARE or
* Dealings in the SOFTWARE.
*
*************************************************************************************************************** ****/

/**
* A Utility class to convert to and from base encoding.
*
* @author <a href= "mailto:russgold@httpunit.org" > Russell Gold </a>
**/
public class Base64 {final static String Encodingchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345 6789+/"; /** * Returns The base encoded equivalent of a supplied string. * @param source The string to encode */public static string encode (string source) {char[] sourcebytes = Getpad Dedbytes (source); int numgroups = (sourcebytes.length + 2)/3; char[] targetbytes = new Char[4]; char[] target = new char[4 * numgroups]; for (int group = 0; group < numgroups; group++) {convert3to4 (sourcebytes, group*3, targetbytes); for (int i = 0; i < targetbytes.length i++) {target[i + 4*group] = Encodingchar.charat (targetbytes[i)); } int numpadbytes = Sourcebytes.length-source.length (); for (int i = Target.length-numpadbytes i < target.length i++) target[i] = ' = '; return new String (target); private static char[] Getpaddedbytes (String source) {char[] converted = Source.tocHararray (); int requiredlength = 3 * ((CONVERTED.LENGTH+2)/3); Char[] result = new char[requiredlength]; System.arraycopy (converted, 0, result, 0, converted.length); return result; private static void Convert3to4 (char[] source, int sourceindex, char[] target) {target[0] = (char) (source[s Ourceindex] > > > 2); TARGET[1] = (char) ((source[sourceindex] & 0x03) < < 4) | (source[sourceindex+1] > > > 4)); TARGET[2] = (char) ((source[sourceindex+1] & 0x0f) < < 2) | (source[sourceindex+2] > > > 6)); TARGET[3] = (char) (source[sourceindex+2] & 0x3f); }/** * Returns the plaintext equivalent of a base 64-encoded string. * @param source a base-which string (must have a multiple of 4 characters) */public static string decode (string SOURCE) {if (Source.length ()%4!= 0) throw new runtimeexception ("Valid Base64 codes have a multiple of 4 characters " ); int NumgrouPS = Source.length ()/4; int numextrabytes = Source.endswith ("= =")? 2: (Source.endswith ("=")? 1:0); byte[] targetbytes = new byte[3*numgroups]; byte[] sourcebytes = new Byte[4]; for (int group = 0; group < numgroups. group++) {for (int i = 0; i < sourcebytes.length; i++) {Sourcebyte S[i] = (byte) math.max (0, Encodingchar.indexof (Source.charat (4*group+i))); } Convert4to3 (Sourcebytes, targetbytes, group*3); Return to New String (targetbytes, 0, targetbytes.length-numextrabytes); private static void Convert4to3 (byte[] source, byte[] target, int targetindex) {target[Targetindex] = (byte) ((Source[0] < < 2) | (Source[1] > > > 4)); target[targetindex+1] = (byte) ((Source[1] & 0x0f) < < 4) | (Source[2] > > > 2)); target[targetindex+2] = (byte) ((Source[2] & 0x03) < < 6) | (Source[3])); } }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.