sm2格式数字信封加解密详解

sm2格式数字信封

0、参考链接

密码行业标准化技术委员会
	http://www.gmbz.org.cn/main/bzlb.html
SM2密码算法使用规范
	http://www.gmbz.org.cn/main/viewfile/2018011001400692565.html
SM2密码算法应用分析
	https://blog.youkuaiyun.com/arlaichin/article/details/23708155?utm_source=itdadao&utm_medium=referral
技术科普 | 国密算法在Ultrain区块链中的运用 
	https://blog.youkuaiyun.com/Tramp_1/article/details/111603396

1、sm2数字信封格式:

有效部分
公钥:04|X|Y,共65字节
私钥:整数,共32字节
SM2EnvelopedKey ::= SEQUENCE {
   
    symalgid        AlgorithmIdentifier,        -- 对称算法ID
    symalgkey       SM2Cipher,                  -- 对称算法密钥(被签名证书公钥加密)
    asympubkey      BIT STRING,                 -- 加密证书公钥
    asymprvkey      BIT STRING                  -- 加密证书私钥(被对称算法加密)
}
typedef struct SM2Cipher_st {
   
    ASN1_INTEGER *xCoordinate;                                // x分量(随机,非公钥)
    ASN1_INTEGER *yCoordinate;                                // y分量(随机,非公钥)
    ASN1_OCTET_STRING *hash;                                  // 杂凑值
    ASN1_OCTET_STRING *cipherText;                            // 密文
} SM2Cipher;
AlgorithmIdentifier ::= SEQUENCE {
   
    algorithm       OBJECT IDENTIFIER,
    parameters      ANY DEFINED BY algorithm OPTIONAL
}

区分普通的数字信封格式,见下图(openssl暂不支持sm2算法的私钥p7信封格式生成,但是支持sm2算法私钥的p7解密,生成p7可以在外部使用gmssl命令行生成)
typedef struct pkcs7_enveloped_st {
   
    ASN1_INTEGER *version;      /* version 0 */
    STACK_OF(PKCS7_RECIP_INFO) *recipientinfo
实现SM2数字签名,加和解需要使用SM2算法库,可以使用Python的第三方库pycryptodome或gmssl。以下是使用pycryptodome实现SM2数字签名,加和解的示例代码: 1. SM2数字签名 ```python from Crypto.PublicKey import ECC from Crypto.Signature import DSS from Crypto.Hash import SHA256 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from binascii import b2a_hex, a2b_hex # 生成SM2钥对 private_key = ECC.generate(curve='sm2') public_key = private_key.public_key() # 待签名数据 data = b'hello, world' # 计算消息摘要 digest = SHA256.new(data) # 对消息摘要进行数字签名 signer = DSS.new(private_key, 'fips-186-3') signature = signer.sign(digest) # 验证数字签名 verifier = DSS.new(public_key, 'fips-186-3') try: verifier.verify(digest, signature) print("Signature is valid.") except ValueError: print("Signature is invalid.") ``` 2. SM2和解 ```python from Crypto.Cipher import SM2Cipher from Crypto.PublicKey import ECC from Crypto.Util.Padding import pad, unpad from binascii import b2a_hex, a2b_hex # 生成SM2钥对 private_key = ECC.generate(curve='sm2') public_key = private_key.public_key() # 加数据 plaintext = b'hello, world' cipher = SM2Cipher.new(public_key) ciphertext = cipher.encrypt(plaintext) # 解数据 cipher = SM2Cipher.new(private_key) decrypttext = cipher.decrypt(ciphertext) print("Plaintext:", plaintext) print("Ciphertext:", b2a_hex(ciphertext)) print("Decrypttext:", decrypttext) ``` 注意,以上代码只是示例,实际使用时需要注意安全性和数据格式转换等问题。
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值