日常记录-简单密码加密工具类(MD5+SHA256)

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class PwdUtil {

    /**
     * 生成密码盐
     *
     * @return 密码盐
     */
    public static String createSalt() {
        return UUID.randomUUID().toString();
    }

    /**
     * 密码加salt加密
     *
     * @param pwd  密文密码
     * @param salt 密码盐
     * @return 加盐密码
     */
    public static String process(String pwd, String salt) {
        return md5(sha256(pwd, salt));//将密码加盐之后 通过MD5降位
    }

    private static String sha256(String pwd, String salt) {
        try {
            MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
            if (salt != null && salt.length() > 0) {
                msgDigest.update(salt.getBytes());
            }
            byte[] digest = msgDigest.digest(pwd.getBytes());
            return new String(new Hex().encode(digest));
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static String md5(String value) {
        if (value == null)
            return null;

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            messagedigest.update(value.getBytes());
            byte[] digest = messagedigest.digest();
            return toHex(digest);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static String toHex(byte abyte0[]) {
        StringBuffer stringbuffer = new StringBuffer();
        for (int i = 0; i < abyte0.length; i++) {
            String s = Integer.toHexString(abyte0[i] & 0xff);
            if (s.length() < 2) {
                stringbuffer.append("0");
            }
            stringbuffer.append(s);
        }
        return stringbuffer.toString();
    }
}  这个密码工具类那些地方可以优化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值