|
| 1 | +package com.auth0.util; |
| 2 | + |
| 3 | +import java.io.UnsupportedEncodingException; |
| 4 | +import java.nio.charset.Charset; |
| 5 | + |
| 6 | +public class Base64 { |
| 7 | + |
| 8 | + private static final byte[] ENCODE_MAP = new byte[] { |
| 9 | + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', |
| 10 | + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', |
| 11 | + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', |
| 12 | + '5', '6', '7', '8', '9', '-', '_' |
| 13 | + }; |
| 14 | + |
| 15 | + public static String encodeUrlSafe(String string) { |
| 16 | + byte[] in = string.getBytes(Charset.defaultCharset()); |
| 17 | + int length = (in.length + 2) * 4 / 3; |
| 18 | + byte[] out = new byte[length]; |
| 19 | + int index = 0, end = in.length - in.length % 3; |
| 20 | + for (int i = 0; i < end; i += 3) { |
| 21 | + out[index++] = ENCODE_MAP[(in[i] & 0xff) >> 2]; |
| 22 | + out[index++] = ENCODE_MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)]; |
| 23 | + out[index++] = ENCODE_MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)]; |
| 24 | + out[index++] = ENCODE_MAP[(in[i + 2] & 0x3f)]; |
| 25 | + } |
| 26 | + switch (in.length % 3) { |
| 27 | + case 1: |
| 28 | + out[index++] = ENCODE_MAP[(in[end] & 0xff) >> 2]; |
| 29 | + out[index++] = ENCODE_MAP[(in[end] & 0x03) << 4]; |
| 30 | + out[index++] = '='; |
| 31 | + out[index++] = '='; |
| 32 | + break; |
| 33 | + case 2: |
| 34 | + out[index++] = ENCODE_MAP[(in[end] & 0xff) >> 2]; |
| 35 | + out[index++] = ENCODE_MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)]; |
| 36 | + out[index++] = ENCODE_MAP[((in[end + 1] & 0x0f) << 2)]; |
| 37 | + out[index++] = '='; |
| 38 | + break; |
| 39 | + } |
| 40 | + try { |
| 41 | + return new String(out, 0, index, "US-ASCII"); |
| 42 | + } catch (UnsupportedEncodingException e) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments