Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**
     * call n md5
     * For example,
     *      if count equal 2, it will call twice md5,  md5(md5(string))
     * @param count
     * @return
     */
    public static String md5N(final String string, final int count) {
        if (count <= 0)
            throw new IllegalArgumentException("count can't < 0");
        String result = null;
        for (int i = 0; i < count; i++) {
            result = md5(string);
        }
        return result;
    }

    /**
     * use md5 algorithm
     * @param string the String need to encrypt
     * @return the encrypted result
     */
    public static String md5(final String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}