Java MD5 String md5Representation(String data)

Here you can find the source of md5Representation(String data)

Description

Returns a md5 representation of the given string

License

MIT License

Parameter

Parameter Description
data a parameter

Declaration

public static String md5Representation(String data) 

Method Source Code

//package com.java2s;
/**/*w  w  w .  j a va 2 s .c  om*/
 * Static class to send messages to Pusher's REST API.
 * 
 * Please set pusherApplicationId, pusherApplicationKey, pusherApplicationSecret accordingly
 * before sending any request. 
 * 
 * @author Stephan Scheuermann
 * Copyright 2010. Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

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

public class Main {
    /**
     * Returns a md5 representation of the given string
     * @param data
     * @return
     */
    public static String md5Representation(String data) {
        try {
            //Get MD5 MessageDigest
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digest = messageDigest.digest(data.getBytes("US-ASCII"));
            return byteArrayToString(digest);
        } catch (NoSuchAlgorithmException nsae) {
            //We should never come here, because GAE has a MD5 algorithm
            throw new RuntimeException("No MD5 algorithm");
        } catch (UnsupportedEncodingException e) {
            //We should never come here, because UTF-8 should be available
            throw new RuntimeException("No UTF-8");
        }
    }

    /**
     * Converts a byte array to a string representation
     * @param data
     * @return
     */
    public static String byteArrayToString(byte[] data) {
        BigInteger bigInteger = new BigInteger(1, data);
        String hash = bigInteger.toString(16);
        // Zero pad it
        while (hash.length() < 32) {
            hash = "0" + hash;
        }
        return hash;
    }
}

Related

  1. md5Hex(String message)
  2. md5Hex(String s)
  3. md5hex(String source)
  4. md5Hex(String str)
  5. md5raw(String data)
  6. md5Signature(TreeMap params, String secret)
  7. md5Signature(TreeMap params, String secret)
  8. md5String(String input)
  9. md5String(String key)