【笔记】java与python HmacSHA256加密代码

java

    public static String sign(String content,String appkey) {

        String result = null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            byte[] keyBytes = appkey.getBytes("UTF-8");
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));

            byte[] hmacSha256Bytes = hmacSha256.doFinal(content.getBytes("UTF-8"));
            result = new String(Base64.encodeBase64(hmacSha256Bytes), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

python

import hashlib
import hmac
import base64

def sign(value,key):
    j = hmac.new(key.encode(), value.encode(), digestmod=hashlib.sha256);
    ret = (base64.b64encode(j.digest()).decode())
    return ret

 

posted @ 2020-04-02 16:51  stagebo  阅读(2072)  评论(2编辑  收藏  举报