Ejemplo n.º 1
0
def generate(clan_tag):
    try:
        _ = int(clan_tag, 16)
    except ValueError:
        print(f'Error: "{clan_tag}" is not valid hex.')
        exit(1)

    n = len(clan_tag)
    while True:
        # Generate a private key
        p_hash_obj = keccak.new(digest_bits=256)
        seed = secrets.token_bytes(32)
        p_hash_obj.update(seed)
        p = p_hash_obj.digest()

        # Derive the public key
        q = PublicKey.from_valid_secret(p).format(compressed=False)[1:]

        # Hash public key into account address
        addr_hash_obj = keccak.new(digest_bits=256)
        addr_hash_obj.update(q)
        address = addr_hash_obj.digest()[-20:]
        if address.hex()[-n:] == clan_tag:
            print('Seed       : ' + seed.hex())
            print('Private key: ' + p_hash_obj.hexdigest())
            print('Public key : ' + q.hex())
            print('Address    : ' + address.hex())
            print('Never share the seed or private key with anyone!')
            print('Never share the seed or private key with anyone!')
            print('Never share the seed or private key with anyone!')
            break
Ejemplo n.º 2
0
def create_merkle_root(tx_id_set):
    num = len(tx_id_set)
    relist = []
    if num == 1:
        return str(tx_id_set[0])
    i = 0
    if num % 2 == 1:
        tx_id_set[num] = tx_id_set[num - 1]
        num = num + 1
    keccak_hash = keccak.new(digest_bits=256)

    while True:
        keccak_hash.update(str(tx_id_set[i]).encode('ascii'))
        tmp1 = keccak_hash.hexdigest()
        tmp11 = str(tmp1)
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(str(tx_id_set[i + 1]).encode('ascii'))
        tmp2 = keccak_hash.hexdigest()
        tmp22 = str(tmp2)

        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update((tmp11 + tmp22).encode('ascii'))
        relist.append(keccak_hash.hexdigest())

        i = i + 2
        if i >= num:
            break

    create_merkle_root(relist)
Ejemplo n.º 3
0
    def get_authentication_response(self, request, as_json=False):
        if type(request) == str:
            request = json_loads(request)
        response = {"success": True, "data": {}}
        response["data"]["authenticated"] = True
        address = self.db.get_address(request["token"])

        keccak_hash = keccak.new(digest_bits=256)
        #keccak_hash.update(rlp.encode(self.get_nonce(request["token"], address)))
        keccak_hash.update(
            self.get_nonce(request["token"], address).encode('utf-8'))
        nonce_hash = keccak_hash.digest()
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(nonce_hash)
        nonce_hash = keccak_hash.digest()

        new_address = PublicKey.recover_from_msg_hash(
            nonce_hash,
            Signature(bytes.fromhex(request["signature"][2:]))).to_address()

        response["data"]["authenticated"] = address == new_address
        self.db.auth(request["token"],
                     authenticated=response["data"]["authenticated"])
        if as_json:
            return response
        return json_dumps(response)
Ejemplo n.º 4
0
def pubhex2address_ethereum(pubhex):
    """Public Key Hex -> Ethereum Address"""

    from Crypto.Hash import keccak
    pubhex_bytes = bytes.fromhex(pubhex)
    # address_body = keccak256((pubkey)[-20:]
    truncated_hashed_pubkey_bytes = keccak.new(data=pubhex_bytes,
                                               digest_bits=256).digest()[-20:]
    address_body = truncated_hashed_pubkey_bytes.hex()

    # Element-wise hex-to-hex comparison
    # checksum_reference = hex(keccak256(hex(address_body)))[:20]
    # checksummed_address_body = stringify([ a.uppercase() if c>=8 else a for (a,c) in zip(address_body, checksum_reference) ])
    checksum = keccak.new(data=address_body.encode(),
                          digest_bits=256).hexdigest()
    checksum_address = '0x'
    for i in range(len(address_body)):
        address_char = address_body[i]
        checksum_char = checksum[i]
        if int(checksum_char, 16) >= 8:
            checksum_address += address_body[i].upper()
        else:
            checksum_address += address_body[i]
    # address = concat('0x', checksummed_address_body)
    return checksum_address
