Beispiel #1
0
  def update(self, arg):
    # Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b). arg is a normal bytestring.

    self.last_digest = None
    # Convert the data into a workable format, and add it to the buffer
    self.buffered_data += encode_hex(arg)

    # Absorb any blocks we can:
    if len(self.buffered_data) * 4 >= self.r:
      extra_bits = len(self.buffered_data) * 4 % self.r

      # An exact fit!
      if extra_bits == 0:
        P = self.buffered_data
        self.buffered_data = ""
      else:
        # Slice it up into the first r*a bits, for some constant a>=1, and the remaining total-r*a bits.
        P = self.buffered_data[:-extra_bits // 4]
        self.buffered_data = self.buffered_data[-extra_bits // 4:]

      #Absorbing phase
      for i in xrange((len(P) * 8 // 2) // self.r):
        to_convert = P[i * (2 * self.r // 8):(i + 1) * (2 * self.r // 8)] + '00' * (self.c // 8)
        P_i = _convertStrToTable(to_convert, self.w, self.b)

        # First apply the XOR to the state + block
        for y in xrange(5):
          for x in xrange(5):
            self.S[x][y] = self.S[x][y] ^ P_i[x][y]
        # Then apply the block permutation, Keccak-F
        self.S = Keccak.KeccakF(self.S, self.n_r, self.w)
Beispiel #2
0
 def big_endian_to_int(value):
     if len(value) == 1:
         return ord(value)
     elif len(value) <= 8:
         return struct.unpack('>Q', value.rjust(8, b'\x00'))[0]
     else:
         return int(encode_hex(value), 16)
Beispiel #3
0
 def to_dict(self):
     d = {}
     for name, _ in self.__class__.fields:
         d[name] = getattr(self, name)
         if name in ('to', ):
             d[name] = '0x' + encode_hex(d[name])
         elif name in ('value', ):
             if self.afi == 1:
                 ip = IPv4Address(Bytes(d[name][:4]))
                 net = IPv4Network(
                     str(ip) + '/' + str(bytes_to_int(d[name][4])))
                 d[name] = str(net)
             else:
                 ip = IPv6Address(Bytes(d[name][:16]))
                 net = IPv6Network(
                     str(ip) + '/' + str(bytes_to_int(d[name][16])))
                 d[name] = str(net)
         elif name in ('metadata', ) and self.category == 2:
             _metadata = []
             i = 0
             while i < len(d[name]):
                 _metadata.append(bytes_to_int(d[name][i]))
                 if _metadata[-1] == 1:
                     ip = IPv4Address(Bytes(d[name][i + 1]))
                 else:
                     ip = IPv6Address(Bytes(d[name][i + 1]))
                 _metadata.append(str(ip))
                 _metadata.append(encode_hex(d[name][i + 2]))
                 i += 3
             d[name] = _metadata
         elif name in ('metadata', ) and self.category == 3:
             _metadata = []
             i = 0
             while i < len(d[name]):
                 _metadata.append(bytes_to_int(d[name][i]))
                 if _metadata[-1] == 1:
                     ip = IPv4Address(Bytes(d[name][i + 1]))
                 else:
                     ip = IPv6Address(Bytes(d[name][i + 1]))
                 _metadata.append(str(ip))
                 _metadata.append(bytes_to_int(d[name][i + 2]))
                 _metadata.append(bytes_to_int(d[name][i + 3]))
                 i += 4
             d[name] = _metadata
     d['sender'] = '0x' + encode_hex(self.sender)
     d['hash'] = '0x' + encode_hex(self.hash)
     return d
Beispiel #4
0
def secure_privtopub(priv):
    if len(priv) == 64:
        return encode_hex(secure_privtopub(decode_hex(priv)))
    if openssl:
        k = openssl.CKey()
        k.generate(priv)
        return k.get_pubkey()
    else:
        return bitcoin.privtopub(priv)
Beispiel #5
0
def secure_privtopub(priv):
    if len(priv) == 64:
        return encode_hex(secure_privtopub(decode_hex(priv)))
    if openssl:
        k = openssl.CKey()
        k.generate(priv)
        return k.get_pubkey()
    else:
        return bitcoin.privtopub(priv)
Beispiel #6
0
def make_keystore_json(priv, pw, kdf="pbkdf2", cipher="aes-128-ctr"):
    # Get the hash function and default parameters
    if kdf not in kdfs:
        raise Exception("Hash algo %s not supported" % kdf)
    kdfeval = kdfs[kdf]["calc"]
    kdfparams = kdfs[kdf]["mkparams"]()
    # Compute derived key
    derivedkey = kdfeval(pw, kdfparams)
    # Get the cipher and default parameters
    if cipher not in ciphers:
        raise Exception("Encryption algo %s not supported" % cipher)
    encrypt = ciphers[cipher]["encrypt"]
    cipherparams = ciphers[cipher]["mkparams"]()
    # Produce the encryption key and encrypt
    enckey = derivedkey[:16]
    c = encrypt(priv, enckey, cipherparams)
    # Compute the MAC
    mac = sha3(derivedkey[16:32] + c)
    # Make a UUID
    u = encode_hex(os.urandom(16))
    if sys.version_info.major == 3:
        u = bytes(u, 'utf-8')
    uuid = b'-'.join((u[:8], u[8:12], u[12:16], u[16:20], u[20:]))
    # Return the keystore json
    return {
        "crypto": {
            "cipher": cipher,
            "ciphertext": encode_hex(c),
            "cipherparams": cipherparams,
            "kdf": kdf,
            "kdfparams": kdfparams,
            "mac": encode_hex(mac),
            "version": 1
        },
        "id": uuid,
        "version": 3
    }
Beispiel #7
0
def eth_privtoaddr(priv):
    pub = encode_pubkey(secure_privtopub(priv), 'bin_electrum')
    return encode_hex(sha3(pub)[12:])
Beispiel #8
0
def bin_to_nibbles(s):
    return [hti[c] for c in utils.encode_hex(s)]
Beispiel #9
0
def _build_message_pair(data):
  hex_data = encode_hex(data)
  size = len(hex_data) * 4
  return (size, hex_data)
Beispiel #10
0
  def hexdigest(self):
    """Like digest() except the digest is returned as a string of hex digits

    This may be used to exchange the value safely in email or other
    non-binary environments."""
    return encode_hex(self.digest())
Beispiel #11
0
def eth_privtoaddr(priv):
    pub = bitcoin.encode_pubkey(secure_privtopub(priv), 'bin_electrum')
    return encode_hex(sha3(pub)[12:])
Beispiel #12
0
def mk_pbkdf2_params():
    params = PBKDF2_CONSTANTS.copy()
    params['salt'] = encode_hex(os.urandom(16))
    return params
Beispiel #13
0
def mk_scrypt_params():
    params = SCRYPT_CONSTANTS.copy()
    params['salt'] = encode_hex(os.urandom(16))
    return params
Beispiel #14
0
def aes_mkparams():
    return {"iv": encode_hex(os.urandom(16))}
Beispiel #15
0
                transaction = utils.web3tx_to_ethtx(transaction)
                address = ContractAddress(address_hex, 
                                            creation_transaction=transaction)
                print("Address: contract.")
            except FileNotFoundError:
                print("Error: Local Web3 node not found. Did you forget to start it?")
                exit(2)
            except AssertionError:
                print("Error: Transaction {} is not a creation "
                      "transaction.".format(options.sent_transaction))
        else:
            print("Error: Please specify either sent trasaction (-p) or creation transaction (-c) flag.")
            exit(1)

        encrypted_message = address.encrypt(message)
        print("Encrypted message: {}".format(utils.add_0x_prefix(utils.encode_hex(encrypted_message))))
        owner = utils.decode_hex(utils.remove_0x_prefix(address.owner_address))
        assert len(owner) == 20
        message_data = owner + encrypted_message + info_bytes()
        print("Message to send: {}".format(utils.add_0x_prefix(utils.encode_hex(message_data))))
        
        if options.send:
            print("Sending transaction to: {}".format(address_hex))
            sender_account = options.send_from
            if not utils.is_hex_address(sender_account):
                try:
                    sender_account = web3.personal.listAccounts[int(sender_account)]
                except ValueError:
                    print("Error: Invalid sender account. Should be your local Ethereum account "
                          "or its index number. See --list flag.")
                    exit(1)
Beispiel #16
0
def eth_privtoaddr(priv):
    pub = encode_pubkey(secure_privtopub(priv), "bin_electrum")
    return encode_hex(sha3(pub)[12:])