Python 相当于 Node.js Buffer.from('string', 'base64')

发布于 2025-01-09 19:01:48 字数 1925 浏览 0 评论 0原文

我正在尝试基于基于哈希的消息身份验证代码 (HMAC) 加密的授权标头来实现授权。为此,我需要使用授权标头通过使用authenticationToken 的二进制缓冲区重新计算哈希值来验证消息内容的真实性。

有一个 Node.js 代码可以正常工作,并按应有的方式重新计算哈希值:

const { Buffer } = require('buffer')
const crypto = require('crypto')

const verifyAuthorizationTokenHTTP = () => {
  const authenticationToken = 'string-token'
  const authenticationTokenBinary = Buffer.from(authenticationToken, 'base64')
  const authHeader = 'B4NmoAWcwqeLVx6ZlfAH26oHhFgpBaBfxmO0TXVsN7k='
  const request_body = 'plain_text_json_like_string'
  const hmac = crypto.createHmac('sha256', authenticationTokenBinary)
  hmac.update(request_body)
  const hashInBase64 = hmac.digest('base64')
  console.log(`result: ${hashInBase64 === authHeader}`)
  return hashInBase64 === authHeader
}

verifyAuthorizationTokenHTTP()

但问题是我需要在 Python 中实现它,但无法使其工作:

import base64
import hmac


def verifyAuthorizationTokenHTTP():
    authenticationToken = 'string-token'
    authenticationToken_bytes = authenticationToken.encode('utf-8')
    authenticationToken_base64 = base64.b64encode(authenticationToken_bytes)
    authHeader = 'B4NmoAWcwqeLVx6ZlfAH26oHhFgpBaBfxmO0TXVsN7k='
    request_body = 'plain_text_json_like_string'
    h = hmac.new(key=authenticationToken_base64, msg=request_body.encode('utf-8'), digestmod="sha256")
    hashInBase64 = base64.b64encode(h.digest())

    print(authHeader == hashInBase64)


if __name__ == '__main__':
    verifyAuthorizationTokenHTTP()

我不确定 base64. b64encode()(或base64.b64decode()codecs.encode()codecs.decode()) Python 相当于 Node.js 中的 Buffer.from('string', 'base64')

我做错了什么?

已解决:

问题是,authenticationToken应该是base64字符串,但JS成功地吃掉了纯字符串而不是base64编码的字符串。

所以 python 中的 bytearray(base64.b64decode('base64_string')) 完全等价于 Buffer.from('base64_string', 'base64')

I'm trying to implement authorization based on a hash-based message authentication code (HMAC)-encrypted authorization header. To do so I need to use the authorization header to verify the authenticity of the message content by recalculating the hash using the binary buffer of the authenticationToken.

There is a Node.js code that works just fine and recalculates the hash as it should:

const { Buffer } = require('buffer')
const crypto = require('crypto')

const verifyAuthorizationTokenHTTP = () => {
  const authenticationToken = 'string-token'
  const authenticationTokenBinary = Buffer.from(authenticationToken, 'base64')
  const authHeader = 'B4NmoAWcwqeLVx6ZlfAH26oHhFgpBaBfxmO0TXVsN7k='
  const request_body = 'plain_text_json_like_string'
  const hmac = crypto.createHmac('sha256', authenticationTokenBinary)
  hmac.update(request_body)
  const hashInBase64 = hmac.digest('base64')
  console.log(`result: ${hashInBase64 === authHeader}`)
  return hashInBase64 === authHeader
}

verifyAuthorizationTokenHTTP()

But thing is that I need to implement it in Python and I can't make it work:

import base64
import hmac


def verifyAuthorizationTokenHTTP():
    authenticationToken = 'string-token'
    authenticationToken_bytes = authenticationToken.encode('utf-8')
    authenticationToken_base64 = base64.b64encode(authenticationToken_bytes)
    authHeader = 'B4NmoAWcwqeLVx6ZlfAH26oHhFgpBaBfxmO0TXVsN7k='
    request_body = 'plain_text_json_like_string'
    h = hmac.new(key=authenticationToken_base64, msg=request_body.encode('utf-8'), digestmod="sha256")
    hashInBase64 = base64.b64encode(h.digest())

    print(authHeader == hashInBase64)


if __name__ == '__main__':
    verifyAuthorizationTokenHTTP()

I'm not sure that base64.b64encode() (or also base64.b64decode(), codecs.encode(), codecs.decode()) in Python is right equivalent of Buffer.from('string', 'base64') in Node.js

What am I doing wrong?

Solved:

The thing was that authenticationToken should be in base64 string but JS successfully eaten plain string instead of base64 encoded one.

So bytearray(base64.b64decode('base64_string')) in python is full equivalent of Buffer.from('base64_string', 'base64')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埋葬我深情 2025-01-16 19:01:48

很高兴看到你自己解决了这个问题。我也想在这里补充一点。

如果它不是 base64ed,请说以下

 echo "console.log(require('crypto').createHmac('sha256', 'nonbase64key').update('password').digest('hex'))" | node

在 python 中等效的 Nodejs 代码是:

python3 -c 'import hashlib;import base64;import hmac;print(hmac.new(b"nonbase64key", "password".encode(), hashlib.sha256).hexdigest())'

等效的 shell 命令是:

echo -n "password" | openssl sha256 -hmac "nonbase64key"

Glad to see that you solved it by yourself. I'd like to add something here, too.

If it's not base64ed, say the following nodejs code

 echo "console.log(require('crypto').createHmac('sha256', 'nonbase64key').update('password').digest('hex'))" | node

it's equivalent in python is:

python3 -c 'import hashlib;import base64;import hmac;print(hmac.new(b"nonbase64key", "password".encode(), hashlib.sha256).hexdigest())'

And the equivalent shell command is:

echo -n "password" | openssl sha256 -hmac "nonbase64key"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文