001/*
002 * Copyright 2015-2020 the original author or authors
003 *
004 * This software is licensed under the Apache License, Version 2.0,
005 * the GNU Lesser General Public License version 2 or later ("LGPL")
006 * and the WTFPL.
007 * You may choose either license to govern your use of this software only
008 * upon the condition that you accept all of the terms of either
009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
010 */
011package org.minidns.util;
012
013/**
014 * Very minimal Base64 encoder.
015 */
016public final class Base64 {
017    private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
018    private static final String PADDING = "==";
019
020    /**
021     * Do not allow to instantiate Base64
022     */
023    private Base64() {
024    }
025
026    public static String encodeToString(byte[] bytes) {
027        int paddingCount = (3 - (bytes.length % 3)) % 3;
028        byte[] padded = new byte[bytes.length + paddingCount];
029        System.arraycopy(bytes, 0, padded, 0, bytes.length);
030        StringBuilder sb = new StringBuilder();
031        for (int i = 0; i < bytes.length; i += 3) {
032            int j = ((padded[i] & 0xff) << 16) + ((padded[i + 1] & 0xff) << 8) + (padded[i + 2] & 0xff);
033            sb.append(ALPHABET.charAt((j >> 18) & 0x3f)).append(ALPHABET.charAt((j >> 12) & 0x3f))
034                    .append(ALPHABET.charAt((j >> 6) & 0x3f)).append(ALPHABET.charAt(j & 0x3f));
035        }
036        return sb.substring(0, sb.length() - paddingCount) + PADDING.substring(0, paddingCount);
037    }
038}