MD5在java中的简单使用

最近项目上有个访问权限配置,访问该接口需要有一定的权限,登录帐号信息,将其加密处理后,当调用该接口时判断帐号权限即可:

具体代码如下:

package com.trip.hotel.ebooking.util;

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

/**
 * @description: md5加密
 * @author: fengze
 * @create: 2018-09-10 14:12
 **/
public class MD5Util {

    private final static String AUTH = "帐号加密串";

    /**
     * 将源字符串使用MD5加密为字节数组
     * @param source
     * @return
     */
    public static byte[] encode2bytes(String source) {
        byte[] result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(source.getBytes("UTF-8"));
            result = md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 将源字符串使用MD5加密为32位16进制数
     * @param source
     * @return
     */
    public static String encode2hex(String source) {
        byte[] data = encode2bytes(source);

        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(0xff & data[i]);

            if (hex.length() == 1) {
                hexString.append('0');
            }

            hexString.append(hex);
        }

        return hexString.toString();
    }

    /**
     * 验证字符串是否匹配
     * @param unknown 待验证的字符串
     * @return	匹配返回true,不匹配返回false
     */
    public static boolean validate(String unknown ) {
        return AUTH.equals(encode2hex(unknown));
    }

    public static void main(String[] args) {
        String str = MD5Util.encode2hex("需要加密的帐号");
        System.out.println("加密后为:" + str);
        System.out.println("是否匹配:" + AUTH.equals(str));
        
    }

}

具体流程:

1.将需要加密的帐号提前进行加密处理,将加密串赋值;

2.每次请求该接口或者方法时,获取登录信息,将登录帐号做加密处理;

3.比较当前登录帐号和配置帐号是否一致;

4.如果一致,有权限修改;否则,没有调用权限。

猜你喜欢

转载自blog.csdn.net/fz13768884254/article/details/82590441