Пример #1
0
def sharip(*args):
    h = SHA256.new()
    for x in args:
        h.update(x)
    h2 = RIPEMD160.new()
    h2.update(h.digest())
    return h2.digest()
Пример #2
0
def test(nb_chunks, chunk_size):
  h = RIPEMD160.new()
  f = open('test.txt', 'rb')
  for i in range(nb_chunks):
    h.update(f.read(chunk_size))
  f.close()
  d = h.hexdigest()
Пример #3
0
def key2address(public_key):
    x = SHA256.new(public_key).digest()
    x = RIPEMD160.new(x).digest()
    p = SHA256.new(x).digest()
    p = SHA256.new(p).digest()[:4]
    x = b"".join([x, p])
    return b64encode(x).encode()
Пример #4
0
    def is_valid(self, blockchain):
        """
        1. Find the prev tx
        2. Extract the output of the tx
        3. Execute the validation script
        4. Return the validation result
        :param blockchain: Blockchain in which we want to validate the transaction.
        :return: If tx is valid, return True, otherwise return False.
        """
        print("\t>> Validating transaction")
        prev_transaction = None
        for block in blockchain.blocks:
            for transaction in block.transactions:
                transaction_hash = transaction.get_hash()
                if transaction_hash == self.tx_input.prev_tx:
                    prev_transaction = transaction

        if prev_transaction is None:
            return False

        print("\t\t-- Found previous transaction")

        # Check values of BTC
        output_value = self.tx_output.value
        prev_transaction_value = prev_transaction.tx_output.value
        if output_value > prev_transaction_value:
            return False

        print("\t\t-- Values are correct")

        # Verifying hash of spender's Pk
        hash_output_prev_tx = prev_transaction.tx_output.hash_pubkey_recipient
        hash_object = RIPEMD160.new(self.tx_input.pk_spender.encode("utf-8"))
        hash_pk_spender = hash_object.hexdigest()

        # Can't spend the money, it's not for you
        if hash_pk_spender != hash_output_prev_tx:
            return False

        print("\t\t-- Pubkey hashes match")

        # Signature validation
        signature_input = self.tx_input.signature

        signature_information = prev_transaction.get_hash() + \
                                prev_transaction.tx_output.hash_pubkey_recipient + \
                                self.tx_output.hash_pubkey_recipient + \
                                str(self.tx_output.value)

        hash_signature_information = SHA256.new(signature_information.encode("utf-8"))
        public_key = ECC.import_key(self.tx_input.pk_spender)

        verifier = DSS.new(public_key, "fips-186-3")

        try:
            verifier.verify(hash_signature_information, signature_input)
            print("\t\t-- Signature verified")
            return True
        except ValueError:
            return False
def ripemd160_hash(data_bytes, times: int):
    if times == 0:
        return data_bytes
    hash_value = RIPEMD160.new(data_bytes)
    hash_value_bytes = hash_value.digest()
    times = times - 1
    return ripemd160_hash(hash_value_bytes, times)
