001// --------------------------------------------------------------------------------
002// Copyright 2002-2024 Echo Three, LLC
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// --------------------------------------------------------------------------------
016
017package com.echothree.util.common.string;
018
019import com.google.common.base.Charsets;
020import com.google.common.io.BaseEncoding;
021import java.security.MessageDigest;
022import java.security.NoSuchAlgorithmException;
023
024public class MD5Utils {
025    
026    private MD5Utils() {
027        super();
028    }
029    
030    private static class MD5UtilsHolder {
031        static MD5Utils instance = new MD5Utils();
032    }
033    
034    public static MD5Utils getInstance() {
035        return MD5UtilsHolder.instance;
036    }
037    
038    public String encode(String string) {
039        byte[] md5Hash = null;
040        
041        try {
042            MessageDigest md5Encoder = MessageDigest.getInstance("MD5");
043            
044            md5Encoder.update(string.getBytes(Charsets.UTF_8));
045            md5Hash = md5Encoder.digest();
046        } catch (NoSuchAlgorithmException nsae) {
047            // nothing
048        }
049        
050        return BaseEncoding.base64().encode(md5Hash);
051    }
052    
053}