| 33 | /// String enc = Base32.encode(secret); |
| 34 | /// ``` |
| 35 | public final class Base32 { |
| 36 | private Base32() {} |
| 37 | |
| 38 | private static final char[] ALPHABET = |
| 39 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray(); |
| 40 | private static final int[] DECODE = new int[128]; |
| 41 | static { |
| 42 | for (int i = 0; i < DECODE.length; i++) { |
| 43 | DECODE[i] = -1; |
| 44 | } |
| 45 | for (int i = 0; i < ALPHABET.length; i++) { |
| 46 | DECODE[ALPHABET[i]] = i; |
| 47 | } |
| 48 | // common lowercase variant |
| 49 | for (int i = 0; i < ALPHABET.length; i++) { |
| 50 | char lc = (char) (ALPHABET[i] | 0x20); |
| 51 | if (lc != ALPHABET[i]) { |
| 52 | DECODE[lc] = i; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// Encodes the bytes as a Base32 string (uppercase, with `=` padding). |
| 58 | public static String encode(byte[] data) { |
| 59 | if (data == null || data.length == 0) { |
| 60 | return ""; |
| 61 | } |
| 62 | int output = ((data.length + 4) / 5) * 8; |
| 63 | StringBuilder b = new StringBuilder(output); |
| 64 | int bits = 0; |
| 65 | int value = 0; |
| 66 | for (byte aData : data) { |
| 67 | value = (value << 8) | (aData & 0xff); |
| 68 | bits += 8; |
| 69 | while (bits >= 5) { |
| 70 | b.append(ALPHABET[(value >>> (bits - 5)) & 0x1f]); |
| 71 | bits -= 5; |
| 72 | } |
| 73 | } |
| 74 | if (bits > 0) { |
| 75 | b.append(ALPHABET[(value << (5 - bits)) & 0x1f]); |
| 76 | } |
| 77 | while (b.length() < output) { |
| 78 | b.append('='); |
| 79 | } |
| 80 | return b.toString(); |
| 81 | } |
| 82 | |
| 83 | /// Decodes a Base32 string. Padding and whitespace are tolerated; mixed |
| 84 | /// case is accepted. |
| 85 | public static byte[] decode(String s) { |
| 86 | if (s == null) { |
| 87 | return new byte[0]; |
| 88 | } |
| 89 | // strip padding and whitespace |
| 90 | StringBuilder cleaned = new StringBuilder(s.length()); |
| 91 | for (int i = 0; i < s.length(); i++) { |
| 92 | char c = s.charAt(i); |
nothing calls this directly
no test coverage detected