Subversion Repositories bacoAlunos

Rev

Blame | Last modification | View Log | RSS feed

package pt.estgp.es.exemplos.hibernate.utils;


import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.math.BigInteger;
import java.rmi.dgc.VMID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 *
 * @author  Jorge Machado
 */


public class BytesUtils {
    private static int counter = 0;
    private static 1.5.0/docs/api/java/util/Random.html">Random random = new 1.5.0/docs/api/java/util/Random.html">Random();
    private static 1.5.0/docs/api/java/rmi/dgc/VMID.html">VMID vmid = new 1.5.0/docs/api/java/rmi/dgc/VMID.html">VMID();
    private static 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(BytesUtils.class);

    /** Private Constructor */

    private BytesUtils () {}


    public static 1.5.0/docs/api/java/lang/String.html">String getMd5FromFile(1.5.0/docs/api/java/lang/String.html">String filepath)
    {
        return getMD5(getBytes(filepath));
    }

    public static byte[] getBytes(1.5.0/docs/api/java/lang/String.html">String fileName)
    {

        byte[] data = null;
        try{

            1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream r = new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(fileName);

            1.5.0/docs/api/java/io/File.html">File f = new 1.5.0/docs/api/java/io/File.html">File(fileName);

            //this value is never bigger than a integer
            int len =(int) f.length();

            data = new byte[len];

            int bytesRead = 0;

            bytesRead = r.read(data);

            r.close();

            if(bytesRead == -1)
                return null;


        }
        catch(1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
        {
            logger.error("Files getBytes()",e);
            return null;
        }
        catch(1.5.0/docs/api/java/io/IOException.html">IOException e)
        {
            logger.error("Files getData()",e);
            return null;
        }
        return data;
    }

    public static 1.5.0/docs/api/java/lang/String.html">String getMD5(1.5.0/docs/api/java/lang/String.html">String data)
    {
        return getMD5(data.getBytes());
    }

    public static 1.5.0/docs/api/java/lang/String.html">String getMD5(byte[] data)
    {
        return toHex(getMD5Bytes(data));
    }

    public static 1.5.0/docs/api/java/lang/String.html">String getDigestMD5Hex(1.5.0/docs/api/java/lang/String.html">String str){
        byte[] digest = getDigestMD5(str.getBytes());
        if(digest != null)
            return toHex(digest);

        return null;
    }
    public static byte[] getDigestMD5(byte[] data)
    {
        byte[] result = null;
        try{
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest md5 = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");

            md5.update(data);

            result = md5.digest();

        }
        catch(1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
        {
            //this never hapens beacause MD5 is a correct algoritm
            logger.fatal("MD5 function does not exists",e);
        }

        return result;
    }
    /*********************************************************
     *Returns true if the two digests are equal
     *
     *******************************************************/

    public static boolean isDigestEqual(byte[] b1,byte[] b2)
    {

        try{
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest md5 = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");

            return md5.isEqual(b1,b2);

        }
        catch(1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
        {
            //this never hapens beacause MD5 is a correct algoritm
            logger.fatal("MD5 function does not exists",e);
        }

        return false;

    }

    public static byte[] getMD5Bytes(byte[] data)
    {
        try
        {
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest digest = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");

            return digest.digest(data);
        }
        catch (1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
        {
            logger.fatal("MD5 function does not exists",e);
        }
        return null;
    }

    /**
     * Return a hex representation of the byte array
     *
     * @param data The data to transform.
     * @return A hex representation of the data.
     */

    public static 1.5.0/docs/api/java/lang/String.html">String toHex(byte[] data)
    {
        if ((data == null) || (data.length == 0))
            return null;

        1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer result = new 1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer();

        // This is far from the most efficient way to do things...
        for (int i = 0; i < data.length; i++)
        {
            int low =  (int) (data[i] & 0x0F);
            int high = (int) (data[i] & 0xF0);

            result.append(1.5.0/docs/api/java/lang/Integer.html">Integer.toHexString(high).substring(0, 1));
            result.append(1.5.0/docs/api/java/lang/Integer.html">Integer.toHexString(low));
        }

        return result.toString();
    }

    /**
     * Generate a unique key.
     * The key is a long (length 38 to 40) sequence of digits.
     *
     * @return A unique key as a long sequence of base-10 digits.
     */

    public static 1.5.0/docs/api/java/lang/String.html">String generateKey()
    {
        return new 1.5.0/docs/api/java/math/BigInteger.html">BigInteger(generateBytesKey()).abs().toString();
    }

    /**
     * Generate a unique key.
     * The key is a 32-character long sequence of hex digits.
     *
     * @return A unique key as a long sequence of hex digits.
     */

    public static 1.5.0/docs/api/java/lang/String.html">String generateHexKey()
    {
        return toHex(generateBytesKey());
    }

    /**
     * Generate a unique key as a byte array.
     *
     * @return A unique key as a byte array.
     */

    public static synchronized byte[] generateBytesKey()
    {
        byte[] junk = new byte[16];

        random.nextBytes(junk);

        1.5.0/docs/api/java/lang/String.html">String input = new 1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer().append(vmid).append(new java.util.5+0%2Fdocs%2Fapi+Date">Date()).append(junk).append(counter++).toString();

        return getMD5Bytes(input.getBytes());
    }

    // The following two methods are taken from the Jakarta IOUtil class.

    /**
     * Copy stream-data from source to destination. This method does not
     * buffer, flush or close the streams, as to do so would require making
     * non-portable assumptions about the streams' origin and further use. If
     * you wish to perform a buffered copy, use {@link #bufferedCopy}.
     *
     * @param input The InputStream to obtain data from.
     * @param output The OutputStream to copy data to.
     */

    public static void copy( final 5+0%2Fdocs%2Fapi+InputStream">InputStream input, final 5+0%2Fdocs%2Fapi+OutputStream">OutputStream output )
            throws 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        final int BUFFER_SIZE = 1024 * 4;
        final byte[] buffer = new byte[ BUFFER_SIZE ];

        while( true )
        {
            final int count = input.read( buffer, 0, BUFFER_SIZE );
            if( -1 == count ) break;

            // write out those same bytes
            output.write( buffer, 0, count );
        }

        //needed to flush cache
        //output.flush();
    }


    public static void bufferedCopy( final 5+0%2Fdocs%2Fapi+InputStream">InputStream source, final 5+0%2Fdocs%2Fapi+OutputStream">OutputStream destination )
            throws 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        final 1.5.0/docs/api/java/io/BufferedInputStream.html">BufferedInputStream input = new 1.5.0/docs/api/java/io/BufferedInputStream.html">BufferedInputStream( source );
        final 1.5.0/docs/api/java/io/BufferedOutputStream.html">BufferedOutputStream output = new 1.5.0/docs/api/java/io/BufferedOutputStream.html">BufferedOutputStream( destination );
        copy( input, output );
        output.flush();
    }

    public static int gen5DigitsKey() {
        1.5.0/docs/api/java/util/Random.html">Random r = new 1.5.0/docs/api/java/util/Random.html">Random( 1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis() );
        return 10000 + r.nextInt(20000);
    }

    public static 1.5.0/docs/api/java/lang/String.html">String genCharsDigitsKey(int number) {
        1.5.0/docs/api/java/lang/String.html">String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-_=+[{]},<.>?";
        return RandomStringUtils.random(number, characters);
    }

    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args)
    {
        1.5.0/docs/api/java/lang/System.html">System.out.println(gen5DigitsKey());
    }


}