001/*
002 *   Copyright 2020 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.auth;
017
018
019import java.io.UnsupportedEncodingException;
020import java.security.MessageDigest;
021import java.security.NoSuchAlgorithmException;
022
023/**
024 * Contains utility methods that use MD5 hashing. The class uses STANDARD JVM MD5 algorithm.
025 *
026 * @author Paul Cook
027 */
028public class MD5Util {
029
030    /**
031     * Calculates MD5 hash for string. assume string is UTF-8 encoded
032     * @param input string which is going to be encoded into MD5 format
033     * @return  MD5 representation of the input string
034     * @throws NoSuchAlgorithmException if the MD5 algorithm is not available.
035     */
036    public static String calculateMd5(String input) throws NoSuchAlgorithmException {
037        try {
038            return calculateMd5(input, "UTF-8");
039        } catch (UnsupportedEncodingException e) {
040            return null; // -- impossible --
041        }
042    }
043
044    /**
045     * Calculates MD5 hash for string.
046     * @param input string which is going to be encoded into MD5 format
047     * @param encoding character encoding of the string which is going to be encoded into MD5 format
048     * @return  MD5 representation of the input string
049     * @throws NoSuchAlgorithmException if the MD5 algorithm is not available.
050     * @throws UnsupportedEncodingException if the specified encoding is unavailable.
051     */
052    public static String calculateMd5(String input, String encoding) throws NoSuchAlgorithmException, UnsupportedEncodingException {
053        MessageDigest md = MessageDigest.getInstance("MD5");
054        md.update(input.getBytes(encoding));
055        byte digest[] = md.digest();
056
057        final StringBuilder hexString = new StringBuilder();
058        for (byte element : digest) {
059            int z = 0xFF & element;
060            if (z < 16)
061                hexString.append("0");
062            hexString.append(Integer.toHexString(z));
063        }
064
065        return hexString.toString();
066    }
067
068}