MD5 Sum : MD5 « Security « Java






MD5 Sum

 
/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.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.eclipse.org/legal/epl-v10.html
 *
 * 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 nl.cloudfarming.client.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author Timon Veenstra
 */
public class MD5Sum {

    /**
     * Create a MD5 checksum for a file
     *
     * @param filename
     * @return md5sum
     * @throws Exception
     */
    public static byte[] createChecksum(InputStream fis) throws NoSuchAlgorithmException, IOException {
        if (fis == null) { 
            throw new FileNotFoundException("InputStream cannot be read");
        }

        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("MD5");
        int numRead;
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        fis.close();
        return complete.digest();
    }
    static final String HEXES = "0123456789abcdef";

    /**
     * convert byte into a hax encoded string
     * 
     * @param raw
     * @return
     */
    public static String getHex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}

   
  








Related examples in the same category

1.OTP one-time password calculationOTP one-time password calculation
2.Applet to serve as an s/key calculator application wrapper around otp class
3.Creating a Keyed Digest Using MD5
4.MD5 BASE64 checksum for the specified input string.
5.MD5 InputStream
6.Implements MD5 functionality on a stream.
7.Fast implementation of RSA's MD5 hash generator in Java JDK Beta-2 or higher
8.MD5 algorithm RFC 1321
9.Contains internal state of the MD5 class
10.Create MD5 String
11.MD5 string
12.MD5 Hashing utility that builds up a hash from a series of objects and base types fed into it.
13.MD5 MessageDigest
14.Get MD5 string