Пример #6
0
 def __init__(self, lock, amount):
     self.lock = lock
     self.amount = amount
     temp_hash = hash(self)
     self.coin_hash = RIPEMD160.new(
         temp_hash.to_bytes(((temp_hash.bit_length() + 7) // 8),
                            byteorder='big')).hexdigest()
Пример #7
0
def ConvertPK2Address(pub_key):
    '''
    Converts Public Key to Address
    - pub-key (string): Public Key
    Returns (string): address
    '''
    h1 = SHA256.new()
    h1.update(pub_key)
    h1d = h1.hexdigest()
    #3. Perform RIPEMD-160 hashing on result
    h2 = RIPEMD160.new()
    h2.update(h1d)
    h2d = h2.hexdigest()
    #4. Add version byte in front of RIPEMD-160 hash (0x00 for Main Network
    h2d = b'00' + h2d
    #5. Perform SHA-256 hash on the extended RIPEMD-160 result
    h3 = SHA256.new()
    h3.update(h2d)
    h3d = h3.hexdigest()
    #6. Perform SHA-256 hash on the result of the previous SHA-256 hash
    h4 = SHA256.new()
    h4.update(h3d)
    h4d = h4.hexdigest()
    #7. Take the first 4 bytes of the second SHA-256 hash. This is the address checksum
    _bytes = h4d[:8]
    #8. Add the 4 checksum bytes from stage 7 at the end of extended RIPEMD-160 hash from stage 4. This is the 25-byte binary Bitcoin Address.
    add = h2d + _bytes
    #9. Convert the result from a byte string into a base58 string using Base58Check encoding.
    _c = base58.b58encode(add)
    return _c
Пример #8
0
    def send_message(self):

        while True:
            input_command = input()

            # This variable is set to True when is a server command
            send_message_to_server = True

            if input_command.startswith("cmd_show_addresses"):
                # This is not a server command
                send_message_to_server = False

                base_path = "public_keys/"
                for file in os.listdir(base_path):
                    pubkey_file = open(base_path + file)
                    pubkey = pubkey_file.read()

                    hash_object = RIPEMD160.new(data=pubkey.encode("utf-8"))
                    print("\t>>", hash_object.hexdigest(), "[", file, "]")

                    pubkey_file.close()
            else:
                message = input_command

            if send_message_to_server:
                self.socket.sendall(message.encode('utf-8'))
Пример #9
0
def sharip(*args):
    h= SHA256.new()
    for x in args:
        h.update(x)
    h2= RIPEMD160.new()
    h2.update(h.digest())
    return h2.digest()
Пример #10
0
    def check_client_id_owner_of_wallet(self):
        step1 = SHA256.new(self.__get_pubkey_bytes() +
                           self.sending_client_id.encode()).digest()
        derived_wid = "W" + RIPEMD160.new(step1).hexdigest()

        print("owner checkr: ", derived_wid == self.sending_wid)

        return derived_wid == self.sending_wid
Пример #11
0
def hash160(message):
    sha = SHA256.new()
    sha.update(message.encode('utf-8'))
    x = sha.hexdigest()
    ripemd = RIPEMD160.new()
    ripemd.update(x.encode('utf-8'))
    y = ripemd.hexdigest()
    return y
Пример #12
0
    def __set_wallet_id(self, pubkey):
        """
        set wallet id using public key of wallet
        :param pubkey:
        :return:
        """

        step1 = SHA256.new(pubkey + self.client_id_of_owner.encode()).digest()
        self.wallet_id = "W" + RIPEMD160.new(step1).hexdigest()
Пример #13
0
    def get_wallet_from_puk(input_RSA_puk):
        '''
        Class method, returns the Wallet object from the corresponding
        RSA Public Key for transaction verification.

        :param input_RSA_puk: STRING Representing the target RSA pubkey
        :return: Returns STRING representing the generated wallet
        '''
        return RIPEMD160.new(data=SHA256.new(data= input_RSA_puk).digest()).hexdigest()
Пример #14
0
def keypub_to_keypubhash(key_pub):
    h = SHA256.new()
    r = RIPEMD160.new()
    b = bytearray()
    b.extend(map(ord, key_pub))
    h.update(b)
    bb = bytearray()
    bb.extend(map(ord, h.hexdigest()))
    r.update(bb)
    return r.hexdigest()
Пример #15
0
    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Crypto.Hash import RIPEMD160

        self.description = "Unapproved hash (RIPEMD160) test"
        hash_obj = RIPEMD160.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
Пример #16
0
    def test_negative_unapproved_hashes(self):
        """Verify that unapproved hashes are rejected"""

        from Crypto.Hash import RIPEMD160

        self.description = "Unapproved hash (RIPEMD160) test"
        hash_obj = RIPEMD160.new()
        signer = DSS.new(self.key_priv, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
Пример #17
0
 def _string_to_key(data: str, key_len: int, suffix: bytes):
     whole = base58.b58decode(data)[:key_len + 4]
     h = RIPEMD160.new()
     h.update(whole[:key_len])
     if suffix:
         h.update(suffix)
     digest = h.digest()
     if digest[:4] != whole[-4:]:
         raise ValueError("Checksum doesn't match")
     return whole[:key_len]
Пример #18
0
    def test4(self):
        """Verify that unapproved hashes are rejected"""

        from Crypto.Hash import RIPEMD160

        self.description = "Unapproved hash (RIPEMD160) test"
        key = DSA.construct((self.Y, self.G, self.P, self.Q))
        hash_obj = RIPEMD160.new()
        signer = DSS.new(key, 'fips-186-3')
        self.assertRaises(ValueError, signer.sign, hash_obj)
        self.assertRaises(ValueError, signer.verify, hash_obj, b("\x00") * 40)
 def get_ripemd160(self):
     hash_obj = RIPEMD160.new()
     hash_obj.update(self.value)
     return {
         "digest":
         hash_obj.digest(),
         "hexdigets":
         hash_obj.hexdigest(),
         "warning":
         "WARNING: Insecure and vulnerable to length-extension attacks."
     }
Пример #20
0
def script_to_program_hash(signature_redeem_script_bytes: bytes):
    temp = SHA256.new(signature_redeem_script_bytes)
    md = RIPEMD160.new(data=temp.digest())
    f = md.digest()
    sign_type = signature_redeem_script_bytes[
        len(signature_redeem_script_bytes) - 1]
    if sign_type == STANDARD:
        f = bytes([33]) + f
    if sign_type == MULTISIG:
        f = bytes([18]) + f
    return f
Пример #21
0
    def check_client_id_owner_of_wallet(self):
        step1 = SHA256.new(
            WalletPKI.generate_key_from_parts(
                x=self.non_json_wallet_pubkey["x"],
                y=self.non_json_wallet_pubkey["y"],
                in_bytes=True) + self.client_id.encode()).digest()
        derived_wid = "W" + RIPEMD160.new(step1).hexdigest()

        print("owner check: ", derived_wid == self.wallet_id)

        return derived_wid == self.wallet_id
Пример #22
0
    def __set_wallet_id(self, pubkey):
        """
        set wallet id using public key of wallet
        :param pubkey: bytes
        :return:
        """

        step1 = SHA256.new(
            self.wallet_pki.load_pub_key(importedKey=False,
                                         user_or_wallet="wallet") +
            self.client_id_of_owner.encode()).digest()
        self.wallet_id = "W" + RIPEMD160.new(step1).hexdigest()
Пример #23
0
    def Ripemd160(data: Union[bytes, str]) -> bytes:
        """
        Compute the RIPEMD-160 of the specified bytes.

        Args:
            data (str or bytes): Data

        Returns:
            bytes: Computed RIPEMD-160
        """
        h = RIPEMD160.new()
        h.update(AlgoUtils.Encode(data))
        return h.digest()
def make_RIPEMD160_hash(message: 'byte stream') -> 'string':
    """
    RIPEMD-160 is a cryptographic algorithm that emits a 20 byte message digest.
    This function computes the RIPEMD-160 message digest of a message and returns
    the hexadecimal string encoded representation of the message digest (40 bytes).
    """
    # convert message to an ascii byte stream
    bstr = bytes(message, 'ascii')
    # generate the RIPEMD hash of message
    h = RIPEMD160.new()
    h.update(bstr)
    # convert to a hexadecimal encoded string
    hash = h.hexdigest()
    return hash
Пример #25
0
    def gerarEndereco(self):

        chavePublica = '04' + binascii.hexlify(
            self.chavePublica.to_string()).decode()
        hash256 = hashlib.sha256(binascii.unhexlify(chavePublica))
        ripemd160 = RIPEMD160.new()
        ripemd160.update(hash256.hexdigest().encode())
        hash160 = ripemd160.hexdigest()
        enderecoPublico_a = b"\x00" + hash160.encode()
        checksum = hashlib.sha256(
            hashlib.sha256(enderecoPublico_a).digest()).digest()[:4]
        enderecoPublico_b = base58.b58encode(enderecoPublico_a + checksum)

        return enderecoPublico_b.decode()
Пример #26
0
    def _key_to_string(key: bytearray, key_len: int, suffix: bytes,
                       prefix: str):
        if len(key) != key_len:
            raise ValueError("Key is not correct size")

        h = RIPEMD160.new()
        h.update(key)
        h.update(suffix)
        digest = h.digest()

        whole = bytearray(key)
        whole += digest

        return prefix + base58.b58encode(whole).decode()
Пример #27
0
def md_sha_hash(flag, text):
    hash_text = None
    if flag == 'MD2':
        h = MD2.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD4':
        h = MD4.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD5':
        h = MD5.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA1':
        h = SHA1.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA224':
        h = SHA224.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA256':
        h = SHA256.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA384':
        h = SHA384.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA512':
        h = SHA512.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD':
        h = RIPEMD.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD160':
        h = RIPEMD160.new()
        h.update(text)
        hash_text = h.hexdigest()
    else:
        return {'error': False, 'msg': u'未知hash算法!'}
    return {'error': True, 'msg': hash_text}
Пример #28
0
    def ripe160_hasher(data, hash_form="hex"):
        """
        used to hash data with RIPEMD160 algorithm
        :param data: data to be hashed
        :type data: str
        :param hash_form: format to return hash 'hex, or 'byte' default is 'hex'
        :type hash_form: str
        :return: hex or bytes of hash
        """

        if not isinstance(data, (bytes, str)):
            data = str(data).encode()
        elif isinstance(data, str):
            data = data.encode()

        h = RIPEMD160.new(data)

        if hash_form == "hex":
            return h.hexdigest()
        elif hash_form == "byte":
            return h.digest()
Пример #29
0
    def __create_admin_id(self):

        step1 = SHA256.new(self.pubkey).digest()
        return "VID-" + RIPEMD160.new(step1).hexdigest()
Пример #30
0
def pubkey_to_hash(pubkey):
    return RIPEMD160.new(SHA256.new(pubkey).digest()).digest()
Пример #31
0
def _ripemd160_new(*args):
    from Crypto.Hash import RIPEMD160
    _new_funcs['RIPEMD160'] = _new_funcs['ripemd160'] = _new_funcs['RIPEMD'] = _new_funcs['ripemd'] = RIPEMD160.new
    return RIPEMD160.new(*args)
Пример #32
0
def _ripemd160_new(*args):
    from Crypto.Hash import RIPEMD160
    _new_funcs['RIPEMD160'] = _new_funcs['ripemd160'] = _new_funcs[
        'RIPEMD'] = _new_funcs['ripemd'] = RIPEMD160.new
    return RIPEMD160.new(*args)
Пример #33
0
def hash_160(public_key):
  if not have_crypto:
    return ''
  h1 = SHA256.new(public_key).digest()
  h2 = RIPEMD160.new(h1).digest()
  return h2
Пример #34
0
def hash_160(public_key):
    if not have_crypto:
        return ''
    h1 = SHA256.new(public_key).digest()
    h2 = RIPEMD160.new(h1).digest()
    return h2
Пример #35
0
    def hash_pubkey(self):
        public_key = self.load_public_key()

        hash_object = RIPEMD160.new(public_key.encode("utf-8"))
        hash_public_key = hash_object.hexdigest()
        return hash_public_key