java生成token之MessageDigest简单使用

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24347541/article/details/88865019
/**
 * 生成token
 */
public class TokenGenerator {

    public static String generateValue() {
        return generateValue(UUID.randomUUID().toString());
    }

    private static final char[] hexCode = "0123456789abcdef".toCharArray();

    public static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for ( byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    public static String generateValue(String param) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            throw new RRException("生成Token失败", e);
        }
    }
}

java.security.MessageDigest类用于为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。简单点说就是用于生成散列码。信息摘要是安全的单向哈希函数,它接收随意大小的数据,输出固定长度的哈希值。

MessageDigest algorithm = MessageDigest.getInstance(“MD5”); //生成实现MD5摘要算法的 MessageDigest 对象
algorithm.reset();//重置摘要以供再次使用。
algorithm.update(param.getBytes()); //使用指定的字节更新摘要。
algorithm.digest();//通过运行诸如填充之类的终于操作完毕哈希计算。
toHexString(messageDigest);//重新进行补码。

猜你喜欢

转载自blog.csdn.net/qq_24347541/article/details/88865019