Java hmac sha256
package com.example;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
String secretKey = "BCDSGS_3ccfa7d4c44c2b2f48df1062dec79a9c";
String message = "POST\n" + "/restapi/prod/IC33000020221014000001/webapi/govmessage/message/send\n" + "\n" + "BCDSGA_c52c72dcfbddc8f48ffea57974d959c3\n" + "Wed, 24 May 2023 07:16:48 GMT\n";
Mac hasher = Mac.getInstance("HmacSHA256");
hasher.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"));
byte[] hash = hasher.doFinal(message.getBytes());
DatatypeConverter.printHexBinary(hash);
String sign = DatatypeConverter.printBase64Binary(hash);
System.out.printf(sign);
}
}
python
import hmac
import hashlib
import base64
if __name__ == '__main__':
try:
secret_key = "BCDSGS_3ccfa7d4c44c2b2f48df1062dec79a9c";
message = "POST\n" + "/restapi/prod/IC33000020221014000001/webapi/govmessage/message/send\n" + "\n" + "BCDSGA_c52c72dcfbddc8f48ffea57974d959c3\n" + "Wed, 24 May 2023 07:16:48 GMT\n"
hasher = hmac.new(bytes(secret_key, 'utf-8'), bytes(message, 'utf-8'), hashlib.sha256)
sign_hex = hasher.hexdigest()
sign_base64 = base64.b64encode(hasher.digest()).decode()
print(sign_base64)
except Exception as e:
print(e)
标签:__,hasher,java,python,sign,import,message,sha256,hmac
From: https://www.cnblogs.com/guanchaoguo/p/17428638.html