예제 #1
0
    def verifyData(self, data):
        # verify hash
        msg_hash = data[:32]
        if msg_hash != keccak256(data[32:]):
            print " First 32 bytes are not keccak256 hash of the rest."
            return
        else:
            print " Verified message hash."

        # verify signature
        signature = data[32:97]
        signed_data = data[97:]
        deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(signature[:64], ord(signature[64]))

        remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signed_data), deserialized_sig, raw = True)

        pub = PublicKey()
        pub.public_key = remote_pubkey

        verified = pub.ecdsa_verify(keccak256(signed_data),
                            pub.ecdsa_recoverable_convert(deserialized_sig),
                            raw = True)

        if not verified:
            print " Signature invalid"
            return False
        else:
            print " Verified signature."
            return True
예제 #2
0
    def handlePacket(self, data, addr):
        # print("received message[" +  str(addr) + "]")
        msg_hash = data[:32]  # 32 Byte Hash
        raw_sig = data[32:97]  # 64 Byte + 1 Byte Signature
        ptype = data[97]  # 1 Byte packet_type
        pdata = data[98:]  # Rest is rlp-encoded data
        decdata = rlp.decode(pdata)
        signedData = data[97:]

        # Verify hash
        if msg_hash != keccak256(data[32:]):
            print("Invalid message hash!")
            exit(0)

        # Verify signature
        deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(
            raw_sig[:64], raw_sig[64])
        remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signedData),
                                                    deserialized_sig,
                                                    raw=True)
        pub = PublicKey()
        pub.public_key = remote_pubkey
        verified = pub.ecdsa_verify(
            keccak256(signedData),
            pub.ecdsa_recoverable_convert(deserialized_sig),
            raw=True)

        if not verified:
            print("Signature invalid!")
            exit(0)
        else:
            print("Public Key: " + pub.serialize().hex())

        packet_type = bytes([ptype])
        if packet_type == PingPacket.packet_type:
            print("Got ping.")
            recv_ping = PingPacket.unpack(rlp.decode(pdata))
            print(str(recv_ping))
            # self.pong(msg_hash, recv_ping.To())
            # TODO: Find out the correct endpoint
            self.pong(self.theirEndpoint, msg_hash)

        if packet_type == PongPacket.packet_type:
            print("Got pong.")
            recv_pong = PongPacket.unpack(decdata)
            print(str(recv_pong))
            # self.ping(self.theirEndpoint)

        if packet_type == FindNodePacket.packet_type:
            print("Got FindNodePacket.")
            recv_findnode = FindNodePacket.unpack(rlp.decode(pdata))
            target = recv_findnode.target
            print("Target: " + str(target.hex()))
            self.neighbors(self.theirEndpoint, target)

        if packet_type == NeighborsPacket.packet_type:
            print("Got NeighborsPacket.")
            recv_neighbors = NeighborsPacket.unpack(rlp.decode(pdata))
            print("# Neighbors: " + str(len(recv_neighbors.neighbors)))
예제 #3
0
def ecdsa_verify(pubkey, signature, message):
    assert len(signature) == 65
    assert len(pubkey) == 64
    pk = PublicKey('\04' + pubkey, raw=True, ctx=ctx)
    return pk.ecdsa_verify(message,
                           pk.ecdsa_recoverable_convert(
                               pk.ecdsa_recoverable_deserialize(
                                   signature[:64], ord(signature[64]))),
                           raw=True)
예제 #4
0
 def ecdsa_compact_verify(self, msg32, sign, pub):
     # Check if pubkey has been bin_electrum encoded.
     # If so, append \04 to the front of the key, to make sure the length is 65
     if len(pub) == 64:
         pub = '\04'+pub
     pub_k = PublicKey().deserialize(pub)
     pub_key = PublicKey(pub_k, raw=False, flags=secp256k1.ALL_FLAGS)
     der_sig = pub_key.ecdsa_recoverable_deserialize(sign[0], sign[1])
     raw_sig = pub_key.ecdsa_recoverable_convert(der_sig)
     return pub_key.ecdsa_verify(msg32, raw_sig, raw=True)
