尝试使用时间戳和base64编码的json字符串创建哈希,获取内存错误

2024-05-14 00:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

这个简单的脚本由于内存错误而死亡,我不知道为什么

import simplejson as json
import hmac
import hashlib
from time import time
import base64
sso_user={'a':'foo','b':'bar'}
ssoKey=b'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
timestamp = round(time() * 1000)
s=json.dumps(sso_user)
userDataJSONBase64 = base64.b64encode(s.encode())
verificationHash = hmac.new(
    bytes(timestamp)+userDataJSONBase64,
    ssoKey,
    hashlib.sha256
).hexdigest()
print(verificationHash)

它被hmac噎住了。新的()


Tags: 内存import脚本jsontime错误hmactimestamp
2条回答

我做了这个改变,似乎已经解决了这个问题

verificationHash = hmac.new(
      str(timestamp).encode() + userDataJSONBase64,
      ssoKey,
      hashlib.sha256
  ).hexdigest()

问题是您使用的^{} built-in in python3与python2中的行为不同。在python2.7中,bytesstr的别名。在python3中,接受整数的构造函数生成一个n0数组。由于您传入了类似于1,617,219,736,292(2021年3月31日)的内容,因此您正在初始化一个大小为1.6万亿的数组并耗尽内存:MemoryError

$ python2
>>> print(bytes.__doc__)
str(object='') -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
^C
$ python3
>>> print(bytes.__doc__)
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - any object implementing the buffer API.
  - an integer

相关问题 更多 >