如何用Python解密CryptoJS RC4Drop加密的数据?
问题:用Python实现CryptoJS RC4Drop的解密功能
现有一段Node.js代码,使用CryptoJS的RC4Drop算法(drop参数为3072/4=768)实现加密解密,运行正常。需要用Python实现对应的解密功能,解密Node.js加密的数据。以下是相关代码及示例:
Node.js 加密解密代码
encryptData(data) { try { var encryptionKey = CryptoJS.enc.Utf8.parse("SecretKey"); return CryptoJS.RC4Drop.encrypt(JSON.stringify(data), encryptionKey, { drop: 3072 / 4 }).toString(); } catch (error) { console.error(error); } }, decryptData(encrypted) { try { var encryptionKey = CryptoJS.enc.Utf8.parse("SecretKey"); const plainPass = CryptoJS.RC4Drop.decrypt(encrypted, encryptionKey, { drop: 3072 / 4 }).toString(CryptoJS.enc.Utf8); return plainPass; } catch (error) { console.error(error); } },
尝试的错误Python代码
def rc4_drop(key, data, drop_bytes): # RC4 Encryption/Decryption cipher = ARC4.new(key) decrypted = cipher.decrypt(data) # Apply drop functionality if drop_bytes < len(decrypted): return decrypted[drop_bytes:] else: return b'' def decrypt_data(encrypted_base64, key, drop_bytes): try: # Convert Base64-encoded encrypted data to bytes encrypted_bytes = base64.b64decode(encrypted_base64) print("Encrypted bytes:", encrypted_bytes) # Convert the key to bytes key_bytes = key.encode('utf-8') print("Key bytes:", key_bytes) # Decrypt data with RC4 and apply drop bytes plaintext_bytes = rc4_drop(key_bytes, encrypted_bytes, drop_bytes) print("Plaintext bytes after dropping:", plaintext_bytes) # Convert bytes to string return plaintext_bytes.decode('utf-8') if plaintext_bytes else '' except Exception as e: print(f"An error occurred: {e}") return None
示例:Node.js加密字符串"Hello"得到Base64输出RlxFVdR/FA==。
正确的Python解密实现
错误原因分析
核心错误是对RC4Drop逻辑的误解:RC4Drop不是解密后截断数据,而是初始化RC4密钥流后,先丢弃前drop个字节,再用剩余的密钥流对密文进行异或解密。
实现代码
依赖pycryptodome库(先安装:pip install pycryptodome):
import base64 from Crypto.Cipher import ARC4 def rc4_drop_decrypt(key, encrypted_data, drop_bytes): # 初始化RC4密码器 cipher = ARC4.new(key) # 先丢弃前drop_bytes个密钥流字节 cipher.decrypt(b'\x00' * drop_bytes) # 用剩余的密钥流解密数据 return cipher.decrypt(encrypted_data) def decrypt_data(encrypted_base64, key, drop_bytes): try: # 解码Base64密文 encrypted_bytes = base64.b64decode(encrypted_base64) # 转换密钥为字节 key_bytes = key.encode('utf-8') # 执行RC4Drop解密 plaintext_bytes = rc4_drop_decrypt(key_bytes, encrypted_bytes, drop_bytes) # 转换为UTF-8字符串 return plaintext_bytes.decode('utf-8') except Exception as e: print(f"解密错误: {e}") return None # 测试示例 if __name__ == "__main__": encrypted_base64 = "RlxFVdR/FA==" key = "SecretKey" drop_bytes = int(3072 / 4) # 768 result = decrypt_data(encrypted_base64, key, drop_bytes) print("解密结果:", result) # 输出: "Hello"
代码说明
- 初始化ARC4密码器后,调用
decrypt(b'\x00' * drop_bytes):生成并丢弃前drop_bytes个密钥流字节,模拟CryptoJS RC4Drop的drop参数逻辑。 - 用同一个密码器解密实际密文,此时使用的是丢弃初始字节后的密钥流,与CryptoJS逻辑完全一致。
内容的提问来源于stack exchange,提问作者Vijay Mulani
相关产品推荐
相关产品推荐

