Method for returning an md5 hash of a string. - Android java.lang

Android examples for java.lang:String Hash

Description

Method for returning an md5 hash of a string.

Demo Code

/**/*from w w  w . j  ava 2s . c  o m*/
 * AdFlakeUtil.java (AdFlakeSDK-Android)
 *
 * Copyright ? 2013 MADE GmbH - All Rights Reserved.
 *
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * unless otherwise noted in the License section of this document header.
 *
 * @file AdFlakeUtil.java
 * @copyright 2013 MADE GmbH. All rights reserved.
 * @section License
 * 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.
 */
//package com.java2s;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**
     * Method for returning an md5 hash of a string.
     * 
     * @param val
     *            the string to hash.
     * @return A hex string representing the md5 hash of the input.
     */
    private static String md5(String val) {
        String result = null;

        if ((val != null) && (val.length() > 0)) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(val.getBytes(), 0, val.length());
                result = String.format("%032X",
                        new BigInteger(1, md5.digest()));
            } catch (NoSuchAlgorithmException nsae) {
                result = val.substring(0, 32);
            }
        }

        return result;
    }
}

Related Tutorials