pythonSM4加密

 数据安全法及密评要求,敏感数据系统需要使用国密算法进行加解密处理。

敏感数使用SM4/ECB加解密方式

#密钥参数epidemic_key
#加密信息参数 message
#加密算法SM4/ECB/PKCS5Padding
#加密类型SM4-ECB
#添加模式PKCS5Padding

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import binascii

def sm4_encrypt_ecb(data, key):
    cipher = Cipher(algorithms.SM4(binascii.unhexlify(key)), modes.ECB(), backend=default_backend())
    encryptor = cipher.encryptor()

    # Use PKCS7 padding
    data_bytes = data.encode('utf-8')
    padded_data = data_bytes + bytes([16 - len(data_bytes) % 16] * (16 - len(data_bytes) % 16))

    ciphertext = encryptor.update(padded_data) + encryptor.finalize()
    return binascii.hexlify(ciphertext).decode('utf-8')


def sm4_decrypt_ecb(ciphertext, key):
    cipher = Cipher(algorithms.SM4(binascii.unhexlify(key)), modes.ECB(), backend=default_backend())
    decryptor = cipher.decryptor()

    decrypted_data = decryptor.update(binascii.unhexlify(ciphertext)) + decryptor.finalize()

    # Remove PKCS7 padding
    return decrypted_data.rstrip(b'\x00').decode('utf-8')


def main():
    epidemic_key = "c6551e2504d123027f7729dd968454f6"
    message = "123"

    encrypted_message = sm4_encrypt_ecb(message, epidemic_key)
    print(f"Original Message: {message}")
    print(f"Encrypted Message: {encrypted_message}")

    decrypted_message = sm4_decrypt_ecb(encrypted_message, epidemic_key)
    print(f"Decrypted Message: {decrypted_message}")


if __name__ == "__main__":
    main()


账户口令加密采用SM3进行hash 

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
import hashlib
def sm3_hash(data):
    digest = hashes.Hash(hashes.SM3(), backend=default_backend())
    digest.update(data.encode('utf-8'))
    return digest.finalize()
def main1():
    message = "闫三"
    hash_value = sm3_hash(message).hex()
    print(f"Message: {message}")
    print(f"SM3 Hash: {hash_value}")

def md5_hash(data):
    md5 = hashlib.md5()
    md5.update(data.encode('utf-8'))
    return md5.hexdigest()
def main():
    message = "123456"
    hash_value = md5_hash(message)
    print(f"Message: {message}")
    print(f"MD5 Hash: {hash_value}")
if __name__ == "__main__":
    main1()
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值