国密SM4 python
时间: 2023-07-06 20:33:58 浏览: 79
要在Python中使用国密SM4算法,可以使用第三方库pycryptodome。在使用前需要先安装该库,可以通过以下命令进行安装:
```
pip install pycryptodome
```
下面是一个简单的示例代码,用于对字符串进行加解密:
```python
from Crypto.Cipher import SM4
# 加密函数
def encrypt(key, plaintext):
cipher = SM4.new(key)
ciphertext = cipher.encrypt(plaintext.encode())
return ciphertext.hex()
# 解密函数
def decrypt(key, ciphertext):
cipher = SM4.new(key)
plaintext = cipher.decrypt(bytes.fromhex(ciphertext)).decode()
return plaintext
# 测试代码
key = bytes.fromhex('0123456789abcdeffedcba9876543210')
plaintext = 'Hello, world!'
ciphertext = encrypt(key, plaintext)
print('Ciphertext:', ciphertext)
decrypted = decrypt(key, ciphertext)
print('Decrypted:', decrypted)
```
在上面的示例代码中,`encrypt`函数用于加密字符串,`decrypt`函数用于解密密文。`key`参数是一个16字节的密钥,`plaintext`参数是要加密的明文字符串,`ciphertext`参数是要解密的密文字符串。加密后的密文和解密后的明文都是16字节的十六进制字符串。
需要注意的是,pycryptodome库中的SM4算法实现是基于C语言的,因此加解密速度非常快,但是需要注意内存使用情况。
相关推荐
![go](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)