HmacSHA256加密算法实现

在许多Api调用的时候都会有对请求字符串拼接并生成签名的要求,下面整理了几个常用编程语言的实现方法

Python

def HmacSHA256(message: str, secret: str):
    message = message.encode('utf-8')
    key = secret.encode('utf-8')
    return base64.b64encode(hmac.new(key, message, digestmod=sha256).digest()).decode()
    
sign = HmacSHA256("hello", "secret_key")

Golang

package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
)

func HmacSHA256(message string, secret string) string {
	key := []byte(secret)
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func main() {
    sign = HmacSHA256("hello", "secret_key")
}

JavaScript

ES6方式

import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';
Base64.stringify(hmacSHA256(message, secret))

NodeJS

var CryptoJS = require("crypto-js");
sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(message, secret))

参考文章 https://devnote.pro/app/community/posts/10000051981222

你可能感兴趣的:(javascript,golang,python)