Java MD5 md5Encode(String strIn)

Here you can find the source of md5Encode(String strIn)

Description

Compute the MD5 of the given string and return it as a Base64-encoded value.

License

Apache License

Parameter

Parameter Description
strIn A Unicode string.

Return

Base64-encoded value of the strings UTF-8 encoded value.

Declaration

public static String md5Encode(String strIn) 

Method Source Code

//package com.java2s;
/*//from w w  w. j a  v a 2s. c  om
 * Copyright (C) 2014 Dell, Inc.
 * 
 * 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.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;

public class Main {
    /**
     * The Charset object for the UTF-8 character set.
     */
    public static final Charset UTF8_CHARSET = Charset.forName("UTF-8");

    /**
     * Compute the MD5 of the given string and return it as a Base64-encoded value. The
     * string is first converted to bytes using UTF-8, and the MD5 is computed on that
     * value. The MD5 value is 16 bytes, but the Base64-encoded string is 24 chars.
     *  
     * @param strIn A Unicode string.
     * @return      Base64-encoded value of the strings UTF-8 encoded value.
     */
    public static String md5Encode(String strIn) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] bin = toBytes(strIn);
            byte[] bout = md5.digest(bin);
            String strOut = javax.xml.bind.DatatypeConverter.printBase64Binary(bout);
            return strOut;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * Convert the given string to a byte[] in using the {@link #UTF8_CHARSET} encoder.
     * This is the inverse of {@link #toString(byte[])}. A null value is allowed, which
     * begets a null result.
     *
     * @param str   String value to be converted.
     * @return      Lossless, encoded value as a byte[], or null if str is null.
     */
    public static byte[] toBytes(String str) {
        if (str == null) {
            return null;
        }
        //optimization for ascii strings
        byte[] ascii = toAsciiBytes(str);
        if (ascii != null)
            return ascii;

        ByteBuffer bb = UTF8_CHARSET.encode(str);
        return getBytes(bb);
    }

    /**
     * Convert a long to a byte[] using the format Cassandra wants for a column or
     * supercolumn name. The antimethod for this one is {@link #toLong(byte[])}.
     *
     * @param value Long value to be converted.
     * @return      Same value encoded into an byte[8] array.
     */
    public static byte[] toBytes(long value) {
        byte[] bytes = new byte[8];
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.putLong(value);
        return bytes;
    }

    private static byte[] toAsciiBytes(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) > 127)
                return null;
        }
        byte[] bytes = new byte[str.length()];
        for (int i = 0; i < str.length(); i++) {
            bytes[i] = (byte) str.charAt(i);
        }
        return bytes;
    }

    /**
     * Extract the bytes in the given ByteBuffer and return it as a byte[]. CAUTION: this
     * method calls ByteBuffer.get(), which <i>transfers</i> bytes from the ByteBuffer to
     * the result buffer. Hence, it is "destructive" in the sense that the value cannot be
     * examined again without calling ByteBuffer.rewind() or something else. 
     *
     * @param   bytes   ByteBuffer.
     * @return          Contents between 'position' and 'limit' (aka 'remaining') as a
     *                  byte[].
     * @see     #copyBytes(ByteBuffer)
     */
    public static byte[] getBytes(ByteBuffer bytes) {
        byte[] result = new byte[bytes.remaining()]; // bytes between position and limit
        bytes.get(result);
        return result;
    }
}

Related

  1. md5(String toDigest)
  2. md5_hh(int C, int B, int G, int F, int A, int E, int D)
  3. md5_id(byte[] md5digest)
  4. md5bytesToHex(byte[] md5)
  5. md5Encode(byte[] content)
  6. md5HashByteToString(byte[] bytes)
  7. md5HashStringToByte(String hash)
  8. md5Hex(final String text)
  9. md5Init()