001/*
002 * Copyright 2015-2024 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 Base32 encoder.
015 */
016public final class Base32 {
017    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
018    private static final String PADDING = "======";
019
020    /**
021     * Do not allow to instantiate Base32
022     */
023    private Base32() {
024    }
025
026    public static String encodeToString(byte[] bytes) {
027        int paddingCount = (int) (8 - (bytes.length % 5) * 1.6) % 8;
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 += 5) {
032            long j = ((long) (padded[i] & 0xff) << 32) + ((long) (padded[i + 1] & 0xff) << 24)
033                    + ((padded[i + 2] & 0xff) << 16) + ((padded[i + 3] & 0xff) << 8) + (padded[i + 4] & 0xff);
034            sb.append(ALPHABET.charAt((int) ((j >> 35) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 30) & 0x1f)))
035                    .append(ALPHABET.charAt((int) ((j >> 25) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 20) & 0x1f)))
036                    .append(ALPHABET.charAt((int) ((j >> 15) & 0x1f))).append(ALPHABET.charAt((int) ((j >> 10) & 0x1f)))
037                    .append(ALPHABET.charAt((int) ((j >> 5) & 0x1f))).append(ALPHABET.charAt((int) (j & 0x1f)));
038        }
039        return sb.substring(0, sb.length() - paddingCount) + PADDING.substring(0, paddingCount);
040    }
041}