-->
当前位置:首页 > DayDayUp > 正文内容

国密密码及python实现

Luz10个月前 (10-06)DayDayUp1475

国密密码,也称为***商用密码,是***政府和相关机构推广的一组密码算法标准,用于保护国家敏感信息和数据的安全性。以下是一些常见的国密密码及其特点:

SM1(商用密码算法)

对称加密算法。

适用于加密数据。

曾被认为不够安全,后来被SM4替代。


SM2(椭圆曲线数字签名算法)

基于椭圆曲线密码学。

用于数字签名和密钥交换。

具有高度的安全性和效率。

适用于非对称加密。

签名验证:

from Crypto.PublicKey import ECC
from Crypto.Signature import DSS
# 生成SM2密钥对
private_key = ECC.generate(curve='SM2')
public_key = private_key.public_key()
# 签名和验证签名
message = b"Hello, World!"
signer = DSS.new(private_key, 'fips-186-3')
signature = signer.sign(message)
verifier = DSS.new(public_key, 'fips-186-3')
try:
    verifier.verify(message, signature)
    print("Signature is valid.")
except ValueError:
    print("Signature is not valid.")

非对称加解密

from Crypto.PublicKey import ECC
from Crypto.Cipher import PKCS1_OAEP
# 生成SM2密钥对
private_key = ECC.generate(curve='SM2')
public_key = private_key.public_key()
# 要加密的消息
plaintext = b"Hello, World!"
# 使用接收方的公钥进行加密
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(plaintext)
print("Encrypted:", ciphertext)
# 使用私钥进行解密
decipher = PKCS1_OAEP.new(private_key)
decrypted = decipher.decrypt(ciphertext)
print("Decrypted:", decrypted)

SM3(密码杂凑算法)

用于数据的消息摘要和哈希。

基于Merkle-Damgard结构。

具有高度的碰撞阻力。

适用于数据完整性验证。

from Crypto.Hash import SM3
data = b"Hello, World!"
hash_object = SM3.new(data)
digest = hash_object.hexdigest()
print("SM3 Hash:", digest)


SM4(分组密码算法)

对称加密算法,类似于AES。

使用128位密钥和分组。

支持电子密码本(ECB)和密码分组链接模式(CBC)等。

适用于数据加密。

from Crypto.Cipher import SM4
key = b"ThisIsASecretKey"  # 128-bit密钥
cipher = SM4.new(key, SM4.MODE_ECB)  # 或者使用SM4.MODE_CBC等模式
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(plaintext)
print("SM4 Encrypted:", ciphertext)
decipher = SM4.new(key, SM4.MODE_ECB)
decrypted = decipher.decrypt(ciphertext)
print("SM4 Decrypted:", decrypted)

SM9(双线性对密码算法)

用于密钥交换和数字签名。

基于双线性对。

具有身份基础的密码功能。

适用于身份验证和密钥管理。

from Crypto.PublicKey import ECC
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import DSS
# 生成SM9密钥对
private_key = ECC.generate(curve='SM9')
public_key = private_key.public_key()
# 要加密的消息
plaintext = b"Hello, World!"
# 使用接收方的公钥进行加密
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(plaintext)
print("Encrypted:", ciphertext)
# 使用私钥进行解密
decipher = PKCS1_OAEP.new(private_key)
decrypted = decipher.decrypt(ciphertext)
print("Decrypted:", decrypted)
# 使用私钥进行数字签名
signer = DSS.new(private_key, 'fips-186-3')
message = b"Hello, digital signature!"
signature = signer.sign(message)
print("Signature:", signature)
# 使用公钥验证数字签名
verifier = DSS.new(public_key, 'fips-186-3')
try:
    verifier.verify(message, signature)
    print("Signature is valid.")
except ValueError:
    print("Signature is not valid.")



发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。