예제 #5
0
    def receive(self, data, addr):
        """
        macSize  = 256 / 8 = 32
        sigSize  = 520 / 8 = 65
        headSize = macSize + sigSize = 97
        hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
        shouldhash := crypto.Sha3(buf[macSize:])
        """
        # verify hash
        msg_hash = data[:32]
        if msg_hash != keccak256(data[32:]):
            print " First 32 bytes are not keccak256 hash of the rest."
            return
        else:
            print " Verified message hash."

        # verify signature
        signature = data[32:97]
        signed_data = data[97:]
        deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(signature[:64],
                                                                       ord(signature[64]))

        remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signed_data),
                                                    deserialized_sig,
                                                    raw=True)

        pub = PublicKey()
        pub.public_key = remote_pubkey

        verified = pub.ecdsa_verify(keccak256(signed_data),
                                    pub.ecdsa_recoverable_convert(deserialized_sig),
                                    raw=True)

        if not verified:
            print " Signature invalid"
            return
        else:
            print " Verified signature."

        response_types = {
            PingNode.packet_type: self.receive_ping,
            Pong.packet_type: self.receive_pong,
            FindNeighbors.packet_type: self.receive_find_neighbors,
            Neighbors.packet_type: self.receive_neighbors
        }

        try:
            packet_type = data[97]
            dispatch = response_types[packet_type]
        except KeyError:
            print " Unknown message type: " + data[97]
            return

        payload = data[98:]
        dispatch(payload, msg_hash, addr)
예제 #6
0
 def verify(self, message):
     pub = PublicKey(self.pub_key, raw=True)
     message = VarInt(len(message)).encode() + message
     # LOGGER.debug("Comparing with %r" % (MESSAGE_TEMPLATE % message))
     try:
         sig_raw = pub.ecdsa_deserialize(self.sig_ser)
         good = pub.ecdsa_verify(MESSAGE_TEMPLATE % message, sig_raw)
     except Exception:
         LOGGER.exception("Verification failed")
         good = False
     return good
def check_sig(public_key, signature, message):
    raw = bytes(bytearray.fromhex(public_key))
    sig = bytes(bytearray.fromhex(signature))
    pub = PublicKey(raw, raw=True)
    try:
        sig_raw = pub.ecdsa_deserialize(sig)
        good = pub.ecdsa_verify(bytes(bytearray.fromhex(message)), sig_raw)
    except:
        good = False
    print(u"{}\n".format(good))
    return 0 if good else 1
예제 #8
0
def verify_sign(message, pubkey, address, sign):
    """verify message sign"""
    # verify public key
    if address != pubkey2address(pubkey):
        return False
    # verify sign
    ecc_pubkey = PublicKey(bytes(bytearray.fromhex(pubkey)), raw=True)
    # print(ecc_pubkey)
    sign = ecc_pubkey.ecdsa_deserialize(binascii.unhexlify(sign))
    verified = ecc_pubkey.ecdsa_verify(binascii.unhexlify(message), sign)
    # print(verified)
    return verified
예제 #9
0
def verify_message(message):
    """验证信息有效性"""
    # 验证公钥
    if message.sender != pubkey2address(message.pubkey):
        return False
    # 验证签名
    ecc_pubkey = PublicKey(bytes(bytearray.fromhex(message.pubkey)), raw=True)
    # print(ecc_pubkey)
    sign = ecc_pubkey.ecdsa_deserialize(binascii.unhexlify(message.sign))
    verified = ecc_pubkey.ecdsa_verify(binascii.unhexlify(message.content), sign)
    # print(verified)
    return verified
예제 #10
0
    def receive(self):

        print "listening..."
        data, addr = self.sock.recvfrom(1024)
        print "received message[", addr, "]"

        ## verify hash
        msg_hash = data[:32]
        if msg_hash != keccak256(data[32:]):
            print " First 32 bytes are not keccak256 hash of the rest."
            return
        else:
            print " Verified message hash."

        ## verify signature
        signature = data[32:97]
        signed_data = data[97:]
        deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(
            signature[:64], ord(signature[64]))

        remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signed_data),
                                                    deserialized_sig,
                                                    raw=True)

        pub = PublicKey()
        pub.public_key = remote_pubkey

        verified = pub.ecdsa_verify(
            keccak256(signed_data),
            pub.ecdsa_recoverable_convert(deserialized_sig),
            raw=True)

        if not verified:
            print " Signature invalid"
            return
        else:
            print " Verified signature."

        response_types = {
            PingNode.packet_type: self.receive_ping,
            Pong.packet_type: self.receive_pong
        }

        try:
            packet_type = data[97]
            dispatch = response_types[packet_type]
        except KeyError:
            print " Unknown message type: " + data[97]
            return

        payload = data[98:]
        dispatch(payload)