Ejemplo n.º 5
0
 def test_update(self):
     pieces = [bchr(10) * 200, bchr(20) * 300]
     h = keccak.new(digest_bytes=64)
     h.update(pieces[0]).update(pieces[1])
     digest = h.digest()
     h = keccak.new(digest_bytes=64)
     h.update(pieces[0] + pieces[1])
     self.assertEqual(h.digest(), digest)
Ejemplo n.º 6
0
 def test_update(self):
     pieces = [bchr(10) * 200, bchr(20) * 300]
     h = keccak.new(digest_bytes=64)
     h.update(pieces[0]).update(pieces[1])
     digest = h.digest()
     h = keccak.new(digest_bytes=64)
     h.update(pieces[0] + pieces[1])
     self.assertEqual(h.digest(), digest)
Ejemplo n.º 7
0
    def init_validator(address):
        ValidatorContract = w3.eth.contract(abi=VALIDATOR_ABI,
                                            bytecode=VALIDATOR_SOL["object"])
        txn_dict = {'from': address}
        tx_hash = ValidatorContract.constructor(
            Solver.CHUNK_SIZE).transact(txn_dict)
        tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
        validator_address = tx_receipt.contractAddress

        validator_contract = w3.eth.contract(
            address=validator_address,
            abi=VALIDATOR_ABI,
        )
        for file_name in os.listdir('./Files'):
            file = open('./Files/' + file_name, 'rb')
            content = file.read()
            file.close()
            chunk = ""
            chunks = []
            merkle_level = []
            merkle_tree = []
            size = len(content)
            chunks_num = int(math.ceil(len(content) / Solver.CHUNK_SIZE))
            for i in range(chunks_num):
                chunk = content[i * Solver.CHUNK_SIZE:(i + 1) *
                                Solver.CHUNK_SIZE]
                chunks.append(chunk)
                k = keccak.new(digest_bits=256)
                k.update(chunk)
                merkle_level.append(k.digest())
            if chunks_num % 2:
                merkle_level.append(b'\x00' * 32)
            merkle_tree.append(merkle_level)
            high = 0
            if chunks_num == 1:
                high = 1
            else:
                high = int(math.ceil(math.log(chunks_num, 2)))
            for _ in range(high):
                prev_level = merkle_level
                merkle_level = []
                for i in range(int(len(prev_level) / 2)):
                    k = keccak.new(digest_bits=256)
                    k.update(prev_level[2 * i])
                    k.update(prev_level[2 * i + 1])
                    merkle_level.append(k.digest())
                if int(len(prev_level) / 2) % 2:
                    merkle_level.append(b'\x00' * 32)
                merkle_tree.append(merkle_level)
            merkle_tree[-1] = [merkle_level[0]]
            merkle_root = merkle_level[0]
            file = open('./FilesData/' + file_name + '.data', 'wb')
            pickle.dump([chunks, merkle_tree], file)
            file.close()
            tx_hash = validator_contract.functions.add_file_info(
                file_name, size, merkle_root).transact(txn_dict)
            tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
        return validator_address
Ejemplo n.º 8
0
    def sig_test2(self, token, address, signature):
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(self.get_nonce(token, address).encode('utf-8'))
        nonce_hash = keccak_hash.digest()
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(nonce_hash)
        nonce_hash = keccak_hash.digest()

        new_address = PublicKey.recover_from_msg_hash(
            nonce_hash, Signature(bytes.fromhex(signature))).to_address()

        return address == new_address
