Base64 URL编码失败

时间:2019-06-03 15:03:01

标签: python base64

我这里有一个小程序,试图为网站(流放被动树路径)生成特定的哈希值。

这是我的代码:

####### ByteEncoder.py (This is a python convert from the official js code )

class ByteEncoder:
  def __init__(self):
    self.dataString = ""

  def intToBytes(self, t, n=4):
    t = int(t)

    i = [None] * n
    s = n - 1
    while True:
      i[s] = 255 & t
      t = t>>8
      s -= 1
      if s < 0:
        break

    return i

  def appendInt(self, t, n):
    i = self.intToBytes(t,n)
    for r in range(0, n):
      self.dataString += chr(i[r])

  def appendInt8(self, t):
    self.appendInt(t, 1)

  def appendInt16(self, t):
    self.appendInt(t, 2)

  def getDataString(self):
    return self.dataString

##### main.py

hashes = [465, 45035]

encoder = ByteEncoder()

encoder.appendInt(4,4) # Tree Version
encoder.appendInt8(2) # Class ID
encoder.appendInt8(0) # Ascendency class
encoder.appendInt8(1) # Fullscreen

for h in hashes:
  encoder.appendInt16(h)

d = str(base64.b64encode(bytes(encoder.getDataString(),encoding='utf8')))

d = d.replace("+", "-").replace("/", "_")

print(d)

我得到哈希AAAABAIAAQHDkcKvw6s =,但我应该得到AAAABAIAAQHRr-s =

有人可以告诉我为什么吗?

如果您想测试一下

我想要什么: https://www.pathofexile.com/fullscreen-passive-skill-tree/3.6.6/AAAABAIAAQHRr-s=

我得到的是: https://www.pathofexile.com/fullscreen-passive-skill-tree/3.6.6/AAAABAIAAQHDkcKvw6s=

以下是Victor 的评论中的答案。 只需使用base64.urlsafe_b64encode()

1 个答案:

答案 0 :(得分:0)

您将文本字符串当作字节来对待,然后使用utf-8对其进行编码,这是一种多字节编码。

如果您需要“透明”的文本到字节编码,请使用“ latin-1”。 但是,在此代码中,您不应该一直使用文本字符串(“ str”)作为开头。它还可以简化事情,因为您可以将整数直接连接到数据中,而不用逐字节转换:

...
class ByteEncoder:
  def __init__(self):
    self.data = bytes()

  ...

  def appendInt(self, t, n):
    i = self.intToBytes(t,n)
    self.data += i

...
# Also,in Python, there is no sense in writting a  "getter" to
# just return an attribute as it is - no need for an equivalent
# of your `.getDataString` method:

d = str(base64.b64encode(encoder.data))