Java工具集-HMacSHA1加解密

代碼示例


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: simple_tools
 * @description: HMacSHA1加解密
 * @author: Mr.chen
 * @create: 2020-05-18 09:00
 **/
public class HMacSHA1Encrypt {

    /**
     *
     * @param pwd
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static byte[] encode(String pwd, String data) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA1");
        byte[] keyBytes = pwd.getBytes("UTF8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        mac.init(signingKey);
        byte[] utf8 = data.getBytes("UTF8");
        return mac.doFinal(utf8);
    }

    /**
     *
     * @param Passwd
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encode(String Passwd) throws NoSuchAlgorithmException {
        MessageDigest alg = MessageDigest.getInstance("SHA-1");
        alg.update(Passwd.getBytes());
        byte[] bts = alg.digest();
        String result = "";
        String tmp = "";
        for (byte bt : bts) {
            tmp = (Integer.toHexString(bt & 0xFF));
            if (tmp.length() == 1) {
                result += "0";
            }
            result += tmp;
        }
        return result;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章