11package com .mailjet .client ;
22
33
4- public class Base64 {
5-
6- private final static char [] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray ();
4+ import static java .nio .charset .StandardCharsets .UTF_8 ;
75
8- private static int [] toInt = new int [128 ];
9-
10- static {
11- for (int i =0 ; i < ALPHABET .length ; i ++){
12- toInt [ALPHABET [i ]]= i ;
13- }
14- }
6+ public class Base64 {
157
168 /**
179 * Translates the specified byte array into Base64 string.
@@ -20,26 +12,7 @@ public class Base64 {
2012 * @return the translated Base64 string (not null)
2113 */
2214 public static String encode (byte [] buf ){
23- int size = buf .length ;
24- char [] ar = new char [((size + 2 ) / 3 ) * 4 ];
25- int a = 0 ;
26- int i =0 ;
27- while (i < size ){
28- byte b0 = buf [i ++];
29- byte b1 = (i < size ) ? buf [i ++] : 0 ;
30- byte b2 = (i < size ) ? buf [i ++] : 0 ;
31-
32- int mask = 0x3F ;
33- ar [a ++] = ALPHABET [(b0 >> 2 ) & mask ];
34- ar [a ++] = ALPHABET [((b0 << 4 ) | ((b1 & 0xFF ) >> 4 )) & mask ];
35- ar [a ++] = ALPHABET [((b1 << 2 ) | ((b2 & 0xFF ) >> 6 )) & mask ];
36- ar [a ++] = ALPHABET [b2 & mask ];
37- }
38- switch (size % 3 ){
39- case 1 : ar [--a ] = '=' ;
40- case 2 : ar [--a ] = '=' ;
41- }
42- return new String (ar );
15+ return new String (java .util .Base64 .getEncoder ().encode (buf ), UTF_8 );
4316 }
4417
4518 /**
@@ -49,26 +22,7 @@ public static String encode(byte[] buf){
4922 * @return the byte array (not null)
5023 */
5124 public static byte [] decode (String s ){
52- int delta = s .endsWith ( "==" ) ? 2 : s .endsWith ( "=" ) ? 1 : 0 ;
53- byte [] buffer = new byte [s .length ()*3 /4 - delta ];
54- int mask = 0xFF ;
55- int index = 0 ;
56- for (int i =0 ; i < s .length (); i +=4 ){
57- int c0 = toInt [s .charAt ( i )];
58- int c1 = toInt [s .charAt ( i + 1 )];
59- buffer [index ++]= (byte )(((c0 << 2 ) | (c1 >> 4 )) & mask );
60- if (index >= buffer .length ){
61- return buffer ;
62- }
63- int c2 = toInt [s .charAt ( i + 2 )];
64- buffer [index ++]= (byte )(((c1 << 4 ) | (c2 >> 2 )) & mask );
65- if (index >= buffer .length ){
66- return buffer ;
67- }
68- int c3 = toInt [s .charAt ( i + 3 )];
69- buffer [index ++]= (byte )(((c2 << 6 ) | c3 ) & mask );
70- }
71- return buffer ;
72- }
25+ return java .util .Base64 .getDecoder ().decode (s );
26+ }
7327
74- }
28+ }
0 commit comments