使用python

时间:2019-01-22 22:49:47

标签: javascript python cryptography hmac cryptojs

这种情况是,我有一个JS脚本为用户提供的输入创建HMAC,并且我想使用python为相同的输入计算相同的HMAC。为了使事情更清楚,请考虑以下JS和Python代码段。

JavaScript

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac-sha256.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/enc-base64.min.js"></script>

<script>
    var secretAccessKey = "bAvW5O18eSrxke4I7eFcrnrDJkN+wKQmx9aSHuMZQ0w=";
    var stringtoSign = "Test";

    // Generate HMAC SHA256 signature
    var secretAccessKeyBase64 = CryptoJS.enc.Base64.parse(secretAccessKey);
    var hash = CryptoJS.HmacSHA256(stringtoSign, secretAccessKeyBase64);
    var signature = CryptoJS.enc.Base64.stringify(hash);
</script>

Python

stringToSign = "Test"
secretAccessKey = "bAvW5O18eSrxke4I7eFcrnrDJkN+wKQmx9aSHuMZQ0w="

secretAccessKeyBase64 = base64.b64decode(secretAccessKey).hex()
keyBytes = bytes(secretAccessKeyBase64, 'utf-8')
stringToSignBytes = bytes(stringToSign, 'utf-8')
signatureHash = hmac.new(keyBytes, stringToSignBytes, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(signatureHash)
print(signature)

Javascript代码给我 b + 1wRzDODA85vyDZkXByPIKO5qmnjCRNF5gZFi33 / Ic = ,而python给我值 b'SsZ4bcYe3op1nGU6bySzlSc9kgg9Kgp37qzF15s2zN>

为什么我的python代码为(似乎)提供给JS脚本的相同输入生成一个不同的HMAC?无论如何,要使用python获取JS代码输出的HMAC值?

1 个答案:

答案 0 :(得分:1)

您在Javascript中使用Base64编码值作为机密,而在Python中,您使用纯文本机密。

<script>
    var secretAccessKeyBase64 = "secret";
    var hash = CryptoJS.HmacSHA256("Message", secretAccessKeyBase64);
    var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
    document.write(hashInBase64);
</script>

这将输出与Python代码相同的值:

qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=

编辑:

base64返回一个字节对象,无需将其转换为hex()

stringToSign = "Test"
secretAccessKey = "bAvW5O18eSrxke4I7eFcrnrDJkN+wKQmx9aSHuMZQ0w="

secretAccessKeyBase64 = base64.b64decode(secretAccessKey)
keyBytes = secretAccessKeyBase64
stringToSignBytes = bytes(stringToSign, 'utf-8')

signatureHash = hmac.new(keyBytes, stringToSignBytes, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(signatureHash)
print(signature)

正确打印:

b'b+1wRzDODA85vyDZkXByPIKO5qmnjCRNF5gZFi33/Ic='