密码加密

生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash

package com.fh.util.websocket;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.Validate;

public class AppUtil  {
    
    /**
     * 密码加密
     * @param plainPassword 明文密码
     * @return 加密后的密码
     */
    public static String entryptPassword2(String plainPassword) {
        //生成随机的bute作为salt
        SecureRandom random = new SecureRandom();
        byte[] salt = null;
        final int SALT_SIZE = 8;
        Validate.isTrue(SALT_SIZE > 0, "numBytes argument must be a positive integer (1 or larger)", SALT_SIZE);
        byte[] bytes = new byte[SALT_SIZE];
        random.nextBytes(bytes);
        salt =  bytes;
        
        // 对字符串进行散列, 支持md5与sha1算法.
        String SHA1 = "SHA-1";
        final int HASH_INTERATIONS = 1024;
        byte[] hashPassword = null;
        //digest(plainPassword.getBytes(), SHA1, salt, HASH_INTERATIONS);
        try {
            MessageDigest digest = MessageDigest.getInstance(SHA1);

            if (salt != null) {
                digest.update(salt);
            }
            
            byte[] result = digest.digest(plainPassword.getBytes());

            for (int i = 1; i < HASH_INTERATIONS; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            hashPassword = result;
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        
        //Hex编码.
        String rel1 = new String(Hex.encodeHex(salt));
        
        //Hex编码.
        String rel2 = new String(Hex.encodeHex(hashPassword));
        
        return rel1 + rel2;
    }
    
    
}
原文地址:https://www.cnblogs.com/excellencesy/p/10694555.html