001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.codec.digest;
018
019import java.util.Random;
020
021/**
022 * Base64 like method to convert binary bytes into ASCII chars.
023 *
024 * TODO: Can Base64 be reused?
025 *
026 * <p>
027 * This class is immutable and thread-safe.
028 * </p>
029 *
030 * @version $Id: B64.java 1435550 2013-01-19 14:09:52Z tn $
031 * @since 1.7
032 */
033class B64 {
034
035    /**
036     * Table with characters for Base64 transformation.
037     */
038    static final String B64T = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
039
040    /**
041     * Base64 like conversion of bytes to ASCII chars.
042     *
043     * @param b2
044     *            A byte from the result.
045     * @param b1
046     *            A byte from the result.
047     * @param b0
048     *            A byte from the result.
049     * @param outLen
050     *            The number of expected output chars.
051     * @param buffer
052     *            Where the output chars is appended to.
053     */
054    static void b64from24bit(final byte b2, final byte b1, final byte b0, final int outLen,
055                             final StringBuilder buffer) {
056        // The bit masking is necessary because the JVM byte type is signed!
057        int w = ((b2 << 16) & 0x00ffffff) | ((b1 << 8) & 0x00ffff) | (b0 & 0xff);
058        // It's effectively a "for" loop but kept to resemble the original C code.
059        int n = outLen;
060        while (n-- > 0) {
061            buffer.append(B64T.charAt(w & 0x3f));
062            w >>= 6;
063        }
064    }
065
066    /**
067     * Generates a string of random chars from the B64T set.
068     *
069     * @param num
070     *            Number of chars to generate.
071     */
072    static String getRandomSalt(final int num) {
073        final StringBuilder saltString = new StringBuilder();
074        for (int i = 1; i <= num; i++) {
075            saltString.append(B64T.charAt(new Random().nextInt(B64T.length())));
076        }
077        return saltString.toString();
078    }
079}