Java MD5 String md5(String s)

Here you can find the source of md5(String s)

Description

md

License

Open Source License

Declaration

public static String md5(String s) 

Method Source Code


//package com.java2s;
/*/*from w ww .j  a  v  a  2 s. c o  m*/
 * Utilities.java
 *
 * Created on February 13, 2007, 8:18 AM
 *
 * (c) 2009  The Echo Nest
 * See "license.txt" for terms
 *
 */

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.math.BigInteger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String md5(String s) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte[] md5sum = digest.digest();
            BigInteger bigInt = new BigInteger(1, md5sum);
            String output = bigInt.toString(16);
            // the MD5 needs to be 32 characters long.
            return prepad(output, 32, '0');
        } catch (NoSuchAlgorithmException e) {
            System.err.println("No MD5 algorithm. we are sunk.");
            return s;
        }
    }

    public static String md5(File f) throws IOException {
        byte[] buffer = new byte[8192];
        int read = 0;
        InputStream is = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            is = new BufferedInputStream(new FileInputStream(f));
            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
            byte[] md5sum = digest.digest();
            BigInteger bigInt = new BigInteger(1, md5sum);
            String output = bigInt.toString(16);
            // the MD5 needs to be 32 characters long.
            return prepad(output, 32, '0');
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Can't find md5 algorithm");
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    private static String prepad(String s, int len, char c) {
        // slow but used so rarely, who cares.
        while (s.length() < len) {
            s = c + s;
        }
        return s;
    }
}

Related

  1. md5(String s)
  2. md5(String s)
  3. md5(String s)
  4. md5(String s)
  5. md5(String s)
  6. md5(String s)
  7. md5(String s)
  8. md5(String s)
  9. md5(String s)