예제 #11
0
def _test_signature(public_key, private_key, msg):
    print('uncompressed pub key %i bytes: %s' %
          (len(public_key), public_key.hex()))
    comp_pubkey = Key.from_sec(public_key)
    print('compressed pub key: %s' %
          comp_pubkey.sec_as_hex(use_uncompressed=False))
    secp_pubkey = PublicKey(public_key, raw=True)
    secp_privkey = PrivateKey(private_key, raw=True)
    print('checking signature')
    signature = secp_privkey.ecdsa_sign(msg)
    if (secp_pubkey.ecdsa_verify(msg, signature)):
        print('signature OK')
    else:
        raise Exception('signature test failed')
예제 #12
0
def getDeployedSecret(dongle, masterPrivate, targetid):
	testMaster = PrivateKey(bytes(masterPrivate))
	testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False))
	targetid = bytearray(struct.pack('>I', targetid))

	# identify
	apdu = bytearray([0xe0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid
	dongle.exchange(apdu)

	# walk the chain 
	batch_info = bytearray(dongle.exchange(bytearray.fromhex('E050000000')))
	cardKey = batch_info[5:5 + batch_info[4]]

	# if not found, get another pair
	#if cardKey <> testMasterPublic:
	#	raise Exception("Invalid batch public key")

	# provide the ephemeral certificate
	ephemeralPrivate = PrivateKey()
	ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False))
	print "Using ephemeral key " + str(ephemeralPublic).encode('hex')
	signature = testMaster.ecdsa_sign(bytes(ephemeralPublic))
	signature = testMaster.ecdsa_serialize(signature)
	certificate = bytearray([len(ephemeralPublic)]) + ephemeralPublic + bytearray([len(signature)]) + signature
	apdu = bytearray([0xE0, 0x51, 0x00, 0x00]) + bytearray([len(certificate)]) + certificate
	dongle.exchange(apdu)

	# walk the device certificates to retrieve the public key to use for authentication
	index = 0
	last_pub_key = PublicKey(bytes(testMasterPublic), raw=True)
	while True:
		certificate = bytearray(dongle.exchange(bytearray.fromhex('E052000000')))
		if len(certificate) == 0:
			break
		certificatePublic = certificate[1 : 1 + certificate[0]]
		certificateSignature = last_pub_key.ecdsa_deserialize(bytes(certificate[2 + certificate[0] :]))		
		if not last_pub_key.ecdsa_verify(bytes(certificatePublic), certificateSignature):
			if index == 0:
				# Not an error if loading from user key
				print "Broken certificate chain - loading from user key"
			else:
				raise Exception("Broken certificate chain")
		last_pub_key = PublicKey(bytes(certificatePublic), raw=True)
		index = index + 1

	# Commit device ECDH channel
	dongle.exchange(bytearray.fromhex('E053000000'))
	secret = last_pub_key.ecdh(bytes(ephemeralPrivate.serialize().decode('hex')))
	return str(secret[0:16])
예제 #13
0
 def validate(self, transaction, unspent_tx_outs):
     if not self.validate_struct():
         return False
     utx_out = None
     for unspent_tx_out in unspent_tx_outs:
         if unspent_tx_out.tx_out_id == self.tx_out_id and unspent_tx_out.tx_out_index == self.tx_out_index:
             utx_out = unspent_tx_out
     if utx_out is None:
         return False
     pubkey = PublicKey(unhexlify(utx_out.address), raw=True)
     if not pubkey.ecdsa_verify(
             unhexlify(transaction.id),
             pubkey.ecdsa_deserialize(unhexlify(self.signature))):
         logging.error("invalid tx_in signature")
         return False
     return True
예제 #14
0
    def valid(self):
        """Check if this object is valid or not"""
        if not self.signature:
            return False

        assert isinstance(self.signature, bytes)
        assert 70 <= len(self.signature) <= 71
        assert isinstance(self.user_public_key, bytes)
        assert len(self.user_public_key) == 33
        assert isinstance(self.user_address, str)
        assert re.match(r'^(?:0[xX])?[0-9a-fA-F]{40}$', self.user_address)
        public_key = PublicKey(self.user_public_key, raw=True)
        verified = public_key.ecdsa_verify(
            self.serialize(include_signature=False),
            public_key.ecdsa_deserialize(self.signature))
        if not verified:
            return False

        if get_address(public_key) != self.user_address:
            return False

        return self.id == self.hash
