def test_sign_message_secp256k1(self): if not ecdsa.SECP256K1_AVAILABLE: return ecdsa.SECP256K1_MODULE = "secp256k1" signature = ecdsa.sign_message("Foobar", wif) pub_key_sig = ecdsa.verify_message("Foobar", signature) self.assertEqual(hexlify(pub_key_sig).decode("latin"), pub_key)
def test_sign_message_cryptography(self): if not ecdsa.CRYPTOGRAPHY_AVAILABLE: return ecdsa.SECP256K1_MODULE = "cryptography" signature = ecdsa.sign_message("Foobar", wif) pub_key_sig = ecdsa.verify_message("Foobar", signature) self.assertEqual(hexlify(pub_key_sig).decode("latin"), 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()] assert len(parts) > 2, "Incorrect number of message parts" message = parts[0].strip() signature = parts[2].strip() # Parse the meta data self.meta = dict(re.findall(r'(\S+)=(.*)', parts[1])) # Ensure we have all the data in meta assert "account" in self.meta assert "memokey" in self.meta assert "block" in self.meta assert "timestamp" in self.meta self.meta['message'] = message # Load account from blockchain account = Account( self.meta.get("account"), vinchain_instance=self.vinchain ) # Test if memo key is the same as on the blockchain if not account["options"]["memo_key"] == self.meta["memokey"]: log.error( "Memo Key of account {} on the Blockchain".format( account["name"]) + "differs from memo key in the message: {} != {}".format( account["options"]["memo_key"], self.meta["memokey"] ) ) raise InvalidMessageSignature # Reformat message message = SIGNED_MESSAGE_META.format(meta=self.meta, **locals()) # Verify Signature pubkey = verify_message(message, unhexlify(signature)) # Verify pubky pk = PublicKey(hexlify(pubkey).decode("ascii")) if format(pk, self.vinchain.prefix) != self.meta["memokey"]: raise InvalidMessageSignature return True
def test_sign_message(): signature = sign_message( "text text text", "5JCvGL2GVVpjDrKzbKWPHEvuwFs5HdEGwr4brp8RQiwrpEFcZNP") # assert(hexlify(signature) == b'2075625adc5f0a025fa5125e1f1a6493c2ad9798ec18afb49d4a1d9f741ccac16' # b'441cb10d240046e5cf3b7f10694b62c608047ec037b2ddaec053bdd1f5107c927') k = verify_message("text text text", signature) p = PublicKey(hexlify(k).decode('ascii')) assert (str(p) == "SCR5bgzuweaHx231escVuPVxgudSyUWdKAH7fKgxZfp3nKSirzFRa")
def verify_tx(d): sig = d['signature'] name = d['account'] account = cybex.account.Account(name , cybex_instance = inst) del d['signature'] op = Tx(**d) message = bytes(op) p = verify_message(message, unhexlify(sig)) pkey = PublicKey(hexlify(p).decode('ascii'), prefix = 'CYB') print(str(pkey)) _pubkey = account['active']['key_auths'][0][0] if str(pkey) == _pubkey: return True return False
def verify_tx(d): sig = d['signature'] name = d['account'] try: account = cybex.account.Account(name , cybex_instance = inst) except: logger.error('account [%s] not found from chain'%(name)) return False del d['signature'] message = name try: p = verify_message(message, unhexlify(sig)) except: logger.error('verify_message failed') return False pkey = PublicKey(hexlify(p).decode('ascii'), prefix = 'CYB') # return str(pkey) _pubkey = account['active']['key_auths'][0][0] if str(pkey) == _pubkey: return True return False
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()] 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["options"]["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["options"]["memo_key"], memo_key)) # Reformat message enc_message = SIGNED_MESSAGE_META.format(**locals()) # Verify Signature pubkey = verify_message(enc_message, unhexlify(signature)) # Verify pubky pk = PublicKey(hexlify(pubkey).decode("ascii")) if format(pk, self.blockchain.prefix) != memo_key: raise InvalidMessageSignature return True
def test_sign_message(self): signature = ecdsa.sign_message("Foobar", wif) pub_key_sig = ecdsa.verify_message("Foobar", signature) self.assertEqual(hexlify(pub_key_sig).decode("latin"), pub_key)
async 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: self.publickey_class(memo_key, prefix=self.blockchain.prefix) except Exception: raise InvalidMemoKeyException( "The memo key in the message is invalid") # Load account from blockchain try: account = await self.account_class( 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["options"]["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["options"]["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 = self.publickey_class(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