All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.evasion.sam.PasswordEncoder Maven / Gradle / Ivy

There is a newer version: 2.0.0.2
Show newest version
package com.evasion.sam;

import com.evasion.sam.codec.Hex;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class PasswordEncoder {

    
    private static final String ALGORITHM = "SHA-1";

    private PasswordEncoder() {
    }
    
    public static String encodePassword(Object salt, String password) {
        MessageDigest sha;
        String saltedPass = mergeSaltPassword(salt, password);
        byte[] digest;

        try {
            sha = MessageDigest.getInstance(ALGORITHM);
            digest = sha.digest(saltedPass.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalStateException("UTF-8 not supported!");
        } catch (NoSuchAlgorithmException ex) {
            throw new IllegalArgumentException("No such algorithm [" + ALGORITHM + "]");
        }


        return new String(Hex.encodeHex(digest));
    }

    private static String mergeSaltPassword(Object salt, String password) {
        StringBuilder saltedPass = new StringBuilder();
        if (password == null) {
            password = new String();
        }
        if (salt == null || "".equals(salt)) {
            return password;
        } else {
            if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
                throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
            }
            return saltedPass.append(password).append("{").
                    append(salt.toString()).append("}").toString();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy