def time_verify(self): message = '576b2c99564392ed50e36c80654224953fdf8b5259528a1a4342c19be2da9b133c44429ac2be4d5dd588ec28e97015c34db80b7e8d8915e023c2501acd3eafe0' signature = b' S\xef\x14x\x06\xeb\xba\xc5\xf9\x0e\xac\x02pL\xbeLO;\x1d"$\xd7\xfc\x07\xfb\x9c\x08\xc5b^\x1e\xec\x19\xb1y\x11\np\xec(\xc9\xf3\xfd\x1f~\xe3\x99\xe8\xc98]\xd3\x951m${\x82\x0f[(\xa9\x90#' pubkey = ecda.verify_message(message, signature) signature = b' W\x83\xe5w\x8f\x07\x19EV\xba\x9d\x90\x9f\xfd \x81&\x0f\xa1L\xa00zK0\x08\xf78/\x9d\x0c\x06JFx[*Z\xfe\xd1F\x8d\x9f \x19\xad\xd9\xc9\xbf\xd3\x1br\xdd\x8e\x8ei\xf8\xd2\xf40\xad\xc6\x9c\xe5' message = 'foo' pubkey = ecda.verify_message(message, signature) signature = b'\x1f9\xb6_\x85\xbdr7\\\xb2N\xfb~\x82\xb7E\x80\xf1M\xa4EP=\x8elJ\x1d[t\xab%v~a\xb7\xdbS\x86;~N\xd2!\xf1k=\xb6tMm-\xf1\xd9\xfc\xf3`\xbf\xd5)\x1b\xb3N\x92u/' message = 'This is a short Message' pubkey = ecda.verify_message(message, signature) message = '1234567890' signature = b' 7\x82\xe2\xad\xdc\xdb]~\xd6\xa8J\xdc\xa5\xf4\x13<i\xb9\xc0\xdcEc\x10\xd0)t\xc7^\xecw\x05 U\x91\x0f\xa2\xce\x04\xa1\xdb\xb0\nQ\xbd\xafP`\\\x8bb\x99\xcf\xe0;\x01*\xe9D]\xad\xd9l\x1f\x05' pubkey = ecda.verify_message(message, signature)
def validate_hivekeychain_ans(ans): """ takes in the answer from hivekeychain and checks everything """ """ https://bit.ly/keychainpython """ acc_name = ans['data']['username'] pubkey = PublicKey(ans['publicKey']) enc_msg = ans['data']['message'] signature = ans['result'] msgkey = verify_message(enc_msg, unhexlify(signature)) pk = PublicKey(hexlify(msgkey).decode("ascii")) if str(pk) == str(pubkey): app.logger.info(f'{acc_name} SUCCESS: signature matches given pubkey') acc = Account(acc_name, lazy=True) match = False, 0 for key in acc['posting']['key_auths']: match = match or ans['publicKey'] in key if match: app.logger.info(f'{acc_name} Matches public key from Hive') mtime = json.loads(enc_msg)['timestamp'] time_since = time.time() - mtime if time_since < 30: app.logger.info(f'{acc_name} SUCCESS: in {time_since} seconds') return True, time_since else: app.logger.warning(f'{acc_name} ERROR: answer took too long.') else: app.logger.warning( f'{acc_name} ERROR: message was signed with a different key') return False, 0
def test_wrong_signature(self, module): if module == "cryptography": if not ecda.CRYPTOGRAPHY_AVAILABLE: return ecda.SECP256K1_MODULE = "cryptography" elif module == "secp256k1": if not ecda.SECP256K1_AVAILABLE: return ecda.SECP256K1_MODULE = "secp256k1" pub_key = py23_bytes(repr(PrivateKey(wif).pubkey), "latin") ecda.SECP256K1_MODULE = module signature = ecda.sign_message("Foobar", wif) pub_key_sig = ecda.verify_message("Foobar", signature) self.assertEqual(hexlify(pub_key_sig), pub_key) pub_key_sig2 = ecda.verify_message("Foobar2", signature) self.assertTrue(hexlify(pub_key_sig2) != pub_key)
def verify(self, **kwargs): """ Verify a message with an account's memo key :param str account: (optional) the account that owns the bet (defaults to ``default_account``) :returns: True if the message is verified successfully :raises InvalidMessageSignature: if the signature is not ok """ # Split message into its parts parts = re.split("|".join(MESSAGE_SPLIT), self.message) parts = [x for x in parts if x.strip()] if not len(parts) > 2: raise AssertionError("Incorrect number of message parts") message = parts[0].strip() signature = parts[2].strip() # Parse the meta data meta = dict(re.findall(r'(\S+)=(.*)', parts[1])) # Ensure we have all the data in meta if "account" not in meta: raise AssertionError() if "memokey" not in meta: raise AssertionError() if "block" not in meta: raise AssertionError() if "timestamp" not in meta: raise AssertionError() # Load account from blockchain account = Account(meta.get("account"), blockchain_instance=self.blockchain) # Test if memo key is the same as on the blockchain if not account["memo_key"] == meta["memokey"]: log.error("Memo Key of account {} on the Blockchain".format( account["name"]) + "differs from memo key in the message: {} != {}".format( account["memo_key"], meta["memokey"])) # Reformat message message = SIGNED_MESSAGE_META.format(**locals()) # Verify Signature pubkey = verify_message(message, unhexlify(signature)) # Verify pubky pk = PublicKey(hexlify(pubkey).decode("ascii")) if format(pk, self.blockchain.prefix) != meta["memokey"]: raise InvalidMessageSignature return True
def verify(self, **kwargs): """ Verify a message with an account's memo key :param str account: (optional) the account that owns the bet (defaults to ``default_account``) :returns: True if the message is verified successfully :raises InvalidMessageSignature if the signature is not ok """ if not isinstance(self.message, dict): try: self.message = json.loads(self.message) except Exception: raise ValueError("Message must be valid JSON") payload = self.message.get("payload") assert payload, "Missing payload" payload_dict = {k[0]: k[1] for k in zip(payload[::2], payload[1::2])} signature = self.message.get("signature") account_name = payload_dict.get("from").strip() memo_key = payload_dict.get("key").strip() assert account_name, "Missing account name 'from'" assert memo_key, "missing 'key'" try: Account(memo_key, prefix=self.blockchain.prefix) except Exception: raise InvalidMemoKeyException( "The memo key in the message is invalid") # Load account from blockchain try: account = Account(account_name, blockchain_instance=self.blockchain) except AccountDoesNotExistsException: raise AccountDoesNotExistsException( "Could not find account {}. Are you connected to the right chain?" .format(account_name)) # Test if memo key is the same as on the blockchain if not account["memo_key"] == memo_key: raise WrongMemoKey("Memo Key of account {} on the Blockchain ". format(account["name"]) + "differs from memo key in the message: {} != {}" .format(account["memo_key"], memo_key)) # Ensure payload and signed match signed_target = json.dumps(self.message.get("payload"), separators=(",", ":")) signed_actual = self.message.get("signed") assert (signed_target == signed_actual ), "payload doesn't match signed message: \n{}\n{}".format( signed_target, signed_actual) # Reformat message enc_message = self.message.get("signed") # Verify Signature pubkey = verify_message(enc_message, unhexlify(signature)) # Verify pubky pk = PublicKey(hexlify(pubkey).decode("ascii"), prefix=self.blockchain.prefix) if format(pk, self.blockchain.prefix) != memo_key: raise InvalidMessageSignature( "The signature doesn't match the memo key") self.signed_by_account = account self.signed_by_name = account["name"] self.plain_message = payload_dict.get("text") return True
def verify(self, **kwargs): """ Verify a message with an account's memo key :param str account: (optional) the account that owns the bet (defaults to ``default_account``) :returns: True if the message is verified successfully :raises InvalidMessageSignature if the signature is not ok """ # Split message into its parts parts = re.split("|".join(self.MESSAGE_SPLIT), self.message) parts = [x for x in parts if x.strip()] assert len(parts) > 2, "Incorrect number of message parts" # Strip away all whitespaces before and after the message message = parts[0].strip() signature = parts[2].strip() # Parse the meta data meta = dict(re.findall(r"(\S+)=(.*)", parts[1])) log.info("Message is: {}".format(message)) log.info("Meta is: {}".format(json.dumps(meta))) log.info("Signature is: {}".format(signature)) # Ensure we have all the data in meta assert "account" in meta, "No 'account' could be found in meta data" assert "memokey" in meta, "No 'memokey' could be found in meta data" assert "block" in meta, "No 'block' could be found in meta data" assert "timestamp" in meta, "No 'timestamp' could be found in meta data" account_name = meta.get("account").strip() memo_key = meta["memokey"].strip() try: PublicKey(memo_key, prefix=self.blockchain.prefix) except Exception: raise InvalidMemoKeyException( "The memo key in the message is invalid") # Load account from blockchain try: account = Account(account_name, blockchain_instance=self.blockchain) except AccountDoesNotExistsException: raise AccountDoesNotExistsException( "Could not find account {}. Are you connected to the right chain?" .format(account_name)) # Test if memo key is the same as on the blockchain if not account["memo_key"] == memo_key: raise WrongMemoKey("Memo Key of account {} on the Blockchain ". format(account["name"]) + "differs from memo key in the message: {} != {}" .format(account["memo_key"], memo_key)) # Reformat message enc_message = self.SIGNED_MESSAGE_META.format(**locals()) # Verify Signature pubkey = verify_message(enc_message, unhexlify(signature)) # Verify pubky pk = PublicKey(hexlify(pubkey).decode("ascii"), prefix=self.blockchain.prefix) if format(pk, self.blockchain.prefix) != memo_key: raise InvalidMessageSignature( "The signature doesn't match the memo key") self.signed_by_account = account self.signed_by_name = account["name"] self.meta = meta self.plain_message = message return True