Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python2 的解密函数 #76

Closed
ddcatgg opened this issue Aug 4, 2024 · 1 comment
Closed

Python2 的解密函数 #76

ddcatgg opened this issue Aug 4, 2024 · 1 comment

Comments

@ddcatgg
Copy link

ddcatgg commented Aug 4, 2024

首页的 PyCookieCloud 是基于 Python3 的,因此如果有人还在使用 Python2 环境,可以通过下面的 decrypt_cryptojs_aes 函数进行解密(由 ChatGPT 参考首页的 go语言实现,略作修改):

# -*- coding: utf-8 -*-
import base64
import hashlib

import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

PKCS5_SALT_LEN = 8


def bytes_to_key(salt, data, hash_type, key_len, block_len):
    salt_len = len(salt)
    if salt_len > 0 and salt_len != PKCS5_SALT_LEN:
        raise ValueError('Salt length is %d, expected %d' % (salt_len, PKCS5_SALT_LEN))

    concat = b''
    last_hash = b''
    total_len = key_len + block_len

    while len(concat) < total_len:
        h = hashlib.new(hash_type)
        h.update(last_hash + data + salt)
        last_hash = h.digest()
        concat += last_hash

    return concat[:key_len], concat[key_len:total_len]


def decrypt_cryptojs_aes(password, ciphertext):
    raw_encrypted = base64.b64decode(ciphertext)
    if len(raw_encrypted) < 16 or raw_encrypted[:8] != b'Salted__':
        raise ValueError('Invalid ciphertext')

    salt = raw_encrypted[8:16]
    encrypted = raw_encrypted[16:]

    key, iv = bytes_to_key(salt, password.encode('utf-8'), 'md5', 32, 16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = cipher.decrypt(encrypted)
    try:
        return unpad(decrypted, AES.block_size).decode('utf-8')
    except ValueError:
        raise ValueError('Incorrect password or corrupted data')


def main():
    uuid = 'xxxx'
    password = 'yyyy'

    url = 'http://your_server:8088/get/%s' % uuid
    d = requests.get(url).json()
    ciphertext = d['encrypted']

    key_password = hashlib.md5('-'.join([uuid, password])).hexdigest()[:16]
    decrypted = decrypt_cryptojs_aes(key_password, ciphertext)
    print(decrypted)


if __name__ == '__main__':
    main()

测试通过的软件版本:
Python:2.7
pycryptodome:3.20.0
requests:2.27.1

@easychen
Copy link
Owner

easychen commented Aug 4, 2024

感谢分享,已添加到首页。

@easychen easychen closed this as completed Aug 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants