用python实现sm4算法
时间: 2024-02-21 21:54:36 浏览: 99
SecurityBoot.zip_AES_SHA256_python aes rsa sm2_sm2_sm4
以下是使用Python实现SM4算法的示例代码:
```python
from Crypto.Cipher import SM4
from Crypto.Util.Padding import pad, unpad
from binascii import b2a_hex, a2b_hex
def sm4_encrypt(key, plaintext):
cipher = SM4.new(key, SM4.MODE_ECB)
padded_plaintext = pad(plaintext.encode(), SM4.block_size)
ciphertext = cipher.encrypt(padded_plaintext)
return b2a_hex(ciphertext).decode()
def sm4_decrypt(key, ciphertext):
cipher = SM4.new(key, SM4.MODE_ECB)
padded_plaintext = cipher.decrypt(a2b_hex(ciphertext))
plaintext = unpad(padded_plaintext, SM4.block_size)
return plaintext.decode()
# 示例用法
key = b'0123456789abcdef' # 16字节的密钥
plaintext = 'Hello, World!'
ciphertext = sm4_encrypt(key, plaintext)
decrypted_text = sm4_decrypt(key, ciphertext)
print("加密结果:", ciphertext)
print("解密结果:", decrypted_text)
```
阅读全文