net.sourceforge.jencrypt.lib.Utils.java Source code

Java tutorial

Introduction

Here is the source code for net.sourceforge.jencrypt.lib.Utils.java

Source

/*******************************************************************************
 * Copyright (c) 2013 "Ivo van Kamp"
 *
 * jEncrypt is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
package net.sourceforge.jencrypt.lib;

import static java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.GROUP_READ;
import static java.nio.file.attribute.PosixFilePermission.GROUP_WRITE;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_READ;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_WRITE;
import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
import gnu.crypto.hash.IMessageDigest;
import gnu.crypto.hash.RipeMD128;
import gnu.crypto.hash.Tiger;

import java.io.*;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;

public class Utils {

    /**
     * The Unix separator character.
     */
    public static final char UNIX_SEPARATOR = '/';

    public static byte[] hashAESKey(String stringToHash, final short keySize) {
        if (stringToHash == null) {
            throw new IllegalArgumentException("Error in call to hashAESKey(): No string specified");
        }
        return hashAESKey(stringToHash.getBytes(), keySize);
    }

    public static byte[] hashAESKey(byte[] bytesToHash, final short keySize) {

        byte[] bytesToHashCopy = Arrays.copyOf(bytesToHash, bytesToHash.length);

        switch (keySize) {
        case 128:
            // GNU crypto library hash function implementation of RipeMD128
            IMessageDigest ripeMD128 = new RipeMD128();
            ripeMD128.update(bytesToHashCopy, 0, bytesToHashCopy.length);
            return ripeMD128.digest();
        case 192:
            // GNU crypto library hash function implementation of Tiger
            IMessageDigest tiger = new Tiger();
            tiger.update(bytesToHashCopy, 0, bytesToHashCopy.length);
            return tiger.digest();
        case 256:
            // Apache Commons Codec lib SHA-256
            bytesToHashCopy = DigestUtils.sha256(bytesToHashCopy);
            return bytesToHashCopy;
        default:
            throw new IllegalArgumentException("Key size unkown");
        }
    }

    public static String humanReadableByteCount(long bytes) {
        int unit = 1024;
        if (bytes < unit)
            return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = "kMGTPE".charAt(exp - 1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

    public static int byteArrayToInt(byte[] b) {
        return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24;
    }

    public static long byteArrayToLong(byte[] b) {
        return (long) (b[7] & 0xFF) | (long) (b[6] & 0xFF) << 8 | (long) (b[5] & 0xFF) << 16
                | (long) (b[4] & 0xFF) << 24 | (long) (b[3] & 0xFF) << 32 | (long) (b[2] & 0xFF) << 40
                | (long) (b[1] & 0xFF) << 48 | (long) (b[0] & 0xFF) << 56;
    }

    /**
     * Encode Set of PosixFilePermission objects as two bytes.
     * 
     * @param b
     * @return
     */
    public static Set<PosixFilePermission> byteToPerms(byte[] b) {

        Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class);
        // @formatter:off      
        if ((b[0] & 1) != 0)
            result.add(OWNER_READ);
        if ((b[0] & 2) != 0)
            result.add(OWNER_WRITE);
        if ((b[0] & 4) != 0)
            result.add(OWNER_EXECUTE);

        if ((b[0] & 8) != 0)
            result.add(GROUP_READ);
        if ((b[0] & 16) != 0)
            result.add(GROUP_WRITE);
        if ((b[0] & 32) != 0)
            result.add(GROUP_EXECUTE);

        if ((b[0] & 64) != 0)
            result.add(OTHERS_READ);
        if ((b[0] & 128) != 0)
            result.add(OTHERS_WRITE);
        if ((b[1] & 1) != 0)
            result.add(OTHERS_EXECUTE);
        // @formatter:on

        return result;
    }

    /**
     * Decode two bytes to Set of PosixFilePermission objects.
     * 
     * @param perms
     * @return
     */
    public static byte[] permsToByte(Set<PosixFilePermission> perms) {

        int b1 = 0, b2 = 0;
        // @formatter:off
        if (perms.contains(OWNER_READ))
            b1 = (b1 | 1);
        if (perms.contains(OWNER_WRITE))
            b1 = (b1 | 2);
        if (perms.contains(OWNER_EXECUTE))
            b1 = (b1 | 4);

        if (perms.contains(GROUP_READ))
            b1 = (b1 | 8);
        if (perms.contains(GROUP_WRITE))
            b1 = (b1 | 16);
        if (perms.contains(GROUP_EXECUTE))
            b1 = (b1 | 32);

        if (perms.contains(OTHERS_READ))
            b1 = (b1 | 64);
        if (perms.contains(OTHERS_WRITE))
            b1 = (b1 | 128);
        if (perms.contains(OTHERS_EXECUTE))
            b2 = (b2 | 1);
        // @formatter:on

        return new byte[] { (byte) b1, (byte) b2 };
    }

    /**
     * Return the contents of a file as a byte array.
     * 
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] getBytesFromFile(File file) throws IOException {

        if (file.length() > Integer.MAX_VALUE) {
            // File is too large
            throw new IOException("File '" + file.getName() + "' is bigger than Integer.MAX_VALUE (>2GB)");
        }
        InputStream in = new FileInputStream(file);

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) file.length()];

        int len = 0;

        // Reads bytes from the input stream and store them in buffer bytes
        len = in.read(bytes);

        // Ensure all the bytes have been read in
        if (len != bytes.length) {
            in.close();
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        in.close();
        return bytes;
    }

    // Unconditionally close an OutputStream.
    // Source: org.apache.commons.io.IOUtils
    public static void closeQuietly(OutputStream output) {
        try {
            if (output != null) {
                output.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    // Unconditionally close an InputStream.
    // Source: org.apache.commons.io.IOUtils
    public static void closeQuietly(InputStream input) {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }
}