krysalis-update/src/java/org/krysalis/depot/update/util/security HashCodeManager.java,NONE,1.1 ChkSum.java,NONE,1.1

Nick Chalko <[email protected]> Wed, 08 Dec 2004 09:07:18 +0000
Newsgroups gmane.comp.krysalis.cvs
Message-ID <[email protected]>
Update of /cvsroot/krysalis/krysalis-update/src/java/org/krysalis/depot/update/util/security
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24726/src/java/org/krysalis/depot/update/util/security

Added Files:
	HashCodeManager.java ChkSum.java 
Log Message:
Copied from the apache incubator.

--- NEW FILE: ChkSum.java ---
/*
 * Copyright  2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.krysalis.depot.update.util.security;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.krysalis.depot.update.UpdateException;
import org.krysalis.depot.common.log.Logger;


/**
 * TODO mm Create Comment
 *
 * @author mmay
 */
public class ChkSum {
    private String digestAlgorithm = null;
    private String digestProvider = null;
    private MessageDigest messageDigest = null;
    private File hashCodeFile = null;
    private File sourceFile = null;
    private String genHashCode = null;
    private String readHashCode = null;
    private int buffersize = HashCodeManager.DEFAULT_BUFFERSIZE;

    /**
     * Constructs a new ChkSum Object
     * Note, that the provider can be null
     */
    public ChkSum(String algorithm, String provider) {
        this.digestAlgorithm = algorithm;
        this.digestProvider = provider;
    }

    /**
     * Creates a new ChkSum object.
     * Convenience Constructor
     *
     * @param algorithm maybe MD5 or SHA or ???
     */
    public ChkSum(String algorithm) {
        this(algorithm, null);
    }

    /**
     * Creates a new ChkSum object with the Default Algorithm
     * Convenience Constructor
     * 
     */
    public ChkSum() {
        this(HashCodeManager.DEFAULT_ALGORITHM, null);
    }

    /**
     * TODO Add JavaDoc
     *
     * @return TODO
     *
     * @throws NoSuchAlgorithmException TODO
     * @throws NoSuchProviderException TODO
     */
    public MessageDigest getDigest() throws NoSuchAlgorithmException, NoSuchProviderException {
        if (this.messageDigest == null) {
            this.messageDigest = HashCodeManager.createDigester(this.digestAlgorithm, this.digestProvider);
        }

        return this.messageDigest;
    }

