python 爬虫 AES加密 网站
时间: 2024-12-29 13:20:33 浏览: 49
### Python 爬虫 AES 加密解决方案
对于涉及 AES 加密的网站,Python 提供了多种方法来进行加密和解密操作。下面是一个完整的示例代码,展示了如何使用 `pycryptodome` 库来处理 AES 加密。
#### 安装依赖库
首先需要安装必要的库:
```bash
pip install pycryptodome requests
```
#### AES 加密与解密实例
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
def aes_encrypt(data, key):
"""
使用给定的密钥对数据进行 AES ECB 模式的加密
参数:
data (bytes): 需要加密的数据
key (bytes): AES 密钥
返回:
str: 经过 Base64 编码后的加密字符串
"""
cipher = AES.new(key, AES.MODE_ECB)
padded_data = pad(data, AES.block_size)
encrypted_bytes = cipher.encrypt(padded_data)
return base64.b64encode(encrypted_bytes).decode('utf-8')
def aes_decrypt(encrypted_base64_str, key):
"""
对经过 Base64 编码并由 AES ECB 模式加密过的字符串进行解密
参数:
encrypted_base64_str (str): 已经被 Base64 编码且 AES 加密的字符串
key (bytes): AES 密钥
返回:
bytes: 原始未加密的数据
"""
cipher = AES.new(key, AES.MODE_ECB)
encrypted_bytes = base64.b64decode(encrypted_base64_str.encode('utf-8'))
decrypted_padded_data = cipher.decrypt(encrypted_bytes)
return unpad(decrypted_padded_data, AES.block_size)
# 测试用例
if __name__ == "__main__":
test_key = b'16bytekey12345678'
original_text = "Hello World!"
# 加密过程
encrypted_message = aes_encrypt(original_text.encode(), test_key)
print(f"Encrypted message: {encrypted_message}")
# 解密过程
decrypted_message = aes_decrypt(encrypted_message, test_key).decode()
print(f"Decrypted message: {decrypted_message}")
```
这段代码实现了基本的 AES 加密和解密功能[^3]。当面对实际项目时,可能还需要考虑更多细节,比如获取动态变化的密钥、IV(初始化向量)等参数,这取决于目标站点的具体实现方式。
阅读全文
相关推荐


















