AttributeError: module 'gmssl.sm2' has no attribute 'encrypt'怎么解决
时间: 2023-06-21 19:18:52 浏览: 61
这个错误可能是因为 gmssl 库版本更新导致的,最新版本的 gmssl 库中,SM2 加密和解密的接口已经变更。下面是一个基于 gmssl 3.3.1 版本的 Python SM2 加密脚本,可以尝试使用该版本的 gmssl 库来运行:
```python
from binascii import hexlify, unhexlify
from gmssl import sm2, func
# 生成 SM2 密钥对
private_key = sm2.generate_private_key()
public_key = sm2.get_public_key(private_key)
# 显示密钥对
print('私钥:', hexlify(private_key).decode('utf-8'))
print('公钥:', hexlify(public_key).decode('utf-8'))
# 明文
message = b'Hello, SM2!'
# 加密
ciphertext, cipher_params = sm2.crypt_and_mac(public_key, message)
# 显示加密后的密文和参数
print('加密后的密文:', hexlify(ciphertext).decode('utf-8'))
print('加密参数:', hexlify(cipher_params).decode('utf-8'))
# 解密
decrypted_message = sm2.decrypt_and_verify(private_key, ciphertext, cipher_params)
# 显示解密后的明文
print('解密后的明文:', decrypted_message.decode('utf-8'))
```
该脚本使用 gmssl 库的 `crypt_and_mac` 方法实现 SM2 加密,使用 `decrypt_and_verify` 方法实现 SM2 解密。如果运行仍然出现问题,可以尝试更新 gmssl 库到最新版本。