Debian Codegraph @

minidns-core/src/main/java/org/minidns/util/Base32.java

raw
1 /*
2 * Copyright 2015-2020 the original author or authors
3 *
4 * This software is licensed under the Apache License, Version 2.0,
5 * the GNU Lesser General Public License version 2 or later ("LGPL")
6 * and the WTFPL.
7 * You may choose either license to govern your use of this software only
8 * upon the condition that you accept all of the terms of either
9 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
10 */
11 package org.minidns.util;
12
13 /**
14 * Very minimal Base32 encoder.
15 */
16 public final class Base32 {
17 private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
18 private static final String PADDING = "======";
19
20 /**
21 * Do not allow to instantiate Base32
22 */
23 private Base32() {
24 }
25
26 public static String encodeToString(byte[] bytes) {
27 int paddingCount = (int) (8 - (bytes.length % 5) * 1.6) % 8;
28 byte[] padded = new byte[bytes.length + paddingCount];
29 System.arraycopy(bytes, 0, padded, 0, bytes.length);
30 StringBuilder sb = new StringBuilder();
31 for (int i = 0; i < bytes.length; i += 5) {
32 long j = ((long) (padded[i] & 0xff) << 32) + ((long) (padded[i + 1] & 0xff) << 24)
33 + ((padded[i + 2] & 0xff) << 16) + ((padded[i + 3] & 0xff) << 8) + (padded[i + 4] & 0xff);
34 sb.append(ALPHABET.charAt((int) ((j >> 35) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 30) & 0x1f)))
35 .append(ALPHABET.charAt((int) ((j >> 25) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 20) & 0x1f)))
36 .append(ALPHABET.charAt((int) ((j >> 15) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 10) & 0x1f)))
37 .append(ALPHABET.charAt((int) ((j >> 5) & 0x1f))).append(ALPHABET.charAt((int) (j & 0x1f)));
38 }
39 return sb.substring(0, sb.length() - paddingCount) + PADDING.substring(0, paddingCount);
40 }
41 }