Java Digest digestThenEncodePasswordForLDAP(String algorithm, String credentials)

Here you can find the source of digestThenEncodePasswordForLDAP(String algorithm, String credentials)

Description

digest Then Encode Password For LDAP

License

Apache License

Declaration

public static String digestThenEncodePasswordForLDAP(String algorithm, String credentials) 

Method Source Code


//package com.java2s;
/*/*  www. j a va 2 s .com*/
 * *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*
 * SMART COSMOS Platform Core SDK
 * ===============================================================================
 * Copyright (C) 2013 - 2015 SMARTRAC Technology Fletcher, 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 com.google.common.io.BaseEncoding;

import java.security.MessageDigest;

public class Main {
    public static String digestThenEncodePasswordForLDAP(String algorithm, String credentials) {
        String hashedCredentials = credentials;

        if ((credentials != null) && (credentials.length() > 0)) {
            boolean isMD5Hash = algorithm.equalsIgnoreCase("MD5");
            boolean isSHAHash = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1")
                    || algorithm.equalsIgnoreCase("SHA-1");

            if (isSHAHash || isMD5Hash) {
                String hashAlgorithm = "MD5";
                if (isSHAHash) {
                    hashAlgorithm = "SHA";
                }
                try {
                    MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
                    md.update(credentials.getBytes("UTF-8"));
                    hashedCredentials = "{" + hashAlgorithm + "}" + BaseEncoding.base64().encode(md.digest());
                } catch (Exception e) {
                    hashedCredentials = null;
                }
            }
        }

        return hashedCredentials;
    }
}

Related

  1. digestStream(MessageDigest digest, InputStream is)
  2. digestString(MessageDigest md, String s)
  3. digestString(String input)
  4. digestString(String pass, String algorithm)
  5. digestString(String pass, String algorithm)
  6. digestWithSalt(String password, byte[] salt, String algorithm)