001/*
002 *    Copyright 2024-2025, Warm-Flow (290631660@qq.com).
003 *
004 *    Licensed under the Apache License, Version 2.0 (the "License");
005 *    you may not use this file except in compliance with the License.
006 *    You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 *    Unless required by applicable law or agreed to in writing, software
011 *    distributed under the License is distributed on an "AS IS" BASIS,
012 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *    See the License for the specific language governing permissions and
014 *    limitations under the License.
015 */
016package org.dromara.warm.flow.core.utils;
017
018/**
019 * Base64工具类
020 *
021 * @author hh
022 */
023public final class Base64 {
024    static private final int BASELENGTH = 128;
025    static private final int LOOKUPLENGTH = 64;
026    static private final int TWENTYFOURBITGROUP = 24;
027    static private final int EIGHTBIT = 8;
028    static private final int SIXTEENBIT = 16;
029    static private final int FOURBYTE = 4;
030    static private final int SIGN = -128;
031    static private final char PAD = '=';
032    static final private byte[] base64Alphabet = new byte[BASELENGTH];
033    static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
034
035    static {
036        for (int i = 0; i < BASELENGTH; ++i) {
037            base64Alphabet[i] = -1;
038        }
039        for (int i = 'Z'; i >= 'A'; i--) {
040            base64Alphabet[i] = (byte) (i - 'A');
041        }
042        for (int i = 'z'; i >= 'a'; i--) {
043            base64Alphabet[i] = (byte) (i - 'a' + 26);
044        }
045
046        for (int i = '9'; i >= '0'; i--) {
047            base64Alphabet[i] = (byte) (i - '0' + 52);
048        }
049
050        base64Alphabet['+'] = 62;
051        base64Alphabet['/'] = 63;
052
053        for (int i = 0; i <= 25; i++) {
054            lookUpBase64Alphabet[i] = (char) ('A' + i);
055        }
056
057        for (int i = 26, j = 0; i <= 51; i++, j++) {
058            lookUpBase64Alphabet[i] = (char) ('a' + j);
059        }
060
061        for (int i = 52, j = 0; i <= 61; i++, j++) {
062            lookUpBase64Alphabet[i] = (char) ('0' + j);
063        }
064        lookUpBase64Alphabet[62] = (char) '+';
065        lookUpBase64Alphabet[63] = (char) '/';
066    }
067
068    private static boolean isWhiteSpace(char octect) {
069        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
070    }
071
072    private static boolean isPad(char octect) {
073        return (octect == PAD);
074    }
075
076    private static boolean isData(char octect) {
077        return (octect < BASELENGTH && base64Alphabet[octect] != -1);
078    }
079
080    /**
081     * Encodes hex octects into Base64
082     *
083     * @param binaryData Array containing binaryData
084     * @return Encoded Base64 array
085     */
086    public static String encode(byte[] binaryData) {
087        if (binaryData == null) {
088            return null;
089        }
090
091        int lengthDataBits = binaryData.length * EIGHTBIT;
092        if (lengthDataBits == 0) {
093            return "";
094        }
095
096        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
097        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
098        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
099        char encodedData[] = null;
100
101        encodedData = new char[numberQuartet * 4];
102
103        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
104
105        int encodedIndex = 0;
106        int dataIndex = 0;
107
108        for (int i = 0; i < numberTriplets; i++) {
109            b1 = binaryData[dataIndex++];
110            b2 = binaryData[dataIndex++];
111            b3 = binaryData[dataIndex++];
112
113            l = (byte) (b2 & 0x0f);
114            k = (byte) (b1 & 0x03);
115
116            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
117            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
118            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
119
120            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
121            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
122            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
123            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
124        }
125
126        // form integral number of 6-bit groups
127        if (fewerThan24bits == EIGHTBIT) {
128            b1 = binaryData[dataIndex];
129            k = (byte) (b1 & 0x03);
130            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
131            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
132            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
133            encodedData[encodedIndex++] = PAD;
134            encodedData[encodedIndex++] = PAD;
135        } else if (fewerThan24bits == SIXTEENBIT) {
136            b1 = binaryData[dataIndex];
137            b2 = binaryData[dataIndex + 1];
138            l = (byte) (b2 & 0x0f);
139            k = (byte) (b1 & 0x03);
140
141            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
142            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
143
144            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
145            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
146            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
147            encodedData[encodedIndex++] = PAD;
148        }
149        return new String(encodedData);
150    }
151
152    /**
153     * Decodes Base64 data into octects
154     *
155     * @param encoded string containing Base64 data
156     * @return Array containind decoded data.
157     */
158    public static byte[] decode(String encoded) {
159        if (encoded == null) {
160            return null;
161        }
162
163        char[] base64Data = encoded.toCharArray();
164        // remove white spaces
165        int len = removeWhiteSpace(base64Data);
166
167        if (len % FOURBYTE != 0) {
168            return null;// should be divisible by four
169        }
170
171        int numberQuadruple = (len / FOURBYTE);
172
173        if (numberQuadruple == 0) {
174            return new byte[0];
175        }
176
177        byte decodedData[] = null;
178        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
179        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
180
181        int i = 0;
182        int encodedIndex = 0;
183        int dataIndex = 0;
184        decodedData = new byte[(numberQuadruple) * 3];
185
186        for (; i < numberQuadruple - 1; i++) {
187
188            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
189                    || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
190                return null;
191            } // if found "no data" just return null
192
193            b1 = base64Alphabet[d1];
194            b2 = base64Alphabet[d2];
195            b3 = base64Alphabet[d3];
196            b4 = base64Alphabet[d4];
197
198            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
199            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
200            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
201        }
202
203        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
204            return null;// if found "no data" just return null
205        }
206
207        b1 = base64Alphabet[d1];
208        b2 = base64Alphabet[d2];
209
210        d3 = base64Data[dataIndex++];
211        d4 = base64Data[dataIndex++];
212        if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
213            if (isPad(d3) && isPad(d4)) {
214                if ((b2 & 0xf) != 0)// last 4 bits should be zero
215                {
216                    return null;
217                }
218                byte[] tmp = new byte[i * 3 + 1];
219                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
220                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
221                return tmp;
222            } else if (!isPad(d3) && isPad(d4)) {
223                b3 = base64Alphabet[d3];
224                if ((b3 & 0x3) != 0)// last 2 bits should be zero
225                {
226                    return null;
227                }
228                byte[] tmp = new byte[i * 3 + 2];
229                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
230                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
231                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
232                return tmp;
233            } else {
234                return null;
235            }
236        } else { // No PAD e.g 3cQl
237            b3 = base64Alphabet[d3];
238            b4 = base64Alphabet[d4];
239            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
240            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
241            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
242
243        }
244        return decodedData;
245    }
246
247    /**
248     * remove WhiteSpace from MIME containing encoded Base64 data.
249     *
250     * @param data the byte array of base64 data (with WS)
251     * @return the new length
252     */
253    private static int removeWhiteSpace(char[] data) {
254        if (data == null) {
255            return 0;
256        }
257
258        // count characters that's not whitespace
259        int newSize = 0;
260        int len = data.length;
261        for (int i = 0; i < len; i++) {
262            if (!isWhiteSpace(data[i])) {
263                data[newSize++] = data[i];
264            }
265        }
266        return newSize;
267    }
268}