| 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 Base64 encoder. |
| 15 |
*/ |
| 16 |
public final class Base64 { |
| 17 |
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 18 |
private static final String PADDING = "=="; |
| 19 |
|
| 20 |
/** |
| 21 |
* Do not allow to instantiate Base64 |
| 22 |
*/ |
| 23 |
private Base64() { |
| 24 |
} |
| 25 |
|
| 26 |
public static String encodeToString(byte[] bytes) { |
| 27 |
int paddingCount = (3 - (bytes.length % 3)) % 3; |
| 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 += 3) { |
| 32 |
int j = ((padded[i] & 0xff) << 16) + ((padded[i + 1] & 0xff) << 8) + (padded[i + 2] & 0xff); |
| 33 |
sb.append(ALPHABET.charAt((j >> 18) & 0x3f)).append(ALPHABET.charAt((j >> 12) & 0x3f)) |
| 34 |
.append(ALPHABET.charAt((j >> 6) & 0x3f)).append(ALPHABET.charAt(j & 0x3f)); |
| 35 |
} |
| 36 |
return sb.substring(0, sb.length() - paddingCount) + PADDING.substring(0, paddingCount); |
| 37 |
} |
| 38 |
} |