| 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. |