类 Base64
- java.lang.Object
-
- com.alibaba.nacos.common.codec.Base64
-
public class Base64 extends java.lang.ObjectProvides Base64 encoding and decoding as defined by RFC 2045.This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies by Freed and Borenstein.
The class can be parameterized in the following manner with various constructors:
- URL-safe mode: Default off.
- Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
- Line separator: Default is CRLF ("\r\n")
Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
This class is not thread-safe. Each thread should use its own instance.
- 从以下版本开始:
- 1.0
- 版本:
- $Revision: 1080712 $
- 作者:
- Apache Software Foundation
- 另请参阅:
- RFC 2045
-
-
字段概要
字段 修饰符和类型 字段 说明 private static intBITS_PER_ENCODED_BYTEBASE32 characters are 6 bits in length.private intbitWorkAreaPlace holder for the bytes we're dealing with for our based logic.private byte[]bufferBuffer for streaming.private static intBYTES_PER_ENCODED_BLOCKprivate static intBYTES_PER_UNENCODED_BLOCK(专用程序包) static byte[]CHUNK_SEPARATORChunk separator per RFC 2045 section 2.1.private intchunkSeparatorLengthSize of chunk separator.private intcurrentLinePosVariable tracks how many characters have been written to the current line.private static byte[]DECODE_TABLEThis array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into their 6-bit positive integer equivalents.private intdecodeSizeConvenience variable to help us determine when our buffer is going to run out of room and needs resizing.private byte[]decodeTableOnly one decode table currently; keep for consistency with Base32 code.private static intDEFAULT_BUFFER_RESIZE_FACTORprivate static intDEFAULT_BUFFER_SIZEDefines the default buffer size - currently 8192 - must be large enough for at least one encoded block+separator.private intencodedBlockSizeNumber of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32private intencodeSizeConvenience variable to help us determine when our buffer is going to run out of room and needs resizing.private byte[]encodeTableEncode table to use: either STANDARD or URL_SAFE.private booleaneofBoolean flag to indicate the EOF has been reached.private intlineLengthChunksize for encoding.private byte[]lineSeparatorLine separator for encoding.private static intMASK_6BITSBase64 uses 6-bit fields.private static intMASK_8BITSMask used to extract 8 bits, used in decoding bytes.private static intMIME_CHUNK_SIZEMIME chunk size per RFC 2045 section 6.8.private intmodulusWrites to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding.private static bytePADprivate static bytePAD_DEFAULTByte used to pad output.private intposPosition where next character should be written in the buffer.private intreadPosPosition where next character should be read from the buffer.private static byte[]STANDARD_ENCODE_TABLEThis array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in Table 1 of RFC 2045.private intunencodedBlockSizeNumber of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32private static byte[]URL_SAFE_ENCODE_TABLEThis is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64 results more URL-SAFE.
-
方法概要
所有方法 静态方法 实例方法 具体方法 修饰符和类型 方法 说明 private booleancontainsAlphabetOrPad(byte[] arrayOctet)Tests a given byte array to see if it contains any characters within the alphabet or PAD.private byte[]decode(byte[] pArray)Decodes a byte[] containing characters in the Base-N alphabet.(专用程序包) voiddecode(byte[] in, int inPos, int inAvail)Decodes all of the provided data, starting at inPos, for inAvail bytes.static byte[]decodeBase64(byte[] base64Data)Decodes Base64 data into octets.private byte[]encode(byte[] pArray)Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.(专用程序包) voidencode(byte[] in, int inPos, int inAvail)Encodes all of the provided data, starting at inPos, for inAvail bytes.static byte[]encodeBase64(byte[] binaryData)Encodes binary data using the base64 algorithm but does not chunk the output.static byte[]encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize)Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.private voidensureBufferSize(int size)Ensure that the buffer has room forsizebytes.private longgetEncodedLength(byte[] pArray)Calculates the amount of space needed to encode the supplied array.protected booleanisInAlphabet(byte octet)Returns whether or not theoctetis in the Base32 alphabet.private intreadResults(byte[] b, int bPos, int bAvail)Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes.private voidreset()Resets this object to its initial newly constructed state.
-
-
-
字段详细资料
-
BITS_PER_ENCODED_BYTE
private static final int BITS_PER_ENCODED_BYTE
BASE32 characters are 6 bits in length. They are formed by taking a block of 3 octets to form a 24-bit string, which is converted into 4 BASE64 characters.- 另请参阅:
- 常量字段值
-
BYTES_PER_UNENCODED_BLOCK
private static final int BYTES_PER_UNENCODED_BLOCK
- 另请参阅:
- 常量字段值
-
BYTES_PER_ENCODED_BLOCK
private static final int BYTES_PER_ENCODED_BLOCK
- 另请参阅:
- 常量字段值
-
CHUNK_SEPARATOR
static final byte[] CHUNK_SEPARATOR
Chunk separator per RFC 2045 section 2.1.N.B. The next major release may break compatibility and make this field private.
- 另请参阅:
- RFC 2045 section 2.1
-
STANDARD_ENCODE_TABLE
private static final byte[] STANDARD_ENCODE_TABLE
This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in Table 1 of RFC 2045.Thanks to "commons" project in ws.apache.org for this code.
http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
-
URL_SAFE_ENCODE_TABLE
private static final byte[] URL_SAFE_ENCODE_TABLE
This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64 results more URL-SAFE. This table is only used when the Base64's mode is set to URL-SAFE.
-
DECODE_TABLE
private static final byte[] DECODE_TABLE
This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 alphabet but fall within the bounds of the array are translated to -1.Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
Thanks to "commons" project in ws.apache.org for this code.
http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
-
MASK_6BITS
private static final int MASK_6BITS
Base64 uses 6-bit fields. Mask used to extract 6 bits, used when encoding- 另请参阅:
- 常量字段值
-
encodeTable
private final byte[] encodeTable
Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch between the two modes.
-
decodeTable
private final byte[] decodeTable
Only one decode table currently; keep for consistency with Base32 code.
-
lineSeparator
private final byte[] lineSeparator
Line separator for encoding. Not used when decoding. Only used if lineLength > 0.
-
decodeSize
private final int decodeSize
Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.decodeSize = 3 + lineSeparator.length;
-
encodeSize
private final int encodeSize
Convenience variable to help us determine when our buffer is going to run out of room and needs resizing.encodeSize = 4 + lineSeparator.length;
-
bitWorkArea
private int bitWorkArea
Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the encoding or decoding from this variable.
-
MIME_CHUNK_SIZE
private static final int MIME_CHUNK_SIZE
MIME chunk size per RFC 2045 section 6.8.The 76 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
- 另请参阅:
- RFC 2045 section 6.8, 常量字段值
-
DEFAULT_BUFFER_RESIZE_FACTOR
private static final int DEFAULT_BUFFER_RESIZE_FACTOR
- 另请参阅:
- 常量字段值
-
DEFAULT_BUFFER_SIZE
private static final int DEFAULT_BUFFER_SIZE
Defines the default buffer size - currently 8192 - must be large enough for at least one encoded block+separator.- 另请参阅:
- 常量字段值
-
MASK_8BITS
private static final int MASK_8BITS
Mask used to extract 8 bits, used in decoding bytes.- 另请参阅:
- 常量字段值
-
PAD_DEFAULT
private static final byte PAD_DEFAULT
Byte used to pad output.- 另请参阅:
- 常量字段值
-
PAD
private static final byte PAD
- 另请参阅:
- 常量字段值
-
unencodedBlockSize
private final int unencodedBlockSize
Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32
-
encodedBlockSize
private final int encodedBlockSize
Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
-
lineLength
private final int lineLength
Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. Rounded down to nearest multiple of encodedBlockSize.
-
chunkSeparatorLength
private final int chunkSeparatorLength
Size of chunk separator. Not used unlesslineLength> 0.
-
buffer
private byte[] buffer
Buffer for streaming.
-
pos
private int pos
Position where next character should be written in the buffer.
-
readPos
private int readPos
Position where next character should be read from the buffer.
-
eof
private boolean eof
Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and must be thrown away.
-
currentLinePos
private int currentLinePos
Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to make sure each encoded line never goes beyond lineLength (if lineLength > 0).
-
modulus
private int modulus
Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This variable helps track that.
-
-
构造器详细资料
-
Base64
public Base64()
Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
When decoding all variants are supported.
-
Base64
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe)Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.When encoding the line length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE.
Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
When decoding all variants are supported.
- 参数:
lineLength- Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.lineSeparator- Each line of encoded data will end with this sequence of bytes.urlSafe- Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode operations. Decoding seamlessly handles both modes.- 抛出:
java.lang.IllegalArgumentException- The provided lineSeparator included some base64 characters. That's not going to work!- 从以下版本开始:
- 1.4
-
-
方法详细资料
-
encode
private byte[] encode(byte[] pArray)
Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.- 参数:
pArray- a byte array containing binary data- 返回:
- A byte array containing only the basen alphabetic character data
-
encode
void encode(byte[] in, int inPos, int inAvail)Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last remaining bytes (if not multiple of 3).
Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
- 参数:
in- byte[] array of binary data to base64 encode.inPos- Position to start reading data from.inAvail- Amount of bytes available from input for encoding.
-
decode
private byte[] decode(byte[] pArray)
Decodes a byte[] containing characters in the Base-N alphabet.- 参数:
pArray- A byte array containing Base-N character data- 返回:
- a byte array containing binary data
-
decode
void decode(byte[] in, int inPos, int inAvail)Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1" call is not necessary when decoding, but it doesn't hurt, either.
Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, garbage-out philosophy: it will not check the provided data for validity.
Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
- 参数:
in- byte[] array of ascii data to base64 decode.inPos- Position to start reading data from.inAvail- Amount of bytes available from input for encoding.
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData)
Encodes binary data using the base64 algorithm but does not chunk the output.- 参数:
binaryData- binary data to encode- 返回:
- byte[] containing Base64 characters in their UTF-8 representation.
-
encodeBase64
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize)Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.- 参数:
binaryData- Array containing binary data to encode.isChunked- iftruethis encoder will chunk the base64 output into 76 character blocksurlSafe- iftruethis encoder will emit - and _ instead of the usual + and / characters.maxResultSize- The maximum result size to accept.- 返回:
- Base64-encoded data.
- 抛出:
java.lang.IllegalArgumentException- Thrown when the input array needs an output array bigger than maxResultSize- 从以下版本开始:
- 1.4
-
decodeBase64
public static byte[] decodeBase64(byte[] base64Data)
Decodes Base64 data into octets.- 参数:
base64Data- Byte array containing Base64 data- 返回:
- Array containing decoded data.
-
isInAlphabet
protected boolean isInAlphabet(byte octet)
Returns whether or not theoctetis in the Base32 alphabet.- 参数:
octet- The value to test- 返回:
trueif the value is defined in the the Base32 alphabetfalseotherwise.
-
ensureBufferSize
private void ensureBufferSize(int size)
Ensure that the buffer has room forsizebytes.- 参数:
size- minimum spare space required
-
readResults
private int readResults(byte[] b, int bPos, int bAvail)Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.- 参数:
b- byte[] array to extract the buffered data into.bPos- position in byte[] array to start extraction at.bAvail- amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).- 返回:
- The number of bytes successfully extracted into the provided byte[] array.
-
reset
private void reset()
Resets this object to its initial newly constructed state.
-
containsAlphabetOrPad
private boolean containsAlphabetOrPad(byte[] arrayOctet)
Tests a given byte array to see if it contains any characters within the alphabet or PAD.Intended for use in checking line-ending arrays
- 参数:
arrayOctet- byte array to test- 返回:
trueif any byte is a valid character in the alphabet or PAD;falseotherwise
-
getEncodedLength
private long getEncodedLength(byte[] pArray)
Calculates the amount of space needed to encode the supplied array.- 参数:
pArray- byte[] array which will later be encoded- 返回:
- amount of space needed to encoded the supplied array. Returns a long since a max-len array will require > Integer.MAX_VALUE
-
-