1 18 19 package jcifs.util; 20 21 public class Base64 { 22 23 private static final String ALPHABET = 24 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 25 26 33 public static String encode(byte[] bytes) { 34 int length = bytes.length; 35 if (length == 0) return ""; 36 StringBuffer buffer = 37 new StringBuffer ((int) Math.ceil((double) length / 3d) * 4); 38 int remainder = length % 3; 39 length -= remainder; 40 int block; 41 int i = 0; 42 while (i < length) { 43 block = ((bytes[i++] & 0xff) << 16) | ((bytes[i++] & 0xff) << 8) | 44 (bytes[i++] & 0xff); 45 buffer.append(ALPHABET.charAt(block >>> 18)); 46 buffer.append(ALPHABET.charAt((block >>> 12) & 0x3f)); 47 buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f)); 48 buffer.append(ALPHABET.charAt(block & 0x3f)); 49 } 50 if (remainder == 0) return buffer.toString(); 51 if (remainder == 1) { 52 block = (bytes[i] & 0xff) << 4; 53 buffer.append(ALPHABET.charAt(block >>> 6)); 54 buffer.append(ALPHABET.charAt(block & 0x3f)); 55 buffer.append("=="); 56 return buffer.toString(); 57 } 58 block = (((bytes[i++] & 0xff) << 8) | ((bytes[i]) & 0xff)) << 2; 59 buffer.append(ALPHABET.charAt(block >>> 12)); 60 buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f)); 61 buffer.append(ALPHABET.charAt(block & 0x3f)); 62 buffer.append("="); 63 return buffer.toString(); 64 } 65 66 72 public static byte[] decode(String string) { 73 int length = string.length(); 74 if (length == 0) return new byte[0]; 75 int pad = (string.charAt(length - 2) == '=') ? 2 : 76 (string.charAt(length - 1) == '=') ? 1 : 0; 77 int size = length * 3 / 4 - pad; 78 byte[] buffer = new byte[size]; 79 int block; 80 int i = 0; 81 int index = 0; 82 while (i < length) { 83 block = (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 18 | 84 (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 12 | 85 (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 6 | 86 (ALPHABET.indexOf(string.charAt(i++)) & 0xff); 87 buffer[index++] = (byte) (block >>> 16); 88 if (index < size) buffer[index++] = (byte) ((block >>> 8) & 0xff); 89 if (index < size) buffer[index++] = (byte) (block & 0xff); 90 } 91 return buffer; 92 } 93 94 } 95 | Popular Tags |