电报护照数据解密(Python)

时间:2018-08-01 13:07:19

标签: python telegram telegram-bot

使用https://core.telegram.org/passport#decrypting-data,我想出了以下功能:

import hashlib
from base64 import b64decode
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES


def decode_credentials(credentials):
    data_encrypted = b64decode(credentials['data'])
    credentials_hash = b64decode(credentials['hash'])
    secret_encrypted = b64decode(credentials['secret'])

    with open(f"private.key", "r") as f:
        private_key = RSA.importKey(f.read())

    secret_decrypted = private_key.decrypt(secret_encrypted)
    secret_hash = hashlib.sha512(secret_decrypted + credentials_hash).digest()
    aes_key = secret_hash[:32]
    aes_iv = secret_hash[32:48]

    aes = AES.new(aes_key, AES.MODE_CBC, aes_iv)
    data_decrypted = aes.decrypt(data_encrypted)
    data_decrypted_hash = hashlib.sha256(data_decrypted).digest()

    if data_decrypted_hash != credentials_hash:
        raise Exception("HASH MISMATCH")

    return data_decrypted[data_decrypted[0]:]

以下代码总是为我带来HASH MISMATCH,因此出现了一个问题:代码有什么问题?

有人能提出他们可以共享的可行解决方案吗?

1 个答案:

答案 0 :(得分:0)

问题出在以下几行:

with open(f"private.key", "r") as f:
    private_key = RSA.importKey(f.read())

secret_decrypted = private_key.decrypt(secret_encrypted)

我不知道区别,但是正确的是:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP

with open(f"private.key", "rb") as f:
    private_key = serialization.load_pem_private_key(
        f.read(),
        password=None,
        backend=default_backend(),
    )

secret_decrypted = private_key.decrypt(
    secret_encrypted,
    OAEP(
        mgf=MGF1(algorithm=SHA1(), ),
        algorithm=SHA1(),
        label=None,
    )
)

https://github.com/python-telegram-bot/python-telegram-bot/commit/a09394b218d3ae05dc1a1f74e782c701283fb82b#diff-eaefd62d25b87433b035868713d3437aR39找到了解决方案。

如果有人会向我解释我的错误,还是很感激。