Example #1
0
    def test_sign_and_verify(self):
        privkey = KeyPair.PrivateKeyFromWIF(
            "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP")
        keypair = KeyPair(privkey)
        hashdata = b'aabbcc'

        keypair_signature = Crypto.Sign(hashdata, bytes(keypair.PrivateKey))
        keypair_signature2 = Crypto.Default().Sign(hashdata,
                                                   bytes(keypair.PrivateKey))
        self.assertEqual(keypair_signature, keypair_signature2)

        verification_result = Crypto.VerifySignature(hashdata.decode('utf8'),
                                                     keypair_signature,
                                                     keypair.PublicKey)
        verification_result2 = Crypto.Default().VerifySignature(
            hashdata.decode('utf8'), keypair_signature, keypair.PublicKey)
        self.assertEqual(verification_result, verification_result2)
        self.assertTrue(verification_result)

        # verify with compressed key
        verification_result3 = Crypto.VerifySignature(
            hashdata.decode('utf8'), keypair_signature,
            binascii.unhexlify(keypair.PublicKey.encode_point(True)))
        self.assertTrue(verification_result3)

        # this should fail because the signature will not match the input data
        verification_result = Crypto.VerifySignature(b'aabb',
                                                     keypair_signature,
                                                     keypair.PublicKey)
        self.assertFalse(verification_result)
Example #2
0
def main():
    tx = construct_tx()
    tx_data = get_tx_data(tx)

    signstr =binascii.hexlify(Crypto.Sign(message=tx_data, private_key=private_key)).decode()

    rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac"
    print (rawtx_data)  #waiting for relay
Example #3
0
    def test_neon_sig(self):

        key = KeyPair(priv_key=self.nmpk)

        hhex = hashlib.sha256(binascii.unhexlify(self.nmsg)).hexdigest()

        self.assertEqual(hhex, self.hashhex)

        sig = Crypto.Sign(self.nmsg, key.PrivateKey)

        self.assertEqual(sig.hex(), self.neon_sig)
Example #4
0
def sign_msg(msg, priv_key):
    """Sign a given message using a private key.

    Args:
        msg (str)         : Message which needs to be signed.
        priv_key (bytes)  : Private key to be used to sign this.

    Returns:
        Signed message as a byte array.
    """
    return Crypto.Sign(msg, priv_key).hex()
Example #5
0
def create_tx(contract_hash, address_from, address_to, tnc_amount, gas_change,
              input_txid, preIndex):

    nep5TokenId = get_nep5token_id(contract_hash)
    scripthash_from = ToScriptHash(address_from)
    scripthash_to = ToScriptHash(address_to)
    f8amount = amount_from_string(nep5TokenId, tnc_amount)
    f8amount_change = Fixed8.TryParse(gas_change, require_positive=True)
    assetId = get_asset_id("gas")
    preHash = UInt256(data=binascii.unhexlify(hex_reverse(input_txid)))

    input = TransactionInput(prevHash=preHash, prevIndex=preIndex)
    output = TransactionOutput(AssetId=assetId,
                               Value=f8amount_change,
                               script_hash=scripthash_from)

    tx = InvocationTransaction(outputs=[output], inputs=[input])
    tx.Version = 1
    context = ContractParametersContext(tx)
    tx.scripts = context.GetScripts()

    invoke_args = [
        nep5TokenId.ScriptHash, 'transfer',
        [
            bytearray.fromhex(hex_reverse(scripthash_from.ToString())),
            bytearray.fromhex(hex_reverse(scripthash_to.ToString())),
            BigInteger(f8amount)
        ]
    ]
    sb = ScriptBuilder()
    invoke_args.reverse()
    for item in invoke_args[:2]:
        if type(item) is list:
            item.reverse()
            listlength = len(item)
            for listitem in item:
                sb.push(listitem)
            sb.push(listlength)
            sb.Emit(PACK)
        else:
            sb.push(binascii.hexlify(item.encode()))

    sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray())

    op_data = sb.ToArray().decode()
    tx.Script = binascii.unhexlify(op_data)
    tx_data = get_tx_data(tx)[:-2]
    print("tx_data:", tx_data)
    signstr = binascii.hexlify(
        Crypto.Sign(message=tx_data, private_key=private_key)).decode()
    rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac"
    return rawtx_data
