get Md5 Hash for a String - Android java.lang

Android examples for java.lang:String Hash

Description

get Md5 Hash for a String

Demo Code

/*******************************************************************************
 * Copyright 2013 momock.com//from  w w  w . j  a  va  2 s . c o  m
 * 
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 * 
 * 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.
 ******************************************************************************/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.annotation.SuppressLint;

public class Main {
  @SuppressLint("DefaultLocale")
  public static String getMd5(String text) {
    MessageDigest m = null;
    try {
      m = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {

    }
    m.update(text.getBytes(), 0, text.length());
    byte md5Data[] = m.digest();

    String uniqueID = new String();
    for (int i = 0; i < md5Data.length; i++) {
      int b = (0xFF & md5Data[i]);
      if (b <= 0xF)
        uniqueID += "0";
      uniqueID += Integer.toHexString(b);
    }
    return uniqueID.toUpperCase();
  }
}

Related Tutorials