Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

import java.util.Formatter;

public class Main {
    /**
     * Returns the Md5 hash for the given text.
     * 
     * @param text
     *            String whose Md5 hash should be returned.
     * @return Returns the Md5 hash for the given text.
     */
    public static String getMd5Hash(String text) {
        StringBuffer result = new StringBuffer(32);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(text.getBytes());
            Formatter f = new Formatter(result);

            byte[] digest = md5.digest();

            for (int i = 0; i < digest.length; i++) {
                f.format("%02x", new Object[] { new Byte(digest[i]) });
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }

        return result.toString();
    }
}