问题描述
使用gmssl(python版本)进行SM4加/解密时结果与国标(GMT0002)不符,或解密失败,原因是gmssl默认使用PKCS7填充,国标文档里的样例是没有填充的。
解决方法
方法一:创建CryptSM4对象时将填充模式设为-1。这是笔者推荐的方法。
方法二:使用CryptSM4.one_round。这是个底层函数,每次只能加/解密一个分组。
例程
from gmssl import sm4, func
g_sData = '0123456789abcdeffedcba9876543210'
g_sKey = '0123456789abcdeffedcba9876543210'
def main():
bufData = bytes.fromhex(g_sData)
bufKey = bytes.fromhex(g_sKey)
oSM4 = sm4.CryptSM4()
oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
r = oSM4.crypt_ecb(bufData)
print(f'enc:{r.hex()}')
oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, sm4.PKCS7)
oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
r = oSM4.crypt_ecb(bufData)
print(f'enc:{r.hex()}')
oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, sm4.ZERO)
oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
r = oSM4.crypt_ecb(bufData)
print(f'enc:{r.hex()}')
oSM4 = sm4.CryptSM4(sm4.SM4_ENCRYPT, -1) # 方法1
oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
r = oSM4.crypt_ecb(bufData)
print(f'enc:{r.hex()}')
oSM4.set_key(bufKey, sm4.SM4_DECRYPT)
r = oSM4.crypt_ecb(r)
print(f'dec:{r.hex()}')
oSM4 = sm4.CryptSM4() # 方法2
oSM4.set_key(bufKey, sm4.SM4_ENCRYPT)
r = oSM4.one_round(oSM4.sk, bufData)
r = func.list_to_bytes(r)
print(f'enc:{r.hex()}')
oSM4.set_key(bufKey, sm4.SM4_DECRYPT)
#r = func.bytes_to_list(r)
r = oSM4.one_round(oSM4.sk, r)
r = func.list_to_bytes(r)
print(f'dec:{r.hex()}')
return
if __name__ == '__main__':
main()
例程输出:
enc:681edf34d206965e86b3e94f536e4246002a8a4efa863ccad024ac0300bb40d2
enc:681edf34d206965e86b3e94f536e4246002a8a4efa863ccad024ac0300bb40d2
enc:681edf34d206965e86b3e94f536e42462677f46b09c122cc975533105bd4a22a
enc:681edf34d206965e86b3e94f536e4246
dec:0123456789abcdeffedcba9876543210
enc:681edf34d206965e86b3e94f536e4246
dec:0123456789abcdeffedcba9876543210
注意事项
sm4.ZERO是一个名字叫“ZERO”的填充模式,不是不填充。
------完------