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

com.centit.support.security.Md5Encoder Maven / Gradle / Ivy

There is a newer version: 5.3.2302
Show newest version
package com.centit.support.security;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 散列算法返回的128bit的编码,HEX编码后的长度为32Byte
 * @author codefan
 *
 */
@SuppressWarnings("unused")
public abstract class Md5Encoder {
    private Md5Encoder() {
        throw new IllegalAccessError("Utility class");
    }

    protected static final Logger logger = LoggerFactory.getLogger(Md5Encoder.class);

    public static String encode(byte[] data){
        MessageDigest MD5;
        try {
            MD5 = MessageDigest.getInstance("MD5");
            MD5.update(data, 0, data.length);
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(),e);//e.printStackTrace();
            return null;
        }
    }

    public static String encode(String data){
        try {
            return encode(data.getBytes("utf8"));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);//e.printStackTrace();
            return null;
        }
    }
    /**
     * encoding password for spring security
     * 目前框架中的密码都是这样加密的
     * @param data  密文
     * @param salt  盐
     * @return 散列值
     */
    public static String encodePasswordAsSpringSecurity(String data,String salt){
        return encode(data + "{" + salt + "}");
    }


    /**
     * encoding password for spring JA-SIG Cas
     * @param data  密文
     * @param salt  盐
     * @param iterations 迭代次数
     * @return 散列值
     */
    public static String encodePasswordAsJasigCas(String data,String salt, int iterations){
        MessageDigest MD5;
        try {
            MD5 = MessageDigest.getInstance("MD5");
            byte[] saltBytes = salt.getBytes("utf8");
            MD5.update(saltBytes, 0, saltBytes.length);
            byte[] hashedBytes = MD5.digest(data.getBytes("utf8"));
            for(int i=0;i




© 2015 - 2024 Weber Informatics LLC | Privacy Policy