예제 #15
0
 def verify_signature(self, msg, signature):
     """Verify message and signature if its from this wallet"""
     pub = PublicKey(self.key.public_byte, raw=True)
     sig = pub.ecdsa_deserialize_compact(encoding.to_bytes(signature))
     valid = pub.ecdsa_verify(msg, sig)
     return valid
예제 #16
0
		break
	textToSign += data + "\n"

dongle = getDongle(True)
publicKey = dongle.exchange(bytes("8004000000".decode('hex')))
print("publicKey " + str(publicKey).encode('hex'))
try:
	offset = 0
	while offset != len(textToSign):
		if (len(textToSign) - offset) > 255:
			chunk = textToSign[offset : offset + 255] 
		else:
			chunk = textToSign[offset:]
		if (offset + len(chunk)) == len(textToSign):
			p1 = 0x80
		else:
			p1 = 0x00
		apdu = bytes("8002".decode('hex')) + chr(p1) + chr(0x00) + chr(len(chunk)) + bytes(chunk)
		signature = dongle.exchange(apdu)
		offset += len(chunk)  	
	print("signature " + str(signature).encode('hex'))
	publicKey = PublicKey(bytes(publicKey), raw=True)
	signature = publicKey.ecdsa_deserialize(bytes(signature))
	print("verified " + str(publicKey.ecdsa_verify(bytes(textToSign), signature)))
except CommException as comm:
	if comm.sw == 0x6985:
		print("Aborted by user")
	else:
		print("Invalid status " + comm.sw)

예제 #17
0
		break
	textToSign += data + "\n"

dongle = getDongle(True)
publicKey = dongle.exchange(bytes("8004000000".decode('hex')))
print "publicKey " + str(publicKey).encode('hex')
try:
	offset = 0
	while offset <> len(textToSign):
		if (len(textToSign) - offset) > 255:
			chunk = textToSign[offset : offset + 255] 
		else:
			chunk = textToSign[offset:]
		if (offset + len(chunk)) == len(textToSign):
			p1 = 0x80
		else:
			p1 = 0x00
		apdu = bytes("8002".decode('hex')) + chr(p1) + chr(0x00) + chr(len(chunk)) + bytes(chunk)
		signature = dongle.exchange(apdu)
		offset += len(chunk)  	
	print "signature " + str(signature).encode('hex')
	publicKey = PublicKey(bytes(publicKey), raw=True)
	signature = publicKey.ecdsa_deserialize(bytes(signature))
	print "verified " + str(publicKey.ecdsa_verify(bytes(textToSign), signature))
except CommException as comm:
	if comm.sw == 0x6985:
		print "Aborted by user"
	else:
		print "Invalid status " + comm.sw 

예제 #18
0
publicKey = dongle.exchange(bytes("e004000000".decode('hex')))
print "publicKey " + str(publicKey).encode('hex')
try:
    offset = 0
    while offset != len(textToSign):
        if (len(textToSign) - offset) > 255:
            chunk = textToSign[offset:offset + 255]
        else:
            chunk = textToSign[offset:]
        if (offset + len(chunk)) == len(textToSign):
            p1 = 0x80
        else:
            p1 = 0x00
        apdu = bytes("e002".decode('hex')) + chr(p1) + chr(0x00) + chr(
            len(chunk)) + bytes(chunk)
        start = time.time()
        signature = dongle.exchange(apdu)
        end = time.time()
        offset += len(chunk)
    print "signature " + str(signature).encode('hex')
    print "time to sign: " + str(end - start)
    publicKey = PublicKey(bytes(publicKey), raw=True)
    signature = publicKey.ecdsa_deserialize(bytes(signature))
    print "verified " + str(
        publicKey.ecdsa_verify(bytes(textToSign), signature))
except CommException as comm:
    if comm.sw == 0x6985:
        print "Aborted by user"
    else:
        print "Invalid status " + str(comm.sw)
