def sm2_enc(private_key, public_key, data): sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) enc_data = sm2_crypt.encrypt(data) enc_data = func.bytes_to_list(enc_data) enc_data = [hex(i) for i in enc_data] print('encrypt_value:') print('/'.join(enc_data))
def gm_xpub_verify(xpub_str, message_str, signature_str): result = False public_key_str = xpub_str[2:66] + decompress_public_key(xpub_str[:66]) sm2_crypt = sm2.CryptSM2(private_key="", public_key=public_key_str) data = bytes.fromhex(message_str) result = sm2_crypt.verify(signature_str, data) return {"result": result}
def gm_xprv_sign(xprv_str, message_str): sm2_crypt = sm2.CryptSM2(private_key=xprv_str[:64], public_key="") K = random.randint(0, 2**256) K_str = K.to_bytes(32, byteorder='big').hex() data = bytes.fromhex(message_str) sig = sm2_crypt.sign(data, K_str) return {"signature": sig}
def sm2_encrypt_func(self): public_key = self.pubkall_LE.text().strip() if len(public_key) != 128: self.Qmsgbox_show("Error", "Public key len is (%d) HEXs, not 64 bytes" % len(public_key)) return self.result_textEdit.append("SM2 Encrypt Publickey: " + public_key) sm2_crypt = sm2.CryptSM2(private_key="", public_key=public_key) if self.plaintext_hex.text().strip() == "": self.Qmsgbox_show("Error", "Plaintext is null") return sm2_plaintext = bytes().fromhex(self.plaintext_hex.text().strip()) self.result_textEdit.append("Plaintext Hex: " + sm2_plaintext.hex().upper()) enc_data = sm2_crypt.encrypt(sm2_plaintext) self.result_textEdit.append("SM2 Encrypt Result Hex: " + enc_data.hex().upper()) data_c1 = enc_data[0:64] self.result_textEdit.append("SM2 Encrypt Result C1 Hex: " + data_c1.hex().upper()) data_c3 = enc_data[64:96] self.result_textEdit.append("SM2 Encrypt Result C3 Hex: " + data_c3.hex().upper()) data_c2 = enc_data[96:] self.result_textEdit.append("SM2 Encrypt Result C2 Hex: " + data_c2.hex().upper()) self.C1.setText(data_c1.hex().upper()) self.C3.setText(data_c3.hex().upper()) self.C2.setText(data_c2.hex().upper()) self.encrypt_result.setText(enc_data.hex().upper())
def sm2_sign_func(self): private_key = self.privkey.text().strip() if len(private_key) != 64: self.Qmsgbox_show("Error", "Private key len is (%d) HEXs not 32 bytes" % len(private_key)) return self.result_textEdit.append("SM2 Sign Privatekey: " + private_key) sm2_crypt = sm2.CryptSM2(private_key=private_key, public_key="") sm2_msg = self.plaintext_hex.text().strip() if sm2_msg != "": self.result_textEdit.append("SM2 Sign msg: " + sm2_msg) e_hash = self.e_LE.text().strip() if len(e_hash) != 64: self.Qmsgbox_show("Error", "e Hash, len is (%d) HEXs not 32 bytes" % len(e_hash)) return self.result_textEdit.append("SM2 Sign e_hash: " + e_hash) random_hex_str = func.random_hex(sm2_crypt.para_len) self.result_textEdit.append("SM2 Sign Randnumber: " + random_hex_str.upper()) sign = sm2_crypt.sign(bytes().fromhex(e_hash), random_hex_str) self.result_textEdit.append("SM2 Sign Result Hex: " + sign.upper()) data_r = sign[0:64] self.result_textEdit.append("SM2 Sign Result: R Hex: " + data_r.upper()) data_s = sign[64:] self.result_textEdit.append("SM2 Sign Result: S Hex: " + data_s.upper()) self.R.setText(data_r.upper()) self.S.setText(data_s.upper()) self.signature_value.setText(sign.upper())
def get_gm_xpub(xprv_str): private_key_int = int(xprv_str[:64], 16) sm2_crypt = sm2.CryptSM2(private_key=xprv_str[:64], public_key="") public_key_str = sm2_crypt._kg(private_key_int, sm2.default_ecc_table['g']) pc = '0' + str(int(public_key_str[-1], 16) % 2 + 2) xpub_str = pc + public_key_str[:64] + xprv_str[64:] return {"xpub": xpub_str}
def sm2_key_pair_func(self): sm2_crypt = sm2.CryptSM2(private_key="", public_key="") #产生私钥 pvk_str = self.privkey.text().strip() if pvk_str != "": if True != self.is_hex_string(pvk_str): self.privkey.setText(pvk_str[0:len(pvk_str) - 1].upper()) self.Qmsgbox_show("Error", "Please input hex number") return if len(pvk_str) != 64: info = "Length of the private key hex number string is : %d, error !" % (len(pvk_str)) self.Qmsgbox_show("Error", info) return self.privkey.setText(pvk_str.upper()) prvk_hex = pvk_str else: prvk_hex = func.random_hex(sm2_crypt.para_len) self.privkey.setText(prvk_hex.upper()) self.result_textEdit.append("Gen Keypair - private key: " + prvk_hex.upper()) k = int(prvk_hex, 16) #计算公钥 Pubk = sm2_crypt._kg(k, sm2_crypt.ecc_table['g']) self.pubkx_LE.setText(Pubk[0:64].upper()) self.pubky_LE.setText(Pubk[64:len(Pubk)].upper()) self.result_textEdit.append("Gen Keypair - public key: " + Pubk.upper())
def sm2_decrypt_func(self): private_key = self.privkey.text().strip() if len(private_key) != 64: self.Qmsgbox_show("Error", "Private key len is not 32 bytes") return self.result_textEdit.append("SM2 Decrypt Private_key: " + private_key) sm2_crypt = sm2.CryptSM2(private_key=private_key, public_key="") encrypt_str = self.encrypt_result.text().strip() if len(encrypt_str) <= 192: self.Qmsgbox_show( "Error", "Encrypt result length should longer than 96 bytes") return if ((self.is_hex_string(encrypt_str) == False) | (len(encrypt_str) % 2 != 0)): self.Qmsgbox_show("Error", "Encrypt result is not hex string") return enc_data = bytes().fromhex(encrypt_str) dec_data = sm2_crypt.decrypt(enc_data) if dec_data is None: self.decrypt_result.setText("") self.result_textEdit.append("SM2 Decrypt Result: " + "SM2 Decrypt failed !!!") self.Qmsgbox_show("Info", "SM2 Decrypt failed !!!") else: dec_result = bytes(dec_data).hex().upper() self.result_textEdit.append("SM2 Decrypt Result: " + dec_result) self.decrypt_result.setText(dec_result)
def test_sm2(): private_key = '3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8' public_key = '09F9DF311E5421A150DD7D161E4BC5C672179FAD1833FC076BB08FF356F35020CCEA490CE26775A52DC6EA718CC1AA600AED05FBF35E084A6632F6072DA9AD13' sm2_crypt = sm2.CryptSM2( public_key=public_key, private_key=private_key) data = b"111" enc_data = sm2_crypt.encrypt(data) #print("enc_data:%s" % enc_data) #print("enc_data_base64:%s" % base64.b64encode(bytes.fromhex(enc_data))) dec_data = sm2_crypt.decrypt(enc_data) print(b"dec_data:%s" % dec_data) assert data == dec_data print("-----------------test sign and verify---------------") #data from OSCCA spec. SM2 #random_hex_str = func.random_hex(sm2_crypt.para_len) random_hex_str = '59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21' data = 'F0B43E94BA45ACCAACE692ED534382EB17E6AB5A19CE7B31F4486FDFC0D28640' sign = sm2_crypt.sign(data, random_hex_str) print('sign:%s' % sign.upper()) verify = sm2_crypt.verify(sign, data) print('verify:%s' % verify) assert verify
def sm2_verify_func(self): public_key = self.pubkall_LE.text().strip() if len(public_key) != 128: self.Qmsgbox_show("Error", "Public key len is not 64 bytes") return self.result_textEdit.append("SM2 Verify Publickey: " + public_key) sm2_crypt = sm2.CryptSM2(private_key="", public_key=public_key) e_hash = self.e_LE.text().strip() if len(e_hash) != 64: self.Qmsgbox_show("Error", "e Hash, len is not 32 bytes") return if self.is_hex_string(e_hash) == False: self.Qmsgbox_show("Error", "e_hash is not hex string") return self.result_textEdit.append("SM2 Verify e_hash: " + e_hash) sign = self.signature_value.text().strip() if len(sign) != 128: self.Qmsgbox_show("Error", "Signature value, len is not 64 bytes") return if self.is_hex_string(sign) == False: self.Qmsgbox_show("Error", "Sign result is not hex string") return self.result_textEdit.append("SM2 Verify signature: " + sign.upper()) verify = sm2_crypt.verify(sign, bytes().fromhex(e_hash)) if verify == True: self.result_textEdit.append("SM2 Verify Result: True") else: self.result_textEdit.append("SM2 Verify Result: False") self.Qmsgbox_show("Info", "Falied to verify signature!!!")
def SM2(): pri_key = params.get('pri_key') pub_key = params.get('pub_key') action = params.get('action') if not pri_key or not pub_key: help_info_and_exit(-1) sm2_crypt = sm2.CryptSM2(public_key=params.get('pub_key'), private_key=params.get('pri_key')) if action == 'encrypt': origbytes = binascii.unhexlify(params.get('dec_data')) enc_data = sm2_crypt.encrypt(origbytes) output_hex(enc_data) elif action == 'decrypt': encrypt_data = binascii.unhexlify(params.get('enc_data')) dec = sm2_crypt.decrypt(encrypt_data) output_hex(dec) elif action == 'sign': if not params.get('random'): help_info_and_exit(-1) decrypt_data = binascii.unhexlify(params.get('dec_data')) sign = sm2_crypt.sign_with_sm3(decrypt_data, params.get('random')) print(sign) elif action == 'verify': if not params.get('sign'): help_info_and_exit(-1) decrypt_data = binascii.unhexlify(params.get('dec_data')) sign = binascii.unhexlify(params.get('sign')) verify = sm2_crypt.verify_with_sm3(sign, decrypt_data) print(verify)
def sign_transaction_hash(self, transaction_hash, chain_id): hashbyte = bytes(transaction_hash) if self.crypto_type == CRYPTO_TYPE_GM: # gm sign public_key = self.gm_account.keypair.public_key private_key = self.gm_account.keypair.private_key sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) public_key = self.gm_account.keypair.public_key private_key = self.gm_account.keypair.private_key (r, s) = sm2_crypt.sign(hashbyte) v_raw = public_key v = int(v_raw, 16) elif self.crypto_type == CRYPTO_TYPE_ECDSA: # ecdsa sign signature = self.ecdsa_account._key_obj.sign_msg_hash( transaction_hash) (v_raw, r, s) = signature.vrs v = self.to_eth_v(v_raw, chain_id) else: raise BcosException( "when sign transaction, unknown crypto type {}".format( self.crypto_type)) return (v, r, s)
def test_sm2_sign(basic_loop, rand_bytes): for _ in range(basic_loop): msg = rand_bytes(random.randint(1, 64)) prikey, pubkey = sm2.sm2_key_pair_gen() crypto_sm2 = sm2.CryptSM2(private_key=prikey, public_key=pubkey) signed_data = crypto_sm2.sign(msg) assert True == crypto_sm2.verify(signed_data, msg)
def test_gmaccount_spec(): privkey = "82dcd33c98a23d5d06f9331554e14ab4044a1d71b169b7a38b61c214f0690f80" account = GM_Account() account.from_key(privkey) signer = Signer_GM(account) data = b"1234567890" (v, r, s) = signer.sign(data) #print("hex v:",hex(v)) print("create account detail: ", account.getdetail()) print("after sign result is ", (r, s, v)) sigdata = "49889ee5e24e9fac262e04e82aab58aa0a2d29368e0a105913b20e96d0df6e1d887b8200d1d23052eae96419e21675cc579c759335226a16726f9d480f06b83f" print("sigdata len = ", len(decode_hex(sigdata))) sm2_crypt = sm2.CryptSM2(public_key=account.keypair.public_key, private_key=privkey) #sigdata= sm2_crypt.combine_signed_R_S(r,s) print("sigdata :", sigdata) vres = sm2_crypt.verify(sigdata[0:128], data) print("verify result : {}", vres) r = int("49889ee5e24e9fac262e04e82aab58aa0a2d29368e0a105913b20e96d0df6e1d", 16) s = int("887b8200d1d23052eae96419e21675cc579c759335226a16726f9d480f06b83f", 16) sigdata = sm2_crypt.combine_signed_R_S(r, s) vres = sm2_crypt.verify(sigdata, data) print("verify result 2: {}", vres)
def test_sm2_enc_dec(basic_loop, rand_bytes): for _ in range(basic_loop): msg = rand_bytes(random.randint(1, 64)) crypto_sm2 = sm2.CryptSM2(private_key=private_key, public_key=public_key) msg_enc = crypto_sm2.encrypt(msg) msg_dec = crypto_sm2.decrypt(msg_enc) assert msg == msg_dec
def get_public_key(p_k): """ 生成私钥所对应的公钥 :param p_k: <bytes> 私钥 :return: <bytes> 公钥 """ f = sm2.CryptSM2(0, 0) return f._kg(int(p_k, 16), sm2.default_ecc_table['g']).encode()
def sign(self, data_in_byte, chain_id=None): if self.sm2_crypt is None: self.sm2_crypt = sm2.CryptSM2( public_key=self.gm_account.keypair.public_key, private_key=self.gm_account.keypair.private_key) (r, s) = self.sm2_crypt.sign(data_in_byte) v_raw = self.keypair.public_key v = int(v_raw, 16) return (v, r, s)
def encrypt(data): """ 加密,这里私钥密钥固定 """ private_key = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5' public_key = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207' sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) enc_data = sm2_crypt.encrypt(data) return enc_data
def decrypt(pub_key, pri_key, cipher_text): buff = base64.b64decode(cipher_text) encrypter = sm2.CryptSM2(public_key=pub_key, private_key=pri_key) try: msg_bytes = encrypter.decrypt(buff) msg = msg_bytes.decode() except: return '---> 解密失败, 异常信息如下: ' + '\n' + traceback.format_exc() return msg
def sm2_sign(pri_k, d): """ 签名 :param pri_k: <bytes>公钥 :param d: <bytes>数据 :return: <bytes> """ random = func.random_hex(64) sm2_crypt = sm2.CryptSM2(pri_k, 0) return sm2_crypt.sign(d, random).encode()
def sm2_encrypt(pub_k, value): """ sm2加密 :param pub_k: <bytes> 公钥 :param value: <bytes> 明文 :return: <bytes> """ pub_k = pub_k.decode() sm2_crypt = sm2.CryptSM2(0, pub_k) return sm2_crypt.encrypt(value)
def sm2_verify(p_k, s, d): """ 验证签名 :param p_k:<bytes>私钥 :param s: <bytes>签名 :param d: <bytes>数据 :return: <bool> """ p_k = p_k.decode() sm2_crypt = sm2.CryptSM2(0, p_k) return sm2_crypt.verify(s, d)
def sm2_decrypt(pri_k, enc_data): """ sm2解密 :param pri_k: <bytes>私钥 :param enc_data: <bytes>密文 :return: <bytes> """ sm2_crypt = sm2.CryptSM2(pri_k, 0) if isinstance(enc_data, str): enc_data = enc_data.encode() return sm2_crypt.decrypt(enc_data)
def sm2_key_pair_func(self): sm2_crypt = sm2.CryptSM2(private_key="", public_key="") #产生私钥 random_hex_str = func.random_hex(sm2_crypt.para_len) self.privkey.setText(random_hex_str.upper()) self.result_textEdit.append("Gen Keypair - private key: " + random_hex_str.upper()) k = int(random_hex_str, 16) #计算公钥 Pubk = sm2_crypt._kg(k, sm2_crypt.ecc_table['g']) self.pubkx_LE.setText(Pubk[0:64].upper()) self.pubky_LE.setText(Pubk[64:len(Pubk)].upper()) self.result_textEdit.append("Gen Keypair - public key: " + Pubk.upper())
def generate(): private_key = '00' + func.random_hex(64) # private_key = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5' public_key = '' sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) # public_key(point) = private_key(int) * g(generator point) public_key = sm2_crypt._kg2(int(private_key, 16), sm2.default_ecc_table['g']) # ensure that works sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) data = b'zeox' enc_data = sm2_crypt.encrypt(data) dec_data =sm2_crypt.decrypt(enc_data) assert dec_data == data, 'generation failed, try again' random_hex_str = func.random_hex(sm2_crypt.para_len) sign = sm2_crypt.sign(data, random_hex_str) assert sm2_crypt.verify(sign, data) return { 'pubkey': public_key, 'pvtkey': private_key }
def test_sm2sm3(): private_key = "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8" public_key = "09F9DF311E5421A150DD7D161E4BC5C672179FAD1833FC076BB08FF356F35020"\ "CCEA490CE26775A52DC6EA718CC1AA600AED05FBF35E084A6632F6072DA9AD13" random_hex_str = "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21" sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) data = b"message digest" print("-----------------test SM2withSM3 sign and verify---------------") sign = sm2_crypt.sign_with_sm3(data, random_hex_str) print('sign: %s' % sign) verify = sm2_crypt.verify_with_sm3(sign, data) print('verify: %s' % verify) assert verify
def sm2_encrypt_func(self): public_key = self.pubkall_LE.text().strip() if len(public_key) != 128: self.Qmsgbox_show("Error", "Public key len is not 64 bytes") return self.result_textEdit.append("SM2 Encrypt Publickey: " + public_key) sm2_crypt = sm2.CryptSM2(private_key="", public_key=public_key) if self.plaintext_hex.text().strip() == "": self.Qmsgbox_show("Error", "Plaintext is null") return sm2_plaintext = bytes().fromhex(self.plaintext_hex.text().strip()) self.result_textEdit.append("Plaintext Hex: " + sm2_plaintext.hex().upper()) enc_data = sm2_crypt.encrypt(sm2_plaintext) self.result_textEdit.append("SM2 Encrypt Result Hex: " + enc_data.hex().upper()) self.encrypt_result.setText(enc_data.hex().upper())
def test_sm2(): private_key = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5' public_key = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207' sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) data = b"111" enc_data = sm2_crypt.encrypt(data) #print("enc_data:%s" % enc_data) #print("enc_data_base64:%s" % base64.b64encode(bytes.fromhex(enc_data))) dec_data = sm2_crypt.decrypt(enc_data) print(b"dec_data:%s" % dec_data) assert data == dec_data print("-----------------test sign and verify---------------") random_hex_str = func.random_hex(sm2_crypt.para_len) sign = sm2_crypt.sign(data, random_hex_str) print('sign:%s' % sign) verify = sm2_crypt.verify(sign, data) print('verify:%s' % verify) assert verify
def msg_pubk_id_to_e(self): public_key = self.pubkall_LE.text().strip() if len(public_key) != 128: return sm2_msg = self.plaintext_hex.text().strip() if len(sm2_msg) == 0: return if len(sm2_msg) % 2 != 0: sm2_msg = sm2_msg[0:len(sm2_msg) - 1] if len(self.id_iv.text().strip()) == "": ida = "31323334353637383132333435363738" else: ida = self.id_iv.text().strip() if len(ida) % 2 != 0: ida = ida[0:len(ida) - 1] sm2_crypt = sm2.CryptSM2(private_key="", public_key=public_key) e_hash = sm2_crypt.sm2_get_e(ida, sm2_msg) self.e_LE.setText(e_hash.upper())
def get_gm_child_xpub(xpub_str, path_list): for i in range(len(path_list)): selector_bytes = bytes.fromhex(path_list[i]) xpub_bytes = bytes.fromhex(xpub_str) hc_str = hmac.HMAC(xpub_bytes[33:], b'N' + xpub_bytes[:33] + selector_bytes, digestmod=hashlib.sha512).hexdigest() Il_int = int(hc_str[:64], 16) sm2_crypt = sm2.CryptSM2(private_key="", public_key="") public_key_str = sm2_crypt._kg(Il_int, sm2.default_ecc_table['g']) par_public_key_str = xpub_str[2:66] + decompress_public_key( xpub_str[:66]) child_public_key_str = sm2_crypt._add_point(public_key_str, par_public_key_str) child_public_key_str = sm2_crypt._convert_jacb_to_nor( child_public_key_str) if int(child_public_key_str[:], 16) & 1 == 0: xpub_str = "02" + child_public_key_str[:64] + hc_str[64:] else: xpub_str = "03" + child_public_key_str[:64] + hc_str[64:] child_xpub_str = xpub_str return {"child_xpub": child_xpub_str}