python php javascript sha256 带密钥

先用 sha256 得到 二进制数据,然后使用 base64 对 二进制数据编码。

使用以下的代码,3 种语言加密的结果是一样的。有利于平台之间的一致性。

Python


    def hash_key(self, msg, secret='2021'):
        import hmac
        import hashlib
        import base64

        dig = hmac.new(bytes(secret.encode()), msg=msg.encode(), digestmod=hashlib.sha256).digest()
        return base64.b64encode(dig).decode()



PHP

参考:

https://www.php.net/manual/zh/function.hash-hmac.php


    function hash_key($secret, $content)
    {
        $hash = hash_hmac('sha256', $content, $secret, true);
        return base64_encode($hash);
    }



Javascript

参考:

https://www.npmjs.com/package/js-sha256


function arrayBufferToBase64( buffer ) {
    let binary = '';
    const bytes = new Uint8Array( buffer );
    const len = bytes.byteLength;
    for (let i = 0; i < len; i ++) {
      binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

function hash_key(secret, content) {
        
    var hash = sha256.hmac.create(secret)
    hash.update(content)
    return arrayBufferToBase64(hash.digest())

}

var secret = '2021';
var content = 'LSL701T0B0B9J00228';

var key = hash_key(secret, content)
console.log(key)



深度学习推荐
深度学习推荐

墨之科技,版权所有 © Copyright 2017-2027

湘ICP备14012786号     邮箱:ai@inksci.com