    /**
     * TODO Add JavaDoc
     *
     * @return TODO
     */
    private boolean validate() throws UpdateException {
    	boolean returnValue = false;
    	
    	Logger.getLogger().debug("Validating HashCode");

        if ((this.sourceFile == null) || !this.sourceFile.exists()) {
        			throw new UpdateException("Cannot find " + sourceFile);
        }

        if ((this.hashCodeFile == null) || !this.hashCodeFile.exists()) {
        			throw new UpdateException("Cannot find " + hashCodeFile);
        }

        try {
            byte[] checksum = HashCodeManager.getDigest(this.sourceFile, this.messageDigest, this.buffersize);
            byte[] readChecksum = HashCodeManager.readHashFromFile(this.hashCodeFile);
            
            returnValue = HashCodeManager.compareHashes(checksum, readChecksum);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue;
    }

    /**
     *
     */
    public void writeHashCodeToFile(File destination, byte[] digest) {
    	Logger.getLogger().debug("Opening destination File");
    	
    	try {
			HashCodeManager.writeHashToFile(destination, digest);
		} catch (IOException e) {
			e.printStackTrace();
		}    	
    }

    /**
     * Generates a Checksum from a File
     *
     * @param source
     *
     * @return
     */
    private byte[] generateChecksum(File source) throws Exception {
        return HashCodeManager.getDigest(source, this.messageDigest, this.buffersize);
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public String getDigestAlgorithm() {
        return digestAlgorithm;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pString
     */
    public void setDigestAlgorithm(String pString) {
        digestAlgorithm = pString;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public String getDigestProvider() {
        return digestProvider;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pString
     */
    public void setDigestProvider(String pString) {
        digestProvider = pString;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public String getGenHashCode() {
        return genHashCode;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pString
     */
    public void setGenHashCode(String pString) {
        genHashCode = pString;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public File getHashCodeFile() {
        return hashCodeFile;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pFile
     */
    public void setHashCodeFile(File pFile) {
        hashCodeFile = pFile;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public MessageDigest getMessageDigest() {
        return messageDigest;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pDigest
     */
    public void setMessageDigest(MessageDigest pDigest) {
        messageDigest = pDigest;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public String getReadHashCode() {
        return readHashCode;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pString
     */
    public void setReadHashCode(String pString) {
        readHashCode = pString;
    }

    /**
     * TODO mm Create Comment
     *
     * @return
     */
    public File getSourceFile() {
        return sourceFile;
    }

    /**
     * TODO mm Create Comment
     *
     * @param pFile
     */
    public void setSourceFile(File pFile) {
        sourceFile = pFile;
    }
}

--- NEW FILE: HashCodeManager.java ---
/*
 * Copyright  2000-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.krysalis.depot.update.util.security;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.krysalis.depot.update.UpdateRuntimeException;
import org.apache.tools.ant.BuildException;

//import org.krysalis.depot.update.RuperException;

/**
 *
 *
 */
public class HashCodeManager {
    public static final String DEFAULT_ALGORITHM = "MD5";
    public static final int DEFAULT_BUFFERSIZE = (8 * 1024);

    /**
     *
     */
    private HashCodeManager() {
        super();
    }

    /**
     * Creates a messageDigester from given parameters
     *
     * @param algorithm e.g. MD5 or SHA is used to generate the checksum
     * @param provider which implements the JAVA Security API (null is a good guess!)
     *
     * @return valid MessageDigest
     *
     * @throws NoSuchAlgorithmException in the case that the digest could not be created
     * @throws NoSuchProviderException TODO
     */
    public static MessageDigest createDigester(String algorithm, String provider)
                                        throws NoSuchAlgorithmException, NoSuchProviderException {
        MessageDigest messageDigest = null;

        if (algorithm == null) {
            algorithm = HashCodeManager.DEFAULT_ALGORITHM;
        }

		if (provider == null) {
        	messageDigest = MessageDigest.getInstance(algorithm);			
		} else {
			messageDigest = MessageDigest.getInstance(algorithm, provider);
		}

        if (messageDigest == null) {
            //                throw new Exception("Cannot create Digest");
        }

        return messageDigest;
    }

    /**
     * TODO Add JavaDoc
     *
     * @param firstHash TODO
     * @param sndHash TODO
     *
     * @return TODO
     */
    public static boolean compareHashes(byte[] firstHash, byte[] sndHash) {
        if (firstHash.length != sndHash.length) {
            return false;
        }

        for (int i = 0; i < sndHash.length; i++) {
            if (firstHash[i] != sndHash[i]) {
                return false;
            }
        }

        return true;
    }

    /**
     * TODO Add JavaDoc
     *
     * @param file TODO
     * @param digest TODO    Note: This code is copied from ant.
     */
    public static void writeHashToFile(File destination, byte[] digest) throws IOException {
        File dest = (File) destination;
        FileOutputStream fos = null;

		try {
			fos = new FileOutputStream(dest);
        	fos.write(digest);
		} catch (FileNotFoundException e) {
			//TODO mm Auto-generated catch block
			e.printStackTrace();
		} finally {
        	fos.close();
        	fos = null;			
		}
    }

    /**
     * TODO Add JavaDoc
     *
     * @param file TODO
     *
     * @return TODO
     *
     * @throws BuildException TODO
     */
    public static byte[] readHashFromFile(File checksumFile) throws Exception {
        String checksum = null;
        
        try {
            BufferedReader diskChecksumReader = new BufferedReader(new FileReader(checksumFile));
            checksum = diskChecksumReader.readLine();
        } catch (IOException e) {
//            throw new BuildException("Couldn't read checksum file " + checksumFile, e);
        }

        byte[] digest = HashCodeManager.decodeHex(checksum.toCharArray());

        return digest;
    }

    /**
     * gets the digest of the file as bytes
     * Copied from ANT
     *
     * @param file The file to read.
     * @param messageDigest TODO
     *
     * @return The bytes of the file.
     *
     * @throws Exception If an error occurs reading in the file's bytes.
     */
    public static byte[] getDigest(File file, MessageDigest messageDigest, int readBufferSize)
                           throws Exception {
        FileInputStream fis = new FileInputStream(file);
        messageDigest.reset();
		
		byte[] buf = new byte[readBufferSize];
		
        DigestInputStream dis = new DigestInputStream(fis, messageDigest);

        while (dis.read(buf, 0, readBufferSize) != -1) {
            ;
        }

        dis.close();
        fis.close();
        fis = null;

        byte[] fileDigest = messageDigest.digest();
        
        return fileDigest;
    }

    /**
     * creates a String from the fileDigest
     *
     * @param fileDigest byteArray containing the fileDigest
     *
     * @return 
     * 
     * NOTE: This code is copied from ant.
     */
    public static String createDigestString(byte[] fileDigest) {
        StringBuffer checksumSb = new StringBuffer();

        for (int i = 0; i < fileDigest.length; i++) {
            String hexStr = Integer.toHexString(0x00ff & fileDigest[i]);

            if (hexStr.length() < 2) {
                checksumSb.append("0");
            }

            checksumSb.append(hexStr);
        }

        return checksumSb.toString();
    }

    /**
     * Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The
     * returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An
     * exception is thrown if the passed char array has an odd number of elements. 
     * NOTE: This code is copied from jakarta-commons codec.
     *
     * @param data TODO
     *
     * @return TODO
     *
     * @throws BuildException TODO
     */
    public static byte[] decodeHex(char[] data) throws Exception {
        int l = data.length;

        if ((l & 0x01) != 0) {
            throw new UpdateRuntimeException("odd number of characters.");
        }

        byte[] out = new byte[l >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < l; i++) {
            int f = Character.digit(data[j++], 16) << 4;
            f = f | Character.digit(data[j++], 16);
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }
}



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now. 
http://productguide.itmanagersjournal.com/