Java Digest digest(final String password)

Here you can find the source of digest(final String password)

Description

Digests password with MD5 and encodes it as a hex String.

License

LGPL

Parameter

Parameter Description
password to digest.

Return

hex encoded password digest.

Declaration

public static String digest(final String password) throws NoSuchAlgorithmException 

Method Source Code

//package com.java2s;
/*/*from   w  w w  .jav  a  2s  .  c  o m*/
 * Cacheonix Systems licenses this file to You under the LGPL 2.1
 * (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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm
 *
 * 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;

public class Main {
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**
     * Digests password with MD5 and encodes it as a hex String.
     *
     * @param password to digest.
     * @return hex encoded password digest.
     */
    public static String digest(final String password) throws NoSuchAlgorithmException {

        final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(password.trim().toLowerCase().getBytes());
        return encodeToHex(messageDigest.digest());
    }

    /**
     * Returns a string of hexadecimal digits from a byte array. Each byte is converted to 2 hex symbols.
     */
    public static String encodeToHex(final byte[] ba) { // NOPMD - "A user given array is stored directly"  - we do NOT store anything.
        final int length = ba.length;
        final char[] buf = new char[(length << 1)];
        for (int i = 0, j = 0; i < length;) {
            final int k = ba[i++];
            buf[j++] = HEX_DIGITS[k >>> 4 & 0x0F];
            buf[j++] = HEX_DIGITS[k & 0x0F];
        }
        return String.valueOf(buf);
    }
}

Related

  1. digest(final @Nullable String[] tokens, @Nullable final Date[] dates)
  2. digest(final byte[] data)
  3. digest(final InputStream inputStream, final MessageDigest digester)
  4. digest(final java.security.MessageDigest messageDigest, final java.nio.ByteBuffer data)
  5. digest(final String algorithm, final byte[] bytes)
  6. digest(InputStream input, String algorithm)
  7. digest(InputStream is, String digestAlgorithm)
  8. digest(MessageDigest digest, InputStream data)
  9. digest(MessageDigest method, File f)