Example #6
0
def sign_message(encoded_message, private_key_hex):
    return Crypto.Sign(message=encoded_message.strip(),
                       private_key=private_key_hex).hex()
Example #7
0
def privtkey_sign(txData, privteKey):
    return binascii.hexlify(Crypto.Sign(message=txData,
                                        private_key=privteKey)).decode()
Example #8
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'A utility for signing messages.  Example usage: "like "neosign mymessage -n"'
    )
    parser.add_argument('message',
                        type=str,
                        nargs='?',
                        default=None,
                        help='The message in hex string format to be signed')
    parser.add_argument(
        '-n',
        '--nep2',
        action='store_true',
        help="Whether to use an NEP2 passhrase rather than a wallet")
    parser.add_argument('-w',
                        '--wif',
                        type=str,
                        default=None,
                        help='If using a wif pass in the wif')
    parser.add_argument('-i',
                        '--input',
                        type=str,
                        default=None,
                        help='Pass in file with signable contents')
    args = parser.parse_args()
    try:

        to_sign = None
        if args.message:
            to_sign = args.message

        elif args.input:
            f = open(args.input, 'r')
            to_sign = f.read()
            regex = re.compile(r'\s+')
            to_sign = regex.sub('', to_sign)

        if args.nep2:

            nep2_key = prompt('[nep2 key]> ', is_password=True)
            nep2_passwd = prompt("[nep2 key password]> ", is_password=True)

            prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
            keypair = KeyPair(priv_key=prikey)
            address = addr_from_pubkey(keypair.PublicKey)
            print("Signing With Address %s " % address)
            signature = Crypto.Sign(to_sign, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.wif:
            prikey = KeyPair.PrivateKeyFromWIF(args.wif)
            keypair = KeyPair(priv_key=prikey)
            address = addr_from_pubkey(keypair.PublicKey)
            print("Signing With Address %s " % address)
            signature = Crypto.Sign(to_sign, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        else:
            raise Exception("Please Specify -n or -w")
    except Exception as e:
        print("Could not sign: %s " % e)
Example #9
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'A utility for signing messages.  Example usage: "np-sign mymessage --wallet_file path/to/my/wallet" or use an NEP2 key/passphrase like "np-sign mymessage -n"'
    )
    parser.add_argument('message',
                        type=str,
                        help='The message in string format to be signed')
    parser.add_argument(
        '-w',
        '--wallet_file',
        type=str,
        default=None,
        help='If using a wallet file, the path to the wallet file')
    parser.add_argument(
        '-a',
        '--address',
        type=str,
        default=False,
        help=
        'If using a wallet file with more than 1 address, the address you would like to use.  Otherwise the default address will be used'
    )
    parser.add_argument(
        '-n',
        '--nep2',
        action='store_true',
        help="Whether to use an NEP2 passhrase rather than a wallet")
    parser.add_argument('--wif',
                        type=str,
                        default=None,
                        help='If using a wif pass in the wif')
    args = parser.parse_args()
    try:

        if args.wallet_file:

            passwd = prompt('[Wallet password]> ', is_password=True)
            wallet = UserWallet.Open(args.wallet_file, to_aes_key(passwd))

            contract = wallet.GetDefaultContract()
            if args.address:
                addr = args.address
                script_hash = Helper.AddrStrToScriptHash(addr)
                contract = wallet.GetContract(script_hash)

                if contract is None:
                    raise Exception('Address %s not found in wallet %s ' %
                                    (addr, args.wallet_file))

            print("Signing With Address %s " % contract.Address)
            signature, pubkey = wallet.SignMessage(args.message,
                                                   contract.ScriptHash)

            pubkey = pubkey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.nep2:

            nep2_key = prompt('[nep2 key]> ', is_password=True)
            nep2_passwd = prompt("[nep2 key password]> ", is_password=True)

            prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd)
            keypair = KeyPair(priv_key=prikey)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

        elif args.wif:
            prikey = KeyPair.PrivateKeyFromWIF(args.wif)
            keypair = KeyPair(priv_key=prikey)
            contract = Contract.CreateSignatureContract(keypair.PublicKey)
            print("Signing With Address %s " % contract.Address)
            signature = Crypto.Sign(args.message, prikey)

            pubkey = keypair.PublicKey.encode_point().decode('utf-8')
            signature = signature.hex()
            print("pubkey, sig: %s %s " % (pubkey, signature))

    except Exception as e:
        print("Could not sign: %s " % e)