예제 #19
0
        apdu += bytes((l, ))
        apdu += bytes(chunk, 'ascii')
        apdu += bip

        signature = dongle.exchange(apdu)
        offset += len(chunk)

        print("\nSent chunk: " +
              binascii.hexlify(bytes(chunk, 'ascii')).decode())

    print("\nGot signature: " + binascii.hexlify(signature).decode())
    publicKey = PublicKey(bytes(publicKey), raw=True)

    print("base64-encoded: " + base64.b64encode(signature).decode())
    signature = publicKey.ecdsa_deserialize(bytes(signature))

    dataToSign = bytes(serialize(json.loads(textToSign)))
    print("\nSource tx: " + textToSign)
    print("\nMy data to sign: " + binascii.hexlify(dataToSign).decode())
    print("\nIs signature verified? " +
          str(publicKey.ecdsa_verify(dataToSign, signature)))
    # fff = base64.b64decode("MEUCID3p7O1FIIWlN1kHAB3rSTK43HB8E9ZIN9h+sce1pDmcAiEA0P0DKOCEssJNqKsAEI+OuwBsU2AbYiCQfSxaveuxpWc=")
    # signature2 = publicKey.ecdsa_deserialize(bytes(fff))
    # print "verified " + str(publicKey.ecdsa_verify(bytes(_textToSign), signature2))

except CommException as comm:
    if comm.sw == 0x6985:
        print("Aborted by user")
    else:
        print("Invalid status " + comm.sw)
예제 #20
0
def validate_signature(sighash, signature, miner_pubkey):
	"""Validate header signature"""
	pubkey = PublicKey(miner_pubkey, raw=True)
	return pubkey.ecdsa_verify(sighash, pubkey.ecdsa_deserialize(signature))
예제 #21
0
    while offset <> len(textToSign):
        if (len(textToSign) - offset) > 255:
            chunk = textToSign[offset:offset + 255]
        else:
            chunk = textToSign[offset:]
        if (offset + len(chunk)) == len(textToSign):
            p1 = 0x80
        else:
            p1 = 0x00
        apdu = bytes("8002".decode('hex')) + chr(p1) + chr(0x00) + chr(
            len(chunk)) + bytes(chunk)
        signature = dongle.exchange(apdu)
        offset += len(chunk)
    print "signature " + str(signature).encode('hex')
    publicKey = PublicKey(bytes(publicKey), raw=True)
    signatureStuct = publicKey.ecdsa_deserialize(bytes(signature))
    print "verified " + str(
        publicKey.ecdsa_verify(bytes(textToSign), signatureStuct))
    sig = bytes(signature)
    try:
        sig_raw = publicKey.ecdsa_deserialize(sig)
        good = publicKey.ecdsa_verify(textToSign, sig_raw)
    except:
        good = False
    print good
except CommException as comm:
    if comm.sw == 0x6985:
        print "Aborted by user"
    else:
        print "Invalid status " + comm.sw
예제 #22
0
    def receive(self, data, addr):
        """
        macSize  = 256 / 8 = 32
        sigSize  = 520 / 8 = 65
        headSize = macSize + sigSize = 97
        hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
        shouldhash := crypto.Sha3(buf[macSize:])
        """
        # verify hash
        msg_hash = data[:32]
        assert msg_hash == keccak256(
            data[32:]), "First 32 bytes are not keccak256 hash of the rest"

        # verify signature
        signature = data[32:97]
        signed_data = data[97:]
        deserialized_sig = self.priv_key.ecdsa_recoverable_deserialize(
            signature[:64], ord(signature[64]))

        remote_pubkey = self.priv_key.ecdsa_recover(keccak256(signed_data),
                                                    deserialized_sig,
                                                    raw=True)

        pub = PublicKey()
        pub.public_key = remote_pubkey

        verified = pub.ecdsa_verify(
            keccak256(signed_data),
            pub.ecdsa_recoverable_convert(deserialized_sig),
            raw=True)

        assert verified, "Signature invalid"

        pubkey = pubkey_format(pub)[1:]
        hex_id = binascii.hexlify(keccak256(pubkey))

        packet_type = data[97]
        payload = rlp.decode(data[98:])
        if packet_type == PingNode.packet_type:
            # fake ip in packet
            payload[1][0] = addr[0]
            ping = PingNode.unpack(payload)
            if expired(ping):
                return
            self.receive_ping(addr, pubkey, ping, msg_hash)
        elif packet_type == Pong.packet_type:
            pong = Pong.unpack(payload)
            if expired(pong):
                return
            self.receive_pong(addr, pubkey, pong)
        elif packet_type == FindNeighbors.packet_type:
            fn = FindNeighbors.unpack(payload)
            if expired(fn):
                return
            self.receive_find_neighbors(addr, pubkey, fn)
        elif packet_type == Neighbors.packet_type:
            neighbours = Neighbors.unpack(payload)
            if expired(neighbours):
                return
            self.receive_neighbors(addr, pubkey, neighbours)
        else:
            assert False, " Unknown message type: {}".format(packet_type)