import gmssl.sm2
class SM2Crypto:
def __init__(self, private_key=None, public_key=None):
self.sm2 = gmssl.sm2.CryptSM2(private_key=private_key, public_key=public_key)
def generate_keys(self):
self.sm2.generate_key()
return self.sm2.get_private_key(), self.sm2.get_public_key()
def encrypt(self, data):
encrypted_data = self.sm2.encrypt(data)
return encrypted_data
def decrypt(self, encrypted_data):
decrypted_data = self.sm2.decrypt(encrypted_data)
return decrypted_data
if __name__ == '__main__':
sm2_crypto = SM2Crypto()
private_key, public_key = sm2_crypto.generate_keys()
sm2_crypto = SM2Crypto(public_key=public_key)
# 加密数据
original_data = b'Hello, World!'
encrypted_data = sm2_crypto.encrypt(original_data)
print('Encrypted:', encrypted_data.hex())
# 使用私钥解密数据
sm2_crypto = SM2Crypto(private_key=private_key)
decrypted_data = sm2_crypto.decrypt(encrypted_data)
print('Decrypted:', decrypted_data)
03-11
890
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-03