Ejemplo n.º 9
0
    def test_new_positive(self):

        for digest_bits in (224, 256, 384, 512):
            hobj = keccak.new(digest_bits=digest_bits)
            self.assertEqual(hobj.digest_size, digest_bits // 8)

            hobj2 = hobj.new()
            self.assertEqual(hobj2.digest_size, digest_bits // 8)

        for digest_bytes in (28, 32, 48, 64):
            hobj = keccak.new(digest_bytes=digest_bytes)
            self.assertEqual(hobj.digest_size, digest_bytes)

            hobj2 = hobj.new()
            self.assertEqual(hobj2.digest_size, digest_bytes)
Ejemplo n.º 10
0
    def test_new_positive(self):

        for digest_bits in (224, 256, 384, 512):
            hobj = keccak.new(digest_bits=digest_bits)
            self.assertEqual(hobj.digest_size, digest_bits // 8)

            hobj2 = hobj.new()
            self.assertEqual(hobj2.digest_size, digest_bits // 8)

        for digest_bytes in (28, 32, 48, 64):
            hobj = keccak.new(digest_bytes=digest_bytes)
            self.assertEqual(hobj.digest_size, digest_bytes)

            hobj2 = hobj.new()
            self.assertEqual(hobj2.digest_size, digest_bytes)
Ejemplo n.º 11
0
    def test_update_after_digest(self):
        msg=b("rrrrttt")

        # Normally, update() cannot be done after digest()
        h = keccak.new(digest_bits=512, data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = keccak.new(digest_bits=512, data=msg).digest()

        # With the proper flag, it is allowed
        h = keccak.new(digest_bits=512, data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)
Ejemplo n.º 12
0
    def __generateParcialHashes(self,finger=None):

        pk = None
        while pk == None:
            try:
                pk = self.__getPrivateKey()
            except ValueError:
                pass
        
        ivs = []
        my_file = Path(self.pathIvs)
        if my_file.is_file():
            with open(my_file,'rb') as f:
                for i in range(self.numSalt):
                    iv = f.read(16)
                    ivs.append(iv)
        else:
            raise IOError('Ivs\'s file not found.')
        
        salt = self.contract.functions.getSalt().call()  #lo devuelve directamente en binario!        
        salt = cipher.decrypt(salt,pk,ivs)
        
        if finger == None:
            fp = FingerPrinter()
            finger = fp.getFingerprinting()
            
        hashes = []
        for i in range(self.numSalt):
            k = keccak.new(digest_bits=256)
            k.update(salt[i])
            k.update(finger[i].encode())
            hashes.append(k.digest()) 
            
        return hashes
Ejemplo n.º 13
0
 def __generateFinalHash(self,hashes):
     
     k = keccak.new(digest_bits=256)        
     for i in range(len(hashes)):
         k.update(hashes[i])
         
     return k.digest() 
Ejemplo n.º 14
0
def _decrypt_utc_aes_128_ctr(pwd: bytes, utc_data: Dict) -> bytes:
    """
    Decrypt AES 128 CTR.
    Requires plain text password and Ether UTC file as JSON object.
    """
    # Decrypt
    utc_cipher_data = utc_data["Crypto"]
    # Check that we have supported KDF
    cur_kdf = utc_cipher_data["kdf"]
    assert cur_kdf in SUPPORTED_KDFS, f"Unsupported KDF: {cur_kdf}"

    kdf_params = utc_cipher_data["kdfparams"]
    # Delegate to the KDF
    derived_key = SUPPORTED_KDFS[cur_kdf](pwd, kdf_params)
    assert len(
        derived_key
    ) == 32, f"Derived key: Expected length 32, got {len(derived_key)}"

    # Decryption key is only the first 16 bytes
    dec_key = derived_key[:16]
    # Convert cipher text from HEX to binary data
    cipher_text = binascii.unhexlify(utc_cipher_data["ciphertext"])
    # Convert IV from HEX to int
    aes_iv_int = int(utc_cipher_data["cipherparams"]["iv"], 16)
    counter = Counter.new(nbits=8, initial_value=aes_iv_int)
    cipher = AES.new(dec_key, AES.MODE_CTR, counter=counter)
    dec_priv_key = cipher.decrypt(cipher_text)

    # MAC in v3 is the KECCAK-256 of the last 16 bytes of the derived key and cipher text
    expected_mac = utc_cipher_data["mac"]
    keccak_256 = keccak.new(digest_bits=256)
    keccak_256.update(derived_key[-16:] + cipher_text)
    actual_mac = keccak_256.hexdigest()
    assert actual_mac == expected_mac, f"MAC error: Expected {expected_mac} != {actual_mac}"
    return dec_priv_key
Ejemplo n.º 15
0
def pubkey_to_addr(pubkey: str) -> str:
    pub_int = int(pubkey, 16)
    keccak_hash = keccak.new(digest_bits=256)
    keccak_hash.update(pub_int.to_bytes(64, 'big'))
    addr = keccak_hash.hexdigest()
    addr = '0x' + addr[-40:]
    return addr
Ejemplo n.º 16
0
    def SignPayloadForm(self, requestBodyJson, extraPayload):
        # hash the payload
        msgBytes = bytearray(requestBodyJson, "utf-8")
        msgHashHex = keccak.new(data=msgBytes, digest_bits=256).hexdigest()
        msgHash = bytearray.fromhex(msgHashHex)

        # create the signature
        privKey = web3.Account.from_key(self._privateKey)
        signature = privKey.signHash(msgHash)
        signatureFinal = signature.signature.hex()[2:130]
        if (len(signatureFinal) != 128):
            raise Exception("signature doesn't have length of 128")

        # get public key as hex
        pubHex = self._masterKey.public_compressed_hex

        newDict = dict()
        newDict["requestBody"] = (None, requestBodyJson,
                                  "text/plain; charset=utf-8")
        newDict['signature'] = (None, signatureFinal,
                                "text/plain; charset=utf-8")
        newDict['publicKey'] = (None, pubHex, "text/plain; charset=utf-8")

        for payloadKey, payloadValue in extraPayload.items():
            newDict[payloadKey] = payloadValue

        return newDict
Ejemplo n.º 17
0
def _derive_key(password: str) -> bytes:
    """ keccak256(password) """
    passwd_bytes = password.encode()
    keccak_hash = keccak.new(digest_bits=256)
    keccak_hash.update(passwd_bytes)
    key = keccak_hash.hexdigest()
    return bytes.fromhex(key)
Ejemplo n.º 18
0
def compile_digest(topic, user, inputdata, tim, epoch=1):

    # protocolversion + padding 7 bytes
    data = "\x00\x00\x00\x00\x00\x00\x00\x00"

    # topic bytes
    data += topic

    # user account bytes
    data += user

    # time now little endian
    # time is 7 bytes, actually
    data += struct.pack("<L", tim)
    data += "\x00\x00\x00"

    # ... so we put the epoch on the eigth
    data += chr(epoch)

    # add the data itself
    data += inputdata

    # fire up hasher
    h = keccak.new(digest_bits=256)
    h.update(data)
    return h.digest()
Ejemplo n.º 19
0
def exploit():
    assert w3.isConnected()
    latest_block = w3.eth.getBlock("latest")
    latest_block_hash = latest_block["hash"]

    keccak256 = keccak.new(digest_bits=256)
    keccak256.update(latest_block_hash)
Ejemplo n.º 20
0
 def derive_eth_address(self, prv):
     public = self.point(prv)
     buffer = public.x.to_bytes(32, self.endianness) + public.y.to_bytes(
         32, self.endianness)
     k = keccak.new(digest_bits=256)
     k.update(buffer)
     return '0x' + k.hexdigest()[24:]
Ejemplo n.º 21
0
    def __init__(self, string, soft=True):
        # Get Private Key
        private_key = NewPrivateKey(string, soft)
        self.printable_pk = private_key
        self.private_key = unhexlify(private_key.encode('ascii'))

        # Generate Seed
        seed = mnemonic.mn_encode(
            self.printable_pk)  # TODO Create MyEther Mnemonic Seed
        seed.append(mnemonic.mn_checksum(seed))
        self.seed = seed
        self.readable_seed = self.readable_seed(seed)
        self.readable_seed_for_terminal_app = self.readable_seed_for_terminal_app(
            seed)

        # Get Public Key
        self.sk = SigningKey.from_string(self.private_key, curve=SECP256k1)
        self.vk = self.sk.verifying_key
        public_key_bytes = hexlify(self.vk.to_string())

        # Get Ethereum Address
        public_key_bytes = decode(public_key_bytes, 'hex')
        k = keccak.new(digest_bits=256)
        k.update(public_key_bytes)
        raw_address = k.hexdigest()
        self.address = "0x" + raw_address[-40:]
Ejemplo n.º 22
0
def deposit(amount, net='main'):
    web3 = Web3(Web3.HTTPProvider(nets[net]['provider']))
    nonce = web3.eth.getTransactionCount(nets[net]['address'])
    method = b'transfer(address,uint256)'

    # method = b"buy()"
    s = keccak.new(digest_bits=256)
    s.update(method)
    method_hash = s.hexdigest()

    data = str(method_hash[:8] +
               fill_up_bytes(nets[net]['deposit_address'][2:]) +
               fill_up_bytes(format(amount, '02x')))
    raw_bytes = codecs.decode(data, 'hex')
    result = signTransaction(nets[net]['token_contract'],
                             0,
                             nets[net]['privkey'],
                             nonce=nonce,
                             data=raw_bytes,
                             gas=100000,
                             gasPrice=(web3.eth.gasPrice * 2))
    if 'sign' in result:
        try:
            result = json.loads(
                broadcastTransaction(nets[net]['api'] + "/api",
                                     nets[net]['key'], result['sign']))
            return (nets[net]['api'] + "/tx/" + result['result'])
        except Exception as e:
            print(e)
 def get_keccak_512_bits(self):
     hash_obj = keccak.new(digest_bits=512)
     hash_obj.update(self.value)
     return {
         "digest": hash_obj.digest(),
         "hexdigets": hash_obj.hexdigest(),
     }
Ejemplo n.º 24
0
    def test_update_after_digest(self):
        msg = b("rrrrttt")

        # Normally, update() cannot be done after digest()
        h = keccak.new(digest_bits=512, data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = keccak.new(digest_bits=512, data=msg).digest()

        # With the proper flag, it is allowed
        h = keccak.new(digest_bits=512, data=msg[:4], update_after_digest=True)
        self.assertEqual(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEqual(h.digest(), dig2)
Ejemplo n.º 25
0
def test_deploy_delegation_aware_atoken():
    # Dependent contracts
    accounts[0].deploy(ReserveLogic)
    accounts[0].deploy(GenericLogic)
    accounts[0].deploy(ValidationLogic)
    lending_pool = accounts[0].deploy(LendingPool)
    weth9 = accounts[0].deploy(WETH9)

    ### DelegationAwareAToken ###
    atoken = accounts[0].deploy(
        DelegationAwareAToken,
        lending_pool.address,
        weth9, ZERO_ADDRESS,
        'Aave interest bearing WETH',
        'aWETH',
        ZERO_ADDRESS
    )

    # DelegationAwareAToken constants and getters
    assert atoken.POOL() == lending_pool.address
    assert atoken.UNDERLYING_ASSET_ADDRESS() == weth9.address
    assert atoken.RESERVE_TREASURY_ADDRESS() == ZERO_ADDRESS
    hasher = keccak.new(digest_bits=256)
    hasher.update(b'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)')
    assert str(atoken.PERMIT_TYPEHASH())[2:] == hasher.hexdigest()
Ejemplo n.º 26
0
    def signPayloadDict(self, requestBodyJson):
        # hash the payload
        msgBytes = bytearray(requestBodyJson, "utf-8")
        msgHashHex = keccak.new(data=msgBytes, digest_bits=256).hexdigest()
        msgHash = bytearray.fromhex(msgHashHex)

        # create the signature
        privKey = web3.Account.from_key(self._privateKey)
        signature = privKey.signHash(msgHash)

        # signatureFinal = format(signature.r, 'x') + format(signature.s, 'x')
        signatureFinal = signature.signature.hex()[2:130]
        if len(signatureFinal) != 128:
            raise Exception("signature doesn't have the length of 128")

        # get public key as hex
        pubHex = self._masterKey.public_compressed_hex

        newDict = dict()
        newDict["requestBody"] = requestBodyJson
        newDict["signature"] = signatureFinal
        newDict["publicKey"] = pubHex
        newDict["hash"] = msgHashHex

        return newDict
Ejemplo n.º 27
0
    def del_eth_address(self, token='', private_key=''):

        # Create Address Object.
        private_key = self.remove0xHeader(private_key)

        privKey = eth_keys.keys.PrivateKey(binascii.unhexlify(private_key))
        address  = privKey.public_key.to_checksum_address()
        keccak_hash = keccak.new(digest_bits=256)
        keccak_hash.update(address.encode())
        hash_msg = keccak_hash.digest()
        signature = privKey.sign_msg_hash(hash_msg)


        payload = self.makeJsonRpcRequest(API_DEL_ETH_ADDRESS, token)
        payload["params"]["address"]  = address
        payload["params"]["public_key"]  = self.remove0xHeader(privKey.public_key.to_hex())
        payload["params"]["signature"] = self.formSignature(signature.to_hex())
       
        res = requestsPost( self.config['api_end_point'], data=json.dumps(payload))

        if res.status_code != 200:
            return False
        
        data = res.json()

        if data['id'] != payload['id']:
            return False
       
        if data["result"]["err_code"] == 0:
            return True
        else:
            return False
Ejemplo n.º 28
0
def sha3_256(data):
    if isinstance(data, str):
        d = bytes(data, "utf-8")
    else:
        d = bytes(data)

    return keccak.new(digest_bits=256, data=d).digest()
Ejemplo n.º 29
0
 def createMetadatakeyAndKeystring(self, folder):
     folder = folder
     folderKey = Helper.getFolderHDKey(self._masterKey, folder)
     metaDataKey = Helper.getMetaDataKey(folderKey)
     keyString = keccak.new(data=bytearray(folderKey.private_hex, "utf-8"),
                            digest_bits=256).hexdigest()
     return {"metadataKey": metaDataKey, "keyString": keyString}
Ejemplo n.º 30
0
 def get_by_name(self, name):
     id_ = self.name_to_id(name)
     res = self.__get_raw(id_)
     hash_obj = keccak.new(data=res[0].encode("utf8"), digest_bits=256)
     hash_str = "0x" + hash_obj.hexdigest()[:13]
     res.append(hash_str)
     return res
    def __oauth_challenge_calculate(self, challenge_data):
        if challenge_data['algorithm']['name'] != 'hashcash' :
            logging.error('unknown proof-of-work algorithm')
            return None

        prefix = '0' * challenge_data['complexity']
        hashcash_str = '%s:%s:%s:%s:%s:%s:' % (
            challenge_data['algorithm']['version'], 
            challenge_data['complexity'], 
            challenge_data['timestamp'], 
            challenge_data['algorithm']['resourse'], 
            challenge_data['algorithm']['extension'], 
            challenge_data['random_string'])
        hashcash_str = hashcash_str.encode('utf-8')

        pow_number = 0
        while True:
            keccak_hash = keccak.new(digest_bits=512)
            keccak_hash.update(hashcash_str+str(pow_number).encode('utf-8'))
            digest = keccak_hash.hexdigest()

            if digest.startswith(prefix):
                return pow_number

            pow_number = pow_number + 1
Ejemplo n.º 32
0
def cmd_passwordSearch():

    # initialize a string
    password = input("\n Enter your password:"******"\nSHA3-224 Hash: ", obj_sha3_224.hexdigest())
    print("\nSHA3-256 Hash: ", obj_sha3_256.hexdigest())
    print("\nSHA3-384 Hash: ", obj_sha3_384.hexdigest())
    print("\nSHA3-512 Hash: ", obj_sha3_512.hexdigest())
    print("\nSHA3-keccak-512 Hash: ", keccak_hash.hexdigest())
    sha3k512 = keccak_hash.hexdigest()

    sub_pass = sha3k512[0:10]

    #print("First 10 characters from the password:"******"https://passwords.xposedornot.com/api/v1/pass/anon/" + sub_pass)
    json_data = json.loads(response.text)
    print("\nOutput:", json_data)
Ejemplo n.º 33
0
    def SignPayloadForm(self, requestBodyJson, extraPayload):
        # hash the payload
        msgBytes = bytearray(requestBodyJson, "utf-8")
        msgHashHex = keccak.new(data=msgBytes, digest_bits=256).hexdigest()
        msgHash = bytearray.fromhex(msgHashHex)

        # create the signature
        privKey = web3.Account.from_key(self._privateKey)
        signature = privKey.signHash(msgHash)

        # signature2 = format(signature.r, 'x') + format(signature.s, 'x')
        signatureFinal = signature.signature.hex()[2:130]
        # signatureFinal = "685789e0865e9ac9f81c6629d6e069eb104e171d15e68d3085d8e44b3b8954df2f0dd358a8797826ea2584632cc17effaea85317cf2baac3fd8f1f3b884bde6b"
        if (len(signatureFinal) != 128):
            raise Exception("signature doesn't has the length of 128")

        # print(signatureFinal)

        # get public key as hex
        pubHex = self._masterKey.public_compressed_hex

        newDict = dict()
        newDict["requestBody"] = (None, requestBodyJson,
                                  "text/plain; charset=utf-8")
        newDict['signature'] = (None, signatureFinal,
                                "text/plain; charset=utf-8")
        newDict['publicKey'] = (None, pubHex, "text/plain; charset=utf-8")
        # newDict["hash"] = msgHashHex

        for payloadKey, payloadValue in extraPayload.items():
            newDict[payloadKey] = payloadValue

        return newDict
Ejemplo n.º 34
0
    def test_digest(self):
        h = keccak.new(digest_bytes=64)
        digest = h.digest()

        # hexdigest does not change the state
        self.assertEqual(h.digest(), digest)
        # digest returns a byte string
        self.failUnless(isinstance(digest, type(b("digest"))))
Ejemplo n.º 35
0
    def test_hex_digest(self):
        mac = keccak.new(digest_bits=512)
        digest = mac.digest()
        hexdigest = mac.hexdigest()

        # hexdigest is equivalent to digest
        self.assertEqual(hexlify(digest), tobytes(hexdigest))
        # hexdigest does not change the state
        self.assertEqual(mac.hexdigest(), hexdigest)
        # hexdigest returns a string
        self.failUnless(isinstance(hexdigest, type("digest")))
Ejemplo n.º 36
0
    def test_new_negative(self):

        # keccak.new needs digest size
        self.assertRaises(TypeError, keccak.new)

        h = keccak.new(digest_bits=512)

        # Either bits or bytes can be specified
        self.assertRaises(TypeError, keccak.new,
                              digest_bytes=64,
                              digest_bits=512)

        # Range
        self.assertRaises(ValueError, keccak.new, digest_bytes=0)
        self.assertRaises(ValueError, keccak.new, digest_bytes=1)
        self.assertRaises(ValueError, keccak.new, digest_bytes=65)
        self.assertRaises(ValueError, keccak.new, digest_bits=0)
        self.assertRaises(ValueError, keccak.new, digest_bits=1)
        self.assertRaises(ValueError, keccak.new, digest_bits=513)
Ejemplo n.º 37
0
 def test_update_negative(self):
     h = keccak.new(digest_bytes=64)
     self.assertRaises(TypeError, h.update, u"string")
Ejemplo n.º 38
0
    def sha3_256(x): return keccak.new(digest_bits=256, data=x.encode()).digest()
except:
Ejemplo n.º 39
0
""")
    scrypt = None
try:
    import bitcoin
except ImportError:
    sys.stderr.write("""
Failed to import bitcoin. This is not a fatal error but does
mean that you will not be able to determine the address from
your wallet file.
""")
import binascii
import struct
from math import ceil
from Crypto.Hash import keccak
sha3_256 = lambda x: keccak.new(digest_bits=256, data=x)
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto.Util import Counter

# TODO: make it compatible!


SCRYPT_CONSTANTS = {
    "n": 262144,
    "r": 1,
    "p": 8,
    "dklen": 32
}

PBKDF2_CONSTANTS = {
Ejemplo n.º 40
0
 def new_test(self, data=data, result=tv.md):
     hobj = keccak.new(digest_bits=512, data=data)
     self.assertEqual(hobj.digest(), result)
Ejemplo n.º 41
0
def keccak_256(data):
    return keccaklib.new(digest_bits=256, data=data)
Ejemplo n.º 42
0
# Implements a version of https://gist.github.com/alexwebr/da8dd928002a236c4709

try:
    from Crypto.Hash import keccak
    sha3 = lambda x: keccak.new(digest_bits=256, data=x).digest()
except ImportError:
    import sha3 as _sha3
    sha3 = lambda x: _sha3.sha3_256(x).digest()

NUM_SUBKEYS = 32
DEPTH = 32

def iterate_hash(msg, n):
    for i in range(n):
        msg = sha3(msg)
    return msg

class LamportSigner():
    def __init__(self, key, depth):
        self.indexcount = 2**depth
        self.priv = key
        self.keys = []
        self.pubs = []
        for i in range(self.indexcount):
            subkeys = [sha3(key + bytes([i // 256, i % 256, j])) for j in range(NUM_SUBKEYS + 1)]
            self.keys.append(subkeys)
            pubs = [iterate_hash(k, DEPTH) for k in subkeys[:-1]] + [iterate_hash(subkeys[-1], DEPTH * NUM_SUBKEYS)]
            self.pubs.append(b''.join(pubs))
            if i % 256 == 255:
                print("Finished %d out of %d privkeys" % ((i + 1), self.indexcount))
        self.merkle_nodes = [0] * self.indexcount + [sha3(x) for x in self.pubs]
Ejemplo n.º 43
0
 def test_long_512(self):
     test_vectors = load_tests("keccak", "LongMsgKAT_512.txt")
     for result, data, desc in test_vectors:
         data = tobytes(data)
         hobj = keccak.new(digest_bits=512, data=data)
         self.assertEqual(hobj.hexdigest(), result)
Ejemplo n.º 44
0
try:
    from Crypto.Hash import keccak

    sha3_256 = lambda x: keccak.new(digest_bits=256, data=x).digest()
    sha3_512 = lambda x: keccak.new(digest_bits=512, data=x)
except:
    import sha3 as _sha3

    sha3_256 = lambda x: _sha3.sha3_256(x).digest()
    sha3_512 = lambda x: _sha3.sha3_512(x).digest()
from rlp.utils import decode_hex, encode_hex
import sys

WORD_BYTES = 4  # bytes in word
DATASET_BYTES_INIT = 2 ** 30  # bytes in dataset at genesis
DATASET_BYTES_GROWTH = 2 ** 23  # growth per epoch (~7 GB per year)
CACHE_BYTES_INIT = 2 ** 24  # Size of the dataset relative to the cache
CACHE_BYTES_GROWTH = 2 ** 17  # Size of the dataset relative to the cache
EPOCH_LENGTH = 30000  # blocks per epoch
MIX_BYTES = 128  # width of mix
HASH_BYTES = 64  # hash length in bytes
DATASET_PARENTS = 256  # number of parents of each dataset element
CACHE_ROUNDS = 3  # number of rounds in cache production
ACCESSES = 64  # number of accesses in hashimoto loop


FNV_PRIME = 0x01000193


def fnv(v1, v2):
    return (v1 * FNV_PRIME ^ v2) % 2 ** 32
Ejemplo n.º 45
0
def mk_contract_address(sender, nonce):
    keccak_hash = keccak.new(digest_bits=256)
    keccak_hash.update(rlp.encode([normalize_address(sender), nonce]))
    return keccak_hash.hexdigest()[24:]
Ejemplo n.º 46
0
    def test_new_positive2(self):

        digest1 = keccak.new(data=b("\x90"), digest_bytes=64).digest()
        digest2 = keccak.new(digest_bytes=64).update(b("\x90")).digest()
        self.assertEqual(digest1, digest2)
Ejemplo n.º 47
0
 def test_short_384(self):
     test_vectors = load_tests("keccak", "ShortMsgKAT_384.txt")
     for result, data, desc in test_vectors:
         data = tobytes(data)
         hobj = keccak.new(digest_bits=384, data=data)
         self.assertEqual(hobj.hexdigest(), result)