Path: blob/master/src/java.base/share/classes/java/util/Base64.java
41152 views
/*1* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.io.FilterOutputStream;28import java.io.InputStream;29import java.io.IOException;30import java.io.OutputStream;31import java.nio.ByteBuffer;3233import sun.nio.cs.ISO_8859_1;3435import jdk.internal.vm.annotation.IntrinsicCandidate;3637/**38* This class consists exclusively of static methods for obtaining39* encoders and decoders for the Base64 encoding scheme. The40* implementation of this class supports the following types of Base6441* as specified in42* <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a> and43* <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.44*45* <ul>46* <li><a id="basic"><b>Basic</b></a>47* <p> Uses "The Base64 Alphabet" as specified in Table 1 of48* RFC 4648 and RFC 2045 for encoding and decoding operation.49* The encoder does not add any line feed (line separator)50* character. The decoder rejects data that contains characters51* outside the base64 alphabet.</p></li>52*53* <li><a id="url"><b>URL and Filename safe</b></a>54* <p> Uses the "URL and Filename safe Base64 Alphabet" as specified55* in Table 2 of RFC 4648 for encoding and decoding. The56* encoder does not add any line feed (line separator) character.57* The decoder rejects data that contains characters outside the58* base64 alphabet.</p></li>59*60* <li><a id="mime"><b>MIME</b></a>61* <p> Uses "The Base64 Alphabet" as specified in Table 1 of62* RFC 2045 for encoding and decoding operation. The encoded output63* must be represented in lines of no more than 76 characters each64* and uses a carriage return {@code '\r'} followed immediately by65* a linefeed {@code '\n'} as the line separator. No line separator66* is added to the end of the encoded output. All line separators67* or other characters not found in the base64 alphabet table are68* ignored in decoding operation.</p></li>69* </ul>70*71* <p> Unless otherwise noted, passing a {@code null} argument to a72* method of this class will cause a {@link java.lang.NullPointerException73* NullPointerException} to be thrown.74*75* @author Xueming Shen76* @since 1.877*/7879public class Base64 {8081private Base64() {}8283/**84* Returns a {@link Encoder} that encodes using the85* <a href="#basic">Basic</a> type base64 encoding scheme.86*87* @return A Base64 encoder.88*/89public static Encoder getEncoder() {90return Encoder.RFC4648;91}9293/**94* Returns a {@link Encoder} that encodes using the95* <a href="#url">URL and Filename safe</a> type base6496* encoding scheme.97*98* @return A Base64 encoder.99*/100public static Encoder getUrlEncoder() {101return Encoder.RFC4648_URLSAFE;102}103104/**105* Returns a {@link Encoder} that encodes using the106* <a href="#mime">MIME</a> type base64 encoding scheme.107*108* @return A Base64 encoder.109*/110public static Encoder getMimeEncoder() {111return Encoder.RFC2045;112}113114/**115* Returns a {@link Encoder} that encodes using the116* <a href="#mime">MIME</a> type base64 encoding scheme117* with specified line length and line separators.118*119* @param lineLength120* the length of each output line (rounded down to nearest multiple121* of 4). If the rounded down line length is not a positive value,122* the output will not be separated in lines123* @param lineSeparator124* the line separator for each output line125*126* @return A Base64 encoder.127*128* @throws IllegalArgumentException if {@code lineSeparator} includes any129* character of "The Base64 Alphabet" as specified in Table 1 of130* RFC 2045.131*/132public static Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) {133Objects.requireNonNull(lineSeparator);134int[] base64 = Decoder.fromBase64;135for (byte b : lineSeparator) {136if (base64[b & 0xff] != -1)137throw new IllegalArgumentException(138"Illegal base64 line separator character 0x" + Integer.toString(b, 16));139}140// round down to nearest multiple of 4141lineLength &= ~0b11;142if (lineLength <= 0) {143return Encoder.RFC4648;144}145return new Encoder(false, lineSeparator, lineLength, true);146}147148/**149* Returns a {@link Decoder} that decodes using the150* <a href="#basic">Basic</a> type base64 encoding scheme.151*152* @return A Base64 decoder.153*/154public static Decoder getDecoder() {155return Decoder.RFC4648;156}157158/**159* Returns a {@link Decoder} that decodes using the160* <a href="#url">URL and Filename safe</a> type base64161* encoding scheme.162*163* @return A Base64 decoder.164*/165public static Decoder getUrlDecoder() {166return Decoder.RFC4648_URLSAFE;167}168169/**170* Returns a {@link Decoder} that decodes using the171* <a href="#mime">MIME</a> type base64 decoding scheme.172*173* @return A Base64 decoder.174*/175public static Decoder getMimeDecoder() {176return Decoder.RFC2045;177}178179/**180* This class implements an encoder for encoding byte data using181* the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.182*183* <p> Instances of {@link Encoder} class are safe for use by184* multiple concurrent threads.185*186* <p> Unless otherwise noted, passing a {@code null} argument to187* a method of this class will cause a188* {@link java.lang.NullPointerException NullPointerException} to189* be thrown.190* <p> If the encoded byte output of the needed size can not191* be allocated, the encode methods of this class will192* cause an {@link java.lang.OutOfMemoryError OutOfMemoryError}193* to be thrown.194*195* @see Decoder196* @since 1.8197*/198public static class Encoder {199200private final byte[] newline;201private final int linemax;202private final boolean isURL;203private final boolean doPadding;204205private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) {206this.isURL = isURL;207this.newline = newline;208this.linemax = linemax;209this.doPadding = doPadding;210}211212/**213* This array is a lookup table that translates 6-bit positive integer214* index values into their "Base64 Alphabet" equivalents as specified215* in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).216*/217private static final char[] toBase64 = {218'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',219'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',220'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',221'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',222'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'223};224225/**226* It's the lookup table for "URL and Filename safe Base64" as specified227* in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and228* '_'. This table is used when BASE64_URL is specified.229*/230private static final char[] toBase64URL = {231'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',232'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',233'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',234'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',235'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'236};237238private static final int MIMELINEMAX = 76;239private static final byte[] CRLF = new byte[] {'\r', '\n'};240241static final Encoder RFC4648 = new Encoder(false, null, -1, true);242static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true);243static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true);244245/**246* Calculates the length of the encoded output bytes.247*248* @param srclen length of the bytes to encode249* @param throwOOME if true, throws OutOfMemoryError if the length of250* the encoded bytes overflows; else returns the251* length252* @return length of the encoded bytes, or -1 if the length overflows253*254*/255private final int encodedOutLength(int srclen, boolean throwOOME) {256int len = 0;257try {258if (doPadding) {259len = Math.multiplyExact(4, (Math.addExact(srclen, 2) / 3));260} else {261int n = srclen % 3;262len = Math.addExact(Math.multiplyExact(4, (srclen / 3)), (n == 0 ? 0 : n + 1));263}264if (linemax > 0) { // line separators265len = Math.addExact(len, (len - 1) / linemax * newline.length);266}267} catch (ArithmeticException ex) {268if (throwOOME) {269throw new OutOfMemoryError("Encoded size is too large");270} else {271// let the caller know that encoded bytes length272// is too large273len = -1;274}275}276return len;277}278279/**280* Encodes all bytes from the specified byte array into a newly-allocated281* byte array using the {@link Base64} encoding scheme. The returned byte282* array is of the length of the resulting bytes.283*284* @param src285* the byte array to encode286* @return A newly-allocated byte array containing the resulting287* encoded bytes.288*/289public byte[] encode(byte[] src) {290int len = encodedOutLength(src.length, true); // dst array size291byte[] dst = new byte[len];292int ret = encode0(src, 0, src.length, dst);293if (ret != dst.length)294return Arrays.copyOf(dst, ret);295return dst;296}297298/**299* Encodes all bytes from the specified byte array using the300* {@link Base64} encoding scheme, writing the resulting bytes to the301* given output byte array, starting at offset 0.302*303* <p> It is the responsibility of the invoker of this method to make304* sure the output byte array {@code dst} has enough space for encoding305* all bytes from the input byte array. No bytes will be written to the306* output byte array if the output byte array is not big enough.307*308* @param src309* the byte array to encode310* @param dst311* the output byte array312* @return The number of bytes written to the output byte array313*314* @throws IllegalArgumentException if {@code dst} does not have enough315* space for encoding all input bytes.316*/317public int encode(byte[] src, byte[] dst) {318int len = encodedOutLength(src.length, false); // dst array size319if (dst.length < len || len == -1)320throw new IllegalArgumentException(321"Output byte array is too small for encoding all input bytes");322return encode0(src, 0, src.length, dst);323}324325/**326* Encodes the specified byte array into a String using the {@link Base64}327* encoding scheme.328*329* <p> This method first encodes all input bytes into a base64 encoded330* byte array and then constructs a new String by using the encoded byte331* array and the {@link java.nio.charset.StandardCharsets#ISO_8859_1332* ISO-8859-1} charset.333*334* <p> In other words, an invocation of this method has exactly the same335* effect as invoking336* {@code new String(encode(src), StandardCharsets.ISO_8859_1)}.337*338* @param src339* the byte array to encode340* @return A String containing the resulting Base64 encoded characters341*/342@SuppressWarnings("deprecation")343public String encodeToString(byte[] src) {344byte[] encoded = encode(src);345return new String(encoded, 0, 0, encoded.length);346}347348/**349* Encodes all remaining bytes from the specified byte buffer into350* a newly-allocated ByteBuffer using the {@link Base64} encoding351* scheme.352*353* Upon return, the source buffer's position will be updated to354* its limit; its limit will not have been changed. The returned355* output buffer's position will be zero and its limit will be the356* number of resulting encoded bytes.357*358* @param buffer359* the source ByteBuffer to encode360* @return A newly-allocated byte buffer containing the encoded bytes.361*/362public ByteBuffer encode(ByteBuffer buffer) {363int len = encodedOutLength(buffer.remaining(), true);364byte[] dst = new byte[len];365int ret = 0;366if (buffer.hasArray()) {367ret = encode0(buffer.array(),368buffer.arrayOffset() + buffer.position(),369buffer.arrayOffset() + buffer.limit(),370dst);371buffer.position(buffer.limit());372} else {373byte[] src = new byte[buffer.remaining()];374buffer.get(src);375ret = encode0(src, 0, src.length, dst);376}377if (ret != dst.length)378dst = Arrays.copyOf(dst, ret);379return ByteBuffer.wrap(dst);380}381382/**383* Wraps an output stream for encoding byte data using the {@link Base64}384* encoding scheme.385*386* <p> It is recommended to promptly close the returned output stream after387* use, during which it will flush all possible leftover bytes to the underlying388* output stream. Closing the returned output stream will close the underlying389* output stream.390*391* @param os392* the output stream.393* @return the output stream for encoding the byte data into the394* specified Base64 encoded format395*/396public OutputStream wrap(OutputStream os) {397Objects.requireNonNull(os);398return new EncOutputStream(os, isURL ? toBase64URL : toBase64,399newline, linemax, doPadding);400}401402/**403* Returns an encoder instance that encodes equivalently to this one,404* but without adding any padding character at the end of the encoded405* byte data.406*407* <p> The encoding scheme of this encoder instance is unaffected by408* this invocation. The returned encoder instance should be used for409* non-padding encoding operation.410*411* @return an equivalent encoder that encodes without adding any412* padding character at the end413*/414public Encoder withoutPadding() {415if (!doPadding)416return this;417return new Encoder(isURL, newline, linemax, false);418}419420@IntrinsicCandidate421private void encodeBlock(byte[] src, int sp, int sl, byte[] dst, int dp, boolean isURL) {422char[] base64 = isURL ? toBase64URL : toBase64;423for (int sp0 = sp, dp0 = dp ; sp0 < sl; ) {424int bits = (src[sp0++] & 0xff) << 16 |425(src[sp0++] & 0xff) << 8 |426(src[sp0++] & 0xff);427dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f];428dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f];429dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f];430dst[dp0++] = (byte)base64[bits & 0x3f];431}432}433434private int encode0(byte[] src, int off, int end, byte[] dst) {435char[] base64 = isURL ? toBase64URL : toBase64;436int sp = off;437int slen = (end - off) / 3 * 3;438int sl = off + slen;439if (linemax > 0 && slen > linemax / 4 * 3)440slen = linemax / 4 * 3;441int dp = 0;442while (sp < sl) {443int sl0 = Math.min(sp + slen, sl);444encodeBlock(src, sp, sl0, dst, dp, isURL);445int dlen = (sl0 - sp) / 3 * 4;446dp += dlen;447sp = sl0;448if (dlen == linemax && sp < end) {449for (byte b : newline){450dst[dp++] = b;451}452}453}454if (sp < end) { // 1 or 2 leftover bytes455int b0 = src[sp++] & 0xff;456dst[dp++] = (byte)base64[b0 >> 2];457if (sp == end) {458dst[dp++] = (byte)base64[(b0 << 4) & 0x3f];459if (doPadding) {460dst[dp++] = '=';461dst[dp++] = '=';462}463} else {464int b1 = src[sp++] & 0xff;465dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)];466dst[dp++] = (byte)base64[(b1 << 2) & 0x3f];467if (doPadding) {468dst[dp++] = '=';469}470}471}472return dp;473}474}475476/**477* This class implements a decoder for decoding byte data using the478* Base64 encoding scheme as specified in RFC 4648 and RFC 2045.479*480* <p> The Base64 padding character {@code '='} is accepted and481* interpreted as the end of the encoded byte data, but is not482* required. So if the final unit of the encoded byte data only has483* two or three Base64 characters (without the corresponding padding484* character(s) padded), they are decoded as if followed by padding485* character(s). If there is a padding character present in the486* final unit, the correct number of padding character(s) must be487* present, otherwise {@code IllegalArgumentException} (488* {@code IOException} when reading from a Base64 stream) is thrown489* during decoding.490*491* <p> Instances of {@link Decoder} class are safe for use by492* multiple concurrent threads.493*494* <p> Unless otherwise noted, passing a {@code null} argument to495* a method of this class will cause a496* {@link java.lang.NullPointerException NullPointerException} to497* be thrown.498* <p> If the decoded byte output of the needed size can not499* be allocated, the decode methods of this class will500* cause an {@link java.lang.OutOfMemoryError OutOfMemoryError}501* to be thrown.502*503* @see Encoder504* @since 1.8505*/506public static class Decoder {507508private final boolean isURL;509private final boolean isMIME;510511private Decoder(boolean isURL, boolean isMIME) {512this.isURL = isURL;513this.isMIME = isMIME;514}515516/**517* Lookup table for decoding unicode characters drawn from the518* "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into519* their 6-bit positive integer equivalents. Characters that520* are not in the Base64 alphabet but fall within the bounds of521* the array are encoded to -1.522*523*/524private static final int[] fromBase64 = new int[256];525static {526Arrays.fill(fromBase64, -1);527for (int i = 0; i < Encoder.toBase64.length; i++)528fromBase64[Encoder.toBase64[i]] = i;529fromBase64['='] = -2;530}531532/**533* Lookup table for decoding "URL and Filename safe Base64 Alphabet"534* as specified in Table2 of the RFC 4648.535*/536private static final int[] fromBase64URL = new int[256];537538static {539Arrays.fill(fromBase64URL, -1);540for (int i = 0; i < Encoder.toBase64URL.length; i++)541fromBase64URL[Encoder.toBase64URL[i]] = i;542fromBase64URL['='] = -2;543}544545static final Decoder RFC4648 = new Decoder(false, false);546static final Decoder RFC4648_URLSAFE = new Decoder(true, false);547static final Decoder RFC2045 = new Decoder(false, true);548549/**550* Decodes all bytes from the input byte array using the {@link Base64}551* encoding scheme, writing the results into a newly-allocated output552* byte array. The returned byte array is of the length of the resulting553* bytes.554*555* @param src556* the byte array to decode557*558* @return A newly-allocated byte array containing the decoded bytes.559*560* @throws IllegalArgumentException561* if {@code src} is not in valid Base64 scheme562*/563public byte[] decode(byte[] src) {564byte[] dst = new byte[decodedOutLength(src, 0, src.length)];565int ret = decode0(src, 0, src.length, dst);566if (ret != dst.length) {567dst = Arrays.copyOf(dst, ret);568}569return dst;570}571572/**573* Decodes a Base64 encoded String into a newly-allocated byte array574* using the {@link Base64} encoding scheme.575*576* <p> An invocation of this method has exactly the same effect as invoking577* {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))}578*579* @param src580* the string to decode581*582* @return A newly-allocated byte array containing the decoded bytes.583*584* @throws IllegalArgumentException585* if {@code src} is not in valid Base64 scheme586*/587public byte[] decode(String src) {588return decode(src.getBytes(ISO_8859_1.INSTANCE));589}590591/**592* Decodes all bytes from the input byte array using the {@link Base64}593* encoding scheme, writing the results into the given output byte array,594* starting at offset 0.595*596* <p> It is the responsibility of the invoker of this method to make597* sure the output byte array {@code dst} has enough space for decoding598* all bytes from the input byte array. No bytes will be written to599* the output byte array if the output byte array is not big enough.600*601* <p> If the input byte array is not in valid Base64 encoding scheme602* then some bytes may have been written to the output byte array before603* IllegalargumentException is thrown.604*605* @param src606* the byte array to decode607* @param dst608* the output byte array609*610* @return The number of bytes written to the output byte array611*612* @throws IllegalArgumentException613* if {@code src} is not in valid Base64 scheme, or {@code dst}614* does not have enough space for decoding all input bytes.615*/616public int decode(byte[] src, byte[] dst) {617int len = decodedOutLength(src, 0, src.length);618if (dst.length < len || len == -1)619throw new IllegalArgumentException(620"Output byte array is too small for decoding all input bytes");621return decode0(src, 0, src.length, dst);622}623624/**625* Decodes all bytes from the input byte buffer using the {@link Base64}626* encoding scheme, writing the results into a newly-allocated ByteBuffer.627*628* <p> Upon return, the source buffer's position will be updated to629* its limit; its limit will not have been changed. The returned630* output buffer's position will be zero and its limit will be the631* number of resulting decoded bytes632*633* <p> {@code IllegalArgumentException} is thrown if the input buffer634* is not in valid Base64 encoding scheme. The position of the input635* buffer will not be advanced in this case.636*637* @param buffer638* the ByteBuffer to decode639*640* @return A newly-allocated byte buffer containing the decoded bytes641*642* @throws IllegalArgumentException643* if {@code buffer} is not in valid Base64 scheme644*/645public ByteBuffer decode(ByteBuffer buffer) {646int pos0 = buffer.position();647try {648byte[] src;649int sp, sl;650if (buffer.hasArray()) {651src = buffer.array();652sp = buffer.arrayOffset() + buffer.position();653sl = buffer.arrayOffset() + buffer.limit();654buffer.position(buffer.limit());655} else {656src = new byte[buffer.remaining()];657buffer.get(src);658sp = 0;659sl = src.length;660}661byte[] dst = new byte[decodedOutLength(src, sp, sl)];662return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst));663} catch (IllegalArgumentException iae) {664buffer.position(pos0);665throw iae;666}667}668669/**670* Returns an input stream for decoding {@link Base64} encoded byte stream.671*672* <p> The {@code read} methods of the returned {@code InputStream} will673* throw {@code IOException} when reading bytes that cannot be decoded.674*675* <p> Closing the returned input stream will close the underlying676* input stream.677*678* @param is679* the input stream680*681* @return the input stream for decoding the specified Base64 encoded682* byte stream683*/684public InputStream wrap(InputStream is) {685Objects.requireNonNull(is);686return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME);687}688689/**690* Calculates the length of the decoded output bytes.691*692* @param src the byte array to decode693* @param sp the source position694* @param sl the source limit695*696* @return length of the decoded bytes697*698*/699private int decodedOutLength(byte[] src, int sp, int sl) {700int[] base64 = isURL ? fromBase64URL : fromBase64;701int paddings = 0;702int len = sl - sp;703if (len == 0)704return 0;705if (len < 2) {706if (isMIME && base64[0] == -1)707return 0;708throw new IllegalArgumentException(709"Input byte[] should at least have 2 bytes for base64 bytes");710}711if (isMIME) {712// scan all bytes to fill out all non-alphabet. a performance713// trade-off of pre-scan or Arrays.copyOf714int n = 0;715while (sp < sl) {716int b = src[sp++] & 0xff;717if (b == '=') {718len -= (sl - sp + 1);719break;720}721if ((b = base64[b]) == -1)722n++;723}724len -= n;725} else {726if (src[sl - 1] == '=') {727paddings++;728if (src[sl - 2] == '=')729paddings++;730}731}732if (paddings == 0 && (len & 0x3) != 0)733paddings = 4 - (len & 0x3);734735// If len is near to Integer.MAX_VALUE, (len + 3)736// can possibly overflow, perform this operation as737// long and cast it back to integer when the value comes under738// integer limit. The final value will always be in integer739// limits740return 3 * (int) ((len + 3L) / 4) - paddings;741}742743/**744* Decodes base64 characters, and returns the number of data bytes745* written into the destination array.746*747* It is the fast path for full 4-byte to 3-byte decoding w/o errors.748*749* decodeBlock() can be overridden by an arch-specific intrinsic.750* decodeBlock can choose to decode all, none, or a variable-sized751* prefix of the src bytes. This allows the intrinsic to decode in752* chunks of the src that are of a favorable size for the specific753* processor it's running on.754*755* If the intrinsic function does not process all of the bytes in756* src, it must process a multiple of four of them, making the757* returned destination length a multiple of three.758*759* If any illegal base64 bytes are encountered in src by the760* intrinsic, the intrinsic must return the actual number of valid761* data bytes already written to dst. Note that the '=' pad762* character is treated as an illegal Base64 character by763* decodeBlock, so it will not process a block of 4 bytes764* containing pad characters.765*766* Given the parameters, no length check is possible on dst, so dst767* is assumed to be large enough to store the decoded bytes.768*769* @param src770* the source byte array of Base64 encoded bytes771* @param sp772* the offset into src array to begin reading773* @param sl774* the offset (exclusive) past the last byte to be converted.775* @param dst776* the destination byte array of decoded data bytes777* @param dp778* the offset into dst array to begin writing779* @param isURL780* boolean, when true decode RFC4648 URL-safe base64 characters781* @return the number of destination data bytes produced782*/783@IntrinsicCandidate784private int decodeBlock(byte[] src, int sp, int sl, byte[] dst, int dp, boolean isURL) {785int[] base64 = isURL ? fromBase64URL : fromBase64;786int sl0 = sp + ((sl - sp) & ~0b11);787int new_dp = dp;788while (sp < sl0) {789int b1 = base64[src[sp++] & 0xff];790int b2 = base64[src[sp++] & 0xff];791int b3 = base64[src[sp++] & 0xff];792int b4 = base64[src[sp++] & 0xff];793if ((b1 | b2 | b3 | b4) < 0) { // non base64 byte794return new_dp - dp;795}796int bits0 = b1 << 18 | b2 << 12 | b3 << 6 | b4;797dst[new_dp++] = (byte)(bits0 >> 16);798dst[new_dp++] = (byte)(bits0 >> 8);799dst[new_dp++] = (byte)(bits0);800}801return new_dp - dp;802}803804private int decode0(byte[] src, int sp, int sl, byte[] dst) {805int[] base64 = isURL ? fromBase64URL : fromBase64;806int dp = 0;807int bits = 0;808int shiftto = 18; // pos of first byte of 4-byte atom809810while (sp < sl) {811if (shiftto == 18 && sp < sl - 4) { // fast path812int dl = decodeBlock(src, sp, sl, dst, dp, isURL);813/*814* Calculate how many characters were processed by how many815* bytes of data were returned.816*/817int chars_decoded = (dl / 3) * 4;818819sp += chars_decoded;820dp += dl;821}822if (sp >= sl) {823// we're done824break;825}826int b = src[sp++] & 0xff;827if ((b = base64[b]) < 0) {828if (b == -2) { // padding byte '='829// = shiftto==18 unnecessary padding830// x= shiftto==12 a dangling single x831// x to be handled together with non-padding case832// xx= shiftto==6&&sp==sl missing last =833// xx=y shiftto==6 last is not =834if (shiftto == 6 && (sp == sl || src[sp++] != '=') ||835shiftto == 18) {836throw new IllegalArgumentException(837"Input byte array has wrong 4-byte ending unit");838}839break;840}841if (isMIME) // skip if for rfc2045842continue;843else844throw new IllegalArgumentException(845"Illegal base64 character " +846Integer.toString(src[sp - 1], 16));847}848bits |= (b << shiftto);849shiftto -= 6;850if (shiftto < 0) {851dst[dp++] = (byte)(bits >> 16);852dst[dp++] = (byte)(bits >> 8);853dst[dp++] = (byte)(bits);854shiftto = 18;855bits = 0;856}857}858// reached end of byte array or hit padding '=' characters.859if (shiftto == 6) {860dst[dp++] = (byte)(bits >> 16);861} else if (shiftto == 0) {862dst[dp++] = (byte)(bits >> 16);863dst[dp++] = (byte)(bits >> 8);864} else if (shiftto == 12) {865// dangling single "x", incorrectly encoded.866throw new IllegalArgumentException(867"Last unit does not have enough valid bits");868}869// anything left is invalid, if is not MIME.870// if MIME, ignore all non-base64 character871while (sp < sl) {872if (isMIME && base64[src[sp++] & 0xff] < 0)873continue;874throw new IllegalArgumentException(875"Input byte array has incorrect ending byte at " + sp);876}877return dp;878}879}880881/*882* An output stream for encoding bytes into the Base64.883*/884private static class EncOutputStream extends FilterOutputStream {885886private int leftover = 0;887private int b0, b1, b2;888private boolean closed = false;889890private final char[] base64; // byte->base64 mapping891private final byte[] newline; // line separator, if needed892private final int linemax;893private final boolean doPadding;// whether or not to pad894private int linepos = 0;895private byte[] buf;896897EncOutputStream(OutputStream os, char[] base64,898byte[] newline, int linemax, boolean doPadding) {899super(os);900this.base64 = base64;901this.newline = newline;902this.linemax = linemax;903this.doPadding = doPadding;904this.buf = new byte[linemax <= 0 ? 8124 : linemax];905}906907@Override908public void write(int b) throws IOException {909byte[] buf = new byte[1];910buf[0] = (byte)(b & 0xff);911write(buf, 0, 1);912}913914private void checkNewline() throws IOException {915if (linepos == linemax) {916out.write(newline);917linepos = 0;918}919}920921private void writeb4(char b1, char b2, char b3, char b4) throws IOException {922buf[0] = (byte)b1;923buf[1] = (byte)b2;924buf[2] = (byte)b3;925buf[3] = (byte)b4;926out.write(buf, 0, 4);927}928929@Override930public void write(byte[] b, int off, int len) throws IOException {931if (closed)932throw new IOException("Stream is closed");933if (off < 0 || len < 0 || len > b.length - off)934throw new ArrayIndexOutOfBoundsException();935if (len == 0)936return;937if (leftover != 0) {938if (leftover == 1) {939b1 = b[off++] & 0xff;940len--;941if (len == 0) {942leftover++;943return;944}945}946b2 = b[off++] & 0xff;947len--;948checkNewline();949writeb4(base64[b0 >> 2],950base64[(b0 << 4) & 0x3f | (b1 >> 4)],951base64[(b1 << 2) & 0x3f | (b2 >> 6)],952base64[b2 & 0x3f]);953linepos += 4;954}955int nBits24 = len / 3;956leftover = len - (nBits24 * 3);957958while (nBits24 > 0) {959checkNewline();960int dl = linemax <= 0 ? buf.length : buf.length - linepos;961int sl = off + Math.min(nBits24, dl / 4) * 3;962int dp = 0;963for (int sp = off; sp < sl; ) {964int bits = (b[sp++] & 0xff) << 16 |965(b[sp++] & 0xff) << 8 |966(b[sp++] & 0xff);967buf[dp++] = (byte)base64[(bits >>> 18) & 0x3f];968buf[dp++] = (byte)base64[(bits >>> 12) & 0x3f];969buf[dp++] = (byte)base64[(bits >>> 6) & 0x3f];970buf[dp++] = (byte)base64[bits & 0x3f];971}972out.write(buf, 0, dp);973off = sl;974linepos += dp;975nBits24 -= dp / 4;976}977if (leftover == 1) {978b0 = b[off++] & 0xff;979} else if (leftover == 2) {980b0 = b[off++] & 0xff;981b1 = b[off++] & 0xff;982}983}984985@Override986public void close() throws IOException {987if (!closed) {988closed = true;989if (leftover == 1) {990checkNewline();991out.write(base64[b0 >> 2]);992out.write(base64[(b0 << 4) & 0x3f]);993if (doPadding) {994out.write('=');995out.write('=');996}997} else if (leftover == 2) {998checkNewline();999out.write(base64[b0 >> 2]);1000out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]);1001out.write(base64[(b1 << 2) & 0x3f]);1002if (doPadding) {1003out.write('=');1004}1005}1006leftover = 0;1007out.close();1008}1009}1010}10111012/*1013* An input stream for decoding Base64 bytes1014*/1015private static class DecInputStream extends InputStream {10161017private final InputStream is;1018private final boolean isMIME;1019private final int[] base64; // base64 -> byte mapping1020private int bits = 0; // 24-bit buffer for decoding10211022/* writing bit pos inside bits; one of 24 (left, msb), 18, 12, 6, 0 */1023private int wpos = 0;10241025/* reading bit pos inside bits: one of 24 (left, msb), 16, 8, 0 */1026private int rpos = 0;10271028private boolean eof = false;1029private boolean closed = false;10301031DecInputStream(InputStream is, int[] base64, boolean isMIME) {1032this.is = is;1033this.base64 = base64;1034this.isMIME = isMIME;1035}10361037private byte[] sbBuf = new byte[1];10381039@Override1040public int read() throws IOException {1041return read(sbBuf, 0, 1) == -1 ? -1 : sbBuf[0] & 0xff;1042}10431044private int leftovers(byte[] b, int off, int pos, int limit) {1045eof = true;10461047/*1048* We use a loop here, as this method is executed only a few times.1049* Unrolling the loop would probably not contribute much here.1050*/1051while (rpos - 8 >= wpos && pos != limit) {1052rpos -= 8;1053b[pos++] = (byte) (bits >> rpos);1054}1055return pos - off != 0 || rpos - 8 >= wpos ? pos - off : -1;1056}10571058private int eof(byte[] b, int off, int pos, int limit) throws IOException {1059/*1060* pos != limit1061*1062* wpos == 18: x dangling single x, invalid unit1063* accept ending xx or xxx without padding characters1064*/1065if (wpos == 18) {1066throw new IOException("Base64 stream has one un-decoded dangling byte.");1067}1068rpos = 24;1069return leftovers(b, off, pos, limit);1070}10711072private int padding(byte[] b, int off, int pos, int limit) throws IOException {1073/*1074* pos != limit1075*1076* wpos == 24: = (unnecessary padding)1077* wpos == 18: x= (dangling single x, invalid unit)1078* wpos == 12 and missing last '=': xx= (invalid padding)1079* wpos == 12 and last is not '=': xx=x (invalid padding)1080*/1081if (wpos >= 18 || wpos == 12 && is.read() != '=') {1082throw new IOException("Illegal base64 ending sequence:" + wpos);1083}1084rpos = 24;1085return leftovers(b, off, pos, limit);1086}10871088@Override1089public int read(byte[] b, int off, int len) throws IOException {1090if (closed) {1091throw new IOException("Stream is closed");1092}1093Objects.checkFromIndexSize(off, len, b.length);1094if (len == 0) {1095return 0;1096}10971098/*1099* Rather than keeping 2 running vars (e.g., off and len),1100* we only keep one (pos), while definitely fixing the boundaries1101* of the range [off, limit).1102* More specifically, each use of pos as an index in b meets1103* pos - off >= 0 & limit - pos > 01104*1105* Note that limit can overflow to Integer.MIN_VALUE. However,1106* as long as comparisons with pos are as coded, there's no harm.1107*/1108int pos = off;1109final int limit = off + len;1110if (eof) {1111return leftovers(b, off, pos, limit);1112}11131114/*1115* Leftovers from previous invocation; here, wpos = 0.1116* There can be at most 2 leftover bytes (rpos <= 16).1117* Further, b has at least one free place.1118*1119* The logic could be coded as a loop, (as in method leftovers())1120* but the explicit "unrolling" makes it possible to generate1121* better byte extraction code.1122*/1123if (rpos == 16) {1124b[pos++] = (byte) (bits >> 8);1125rpos = 8;1126if (pos == limit) {1127return len;1128}1129}1130if (rpos == 8) {1131b[pos++] = (byte) bits;1132rpos = 0;1133if (pos == limit) {1134return len;1135}1136}11371138bits = 0;1139wpos = 24;1140for (;;) {1141/* pos != limit & rpos == 0 */1142final int i = is.read();1143if (i < 0) {1144return eof(b, off, pos, limit);1145}1146final int v = base64[i];1147if (v < 0) {1148/*1149* i not in alphabet, thus1150* v == -2: i is '=', the padding1151* v == -1: i is something else, typically CR or LF1152*/1153if (v == -1) {1154if (isMIME) {1155continue;1156}1157throw new IOException("Illegal base64 character 0x" +1158Integer.toHexString(i));1159}1160return padding(b, off, pos, limit);1161}1162wpos -= 6;1163bits |= v << wpos;1164if (wpos != 0) {1165continue;1166}1167if (limit - pos >= 3) {1168/* frequently taken fast path, no need to track rpos */1169b[pos++] = (byte) (bits >> 16);1170b[pos++] = (byte) (bits >> 8);1171b[pos++] = (byte) bits;1172bits = 0;1173wpos = 24;1174if (pos == limit) {1175return len;1176}1177continue;1178}11791180/* b has either 1 or 2 free places */1181b[pos++] = (byte) (bits >> 16);1182if (pos == limit) {1183rpos = 16;1184return len;1185}1186b[pos++] = (byte) (bits >> 8);1187/* pos == limit, no need for an if */1188rpos = 8;1189return len;1190}1191}11921193@Override1194public int available() throws IOException {1195if (closed)1196throw new IOException("Stream is closed");1197return is.available(); // TBD:1198}11991200@Override1201public void close() throws IOException {1202if (!closed) {1203closed = true;1204is.close();1205}1206}1207}1208}120912101211