AttributeError: module 'cryptography.hazmat.primitives.ciphers.algorithms' has no attribute 'RSAEncryption'
时间: 2024-08-30 19:00:15 浏览: 187
出现这个错误是因为您尝试在`cryptography.hazmat.primitives.ciphers.algorithms`模块中查找名为`RSAEncryption`的属性,但在该模块中实际上没有这样的属性。`RSAEncryption`应该属于`asymmetric`子模块下的`rsa`模块,用于表示RSA算法而不是用于直接加密/解密操作。
在`cryptography`库中,如果要用到RSA的加密功能,应该使用`cryptography.hazmat.primitives.asymmetric.rsa`模块,而不是`ciphers`模块。以下是用`cryptography`进行RSA加密的正确代码示例:
```python
from cryptography.hazmat.primitives.asymmetric import rsa, padding, serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
# ...假设已经加载了公钥和私钥
public_key = ...
private_key = ...
def encrypt_rsa(public_key, message):
message_bytes = message.encode('utf-8')
encrypter = public_key.encryptor()
if isinstance(encrypter, rsa.RSAPublicKeyEncryptionWithPadding): # 对于RSA公钥
encrypted_data = encrypter.encrypt(message_bytes, asymmetric_padding.OAEP(mgf=asymmetric_padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256()))
else:
raise ValueError("Invalid public key type for RSA encryption.")
return encrypted_data
# 实际调用
try:
encrypted_message = encrypt_rsa(public_key, "Hello, RSA!")
except Exception as e:
print(f"Error occurred: {str(e)}")
```
确保导入正确的模块和方法,否则可能会导致`AttributeError`。
阅读全文