SecurityTool.java 2.93 KB
package com.xkl.security;

import java.security.MessageDigest;
import java.util.Random;

/**
 * Created by win7 on 2016/11/7.
 */
public class SecurityTool {
    private static final String ALGORITHM = "SHA1";

    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };
    /**
     * 生成SALT的数组(86)
     */
    private static final String[] SALT_ARR = { "a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
            "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
            "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "0"};

    /**
     * SALT长度
     */
    private static final int SALT_LENGTH = 16;

    /**
     * 生成16为随机salt
     * @return
     */
    public static String genSalt() {
        StringBuffer result = new StringBuffer();
        Random r = new Random();
        int temp = 0;
        for (int i = 0; i < SALT_LENGTH; i++) {
            temp = r.nextInt(SALT_ARR.length);
            result.append(SALT_ARR[temp]);
        }
        return result.toString();
    }

    /**
     * encode string
     *
     * @param algorithm
     * @param str
     * @return String
     */
    public static String encode(String algorithm, String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes
     *            the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String getPassword(String account, String origalPassword, String salt) {
        // 将原始密码加密成md5
        String md5pass = encode("MD5",origalPassword);
        //用户在数据库中存储的数据为:md5(sha1(account + salt) + md5pass)
        String encodePass = encode("MD5", encode("SHA1",account + salt) + md5pass);
        return encodePass;
    }

    public static void main(String[] args) {
        String salt=genSalt();
        System.out.println(salt);
        System.out.println(getPassword("admin", "admin",salt));
    }
}