数据安全法及密评要求,敏感数据系统需要使用国密算法进行加解密处理。
敏感数使用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()