예제 #1
0
 def web3_sha3(self, value, encoding='hex'):
     logger.info('web3_sha3')
     if encoding == 'hex':
         value = decode_hex(value)
     else:
         value = force_bytes(value)
     return encode_32bytes(keccak_256(value).digest())
예제 #2
0
    def __init__(self):
        import sha3
        self.PrivateKey = getRandom(512)
        self.PublicKey = [0]*512

        for i in range(0, 512):
            self.PublicKey[i] = bytes_to_int(sha3.keccak_256(int_to_bytes32(self.PrivateKey[i])).digest())
예제 #3
0
파일: addr.py 프로젝트: onedot618/mmgen
	def to_addr(self,sk_hex): # sk_hex instead of pubhex

		# ed25519ll, a low-level ctypes wrapper for Ed25519 digital signatures by
		# Daniel Holth <*****@*****.**> - http://bitbucket.org/dholth/ed25519ll/
		try:
			from ed25519ll.djbec import scalarmult,edwards,encodepoint,B
		except:
			from mmgen.ed25519 import scalarmult,edwards,encodepoint,B

		# Source and license for scalarmultbase function:
		#   https://github.com/bigreddmachine/MoneroPy/blob/master/moneropy/crypto/ed25519.py
		# Copyright (c) 2014-2016, The Monero Project
		# All rights reserved.
		def scalarmultbase(e):
			if e == 0: return [0, 1]
			Q = scalarmult(B, e//2)
			Q = edwards(Q, Q)
			if e & 1: Q = edwards(Q, B)
			return Q

		def hex2int_le(hexstr):
			return int(hexstr.decode('hex')[::-1].encode('hex'),16)

		vk_hex = self.to_viewkey(sk_hex)
		pk_str  = encodepoint(scalarmultbase(hex2int_le(sk_hex)))
		pvk_str = encodepoint(scalarmultbase(hex2int_le(vk_hex)))
		addr_p1 = g.proto.addr_ver_num['monero'][0].decode('hex') + pk_str + pvk_str

		import sha3
		return CoinAddr(self.b58enc(addr_p1 + sha3.keccak_256(addr_p1).digest()[:4]))
예제 #4
0
def MLSAG_Test(m=4, n=3):
    import random
    xk = []
    indices = []
    pub_keys = []

    #Generate Private Keys
    for i in range(0, m):
        xk = xk + [getRandom()]
        indices = indices + [random.randrange(0, n)]

    #Generate Mix-in Public Keys
    for i in range(0, m*(n-1)):
        P = multiply(G1, getRandom())
        pub_keys = pub_keys + [P]

    msg = b"MLSAGTest"
    hasher = sha3.keccak_256()
    hasher.update(msg)
    msgHash = int_to_bytes32(bytes_to_int(hasher.digest()))
    
    mlsag_signature = MLSAG.Sign_GenRandom(m, msgHash, xk, indices, pub_keys)
    mlsag_signature.Print()

    if (mlsag_signature.Verify()):
        print("MLSAG Verification Success!")
    else:
        print("MLSAG Verification Failure!")
예제 #5
0
    def Verify(self):
        #Check input parameter lengths
        m = self.m
        if (m == 0): return False
        if (len(self.pub_keys) % m != 0): return False
        n = len(self.pub_keys) // m
        if (n == 0): return False
        if (len(self.signature) != (m*n+1)): return False

        #Initialize c1 hasher (total length of array + message hash)
        hasher = sha3.keccak_256()
        hasher.update(int_to_bytes32(2*m+1))
        hasher.update(self.msgHash)

        #Calculate Rings
        for i in range(0, m):
            #Get c1
            ck = self.signature[0]

            #Calculate (n-1) ring segments
            for j in range(0, n-1):
                index = m*j+i
                ck = MSAG.CalculateRingSegment(self.msgHash, ck, self.signature[index+1], self.pub_keys[index])

            #Calculate last ring segment
            index = m*(n-1)+i
            point = MSAG.CalculateRingSegment_NoHash(ck, self.signature[index+1], self.pub_keys[index])

            #Update c1 hash
            hasher.update(int_to_bytes32(point[0].n))
            hasher.update(int_to_bytes32(point[1].n))
                
        #Check if ring is closed
        ck = bytes_to_int(hasher.digest())
        return (self.signature[0] == ck)
예제 #6
0
파일: protocol.py 프로젝트: mmgen/mmgen
	def verify_addr(cls,addr,hex_width,return_dict=False):

		def b58dec(addr_str):
			from mmgen.util import baseconv
			l = len(addr_str)
			a = ''.join([baseconv.tohex(addr_str[i*11:i*11+11],'b58',pad=16) for i in range(l//11)])
			b = baseconv.tohex(addr_str[-(l%11):],'b58',pad=10)
			return a + b

		from mmgen.util import is_b58_str
		assert is_b58_str(addr),'Not valid base-58 string'
		assert len(addr) == cls.addr_width,'Incorrect width'

		ret = b58dec(addr)

		try:
			assert not g.use_internal_keccak_module
			from sha3 import keccak_256
		except:
			from mmgen.keccak import keccak_256

		chk = keccak_256(bytes.fromhex(ret)[:-4]).hexdigest()[:8]
		assert chk == ret[-8:],'{}: incorrect checksum.  Correct value: {}'.format(ret[-8:],chk)

		return { 'hex': ret, 'format': 'monero' } if return_dict else True
예제 #7
0
 def LinkableRingHashFunction(msgHash, left, right):
     hasher = sha3.keccak_256()
     hasher.update(msgHash)
     hasher.update(int_to_bytes32(left[0].n))
     hasher.update(int_to_bytes32(left[1].n))
     hasher.update(int_to_bytes32(right[0].n))
     hasher.update(int_to_bytes32(right[1].n))
     return bytes_to_int(hasher.digest())
예제 #8
0
def sha3(data: bytes) -> bytes:
    """
    Raises:
        RuntimeError: If Keccak lib initialization failed, or if the function
        failed to compute the hash.

        TypeError: This function does not accept unicode objects, they must be
        encoded prior to usage.
    """
    return keccak_256(data).digest()
예제 #9
0
def hash_to_point(p):
    hasher = sha3.keccak_256()
    hasher.update(int_to_bytes32(p[0].n))
    hasher.update(int_to_bytes32(p[1].n))
    x = bytes_to_int(hasher.digest()) % Pcurve

    onCurve = False
    while(not onCurve):
        y_squared = (pow(x, 3, Pcurve) + 3) % Pcurve
        y = pow(y_squared, (Pcurve+1)//4, Pcurve)

        onCurve = (pow(y,2,Pcurve) == y_squared)

        if(not(onCurve)):
            x = x + 1

    return (FQ(x), FQ(y))
예제 #10
0
def brute_prototype(function, dict_file, max_args=3, exhaustive=False):
    logging.info('Now processing function %s' % function.encode('hex'))
    argtypes = ['bool', 'address', 'bytes', 'string']
    if exhaustive:
        argtypes += ['int%s' % x for x in xrange(8, 257, 8)]
        argtypes += ['uint%s' % x for x in xrange(8, 257, 8)]
        argtypes += ['bytes%s' % x for x in xrange(1, 33)]
    else:
        argtypes += ['bytes8', 'bytes16', 'bytes32', 'uint256', 'int256']
    with open(dict_file, 'r') as names:
        counter = 0
        for name in names:
            if counter % 1000 == 0:
                logging.debug('Processed %s names' % counter)
            for argnum in xrange(max_args + 1):
                for signature in itertools.product(argtypes, repeat=argnum):
                    prototype = '%s(%s)' % (name.strip(), ','.join(signature))
                    if sha3.keccak_256(prototype).digest()[:4] == function:
                        logging.warning('FOUND function %s prototype: %s' %
                                        (function.encode('hex'), prototype))
                        return prototype
            counter += 1
예제 #11
0
def newid_encode_by_public_key(public_key, chain_id):
    """ generate newid by public key

    :param str public_key: The public key of newid
    :param int chain_id: The blockchain ID
    :rtype: str
    :return: The encoded newid
    """
    if public_key.startswith('0x'):
        public_key = public_key[2:]
    if len(public_key) < 64:
        public_key = '0' * (64 - len(public_key)) + public_key
    k = keccak_256()
    k.update(bytearray.fromhex(public_key))
    data = k.hexdigest()
    hex_chainID = hex(chain_id)[2:][-8:]
    if (len(hex_chainID) % 2) == 1:
        hex_chainID = '0' + hex_chainID
    num_sum = hex_chainID + data
    data = base58.b58encode_check(b'\0' + binascii.a2b_hex(num_sum))
    newid = PREFIX + 'ID' + data.decode()
    return newid
def insert(node, db, is_leaf):
    if len(node) == 17:
        for hash in node[:16]:
            if not hash:
                continue
            exist = db.get(hash)
            assert exist, "Child hash is not inserted"

    node = copy.copy(node)
    if len(node) == 2:
        node[0] = nibbles_to_bytes(node[0], is_leaf)
    node_rlp = rlp.encode(node)
    k = sha3.keccak_256()
    k.update(node_rlp)
    node_hash = k.digest()
    assert len(
        k.hexdigest()) == 64, "Invalid hash length for %s" % node_hash.hexdigest()
    exist = db.get(node_hash)
    assert not exist or exist == node_rlp, "Conflict insertion on %s(%s-%s)" %\
        (node_hash.hex(), exist.hex(), node_rlp.hex())
    db.put(node_hash, node_rlp)
    return node_hash
예제 #13
0
		def parse_addr(self,addr):

			from .baseconv import baseconv,is_b58_str

			def b58dec(addr_str):
				l = len(addr_str)
				a = b''.join([baseconv.tobytes(addr_str[i*11:i*11+11],'b58',pad=8) for i in range(l//11)])
				b = baseconv.tobytes(addr_str[-(l%11):],'b58',pad=5)
				return a + b

			ret = b58dec(addr)

			try:
				assert not g.use_internal_keccak_module
				from sha3 import keccak_256
			except:
				from .keccak import keccak_256

			chk = keccak_256(ret[:-4]).digest()[:4]
			assert ret[-4:] == chk, f'{ret[-4:].hex()}: incorrect checksum.  Correct value: {chk.hex()}'

			return self.parse_addr_bytes(ret)
예제 #14
0
def validateFeedback(
    address,
    id,
    date,
    created_at,
    comment,
    feedback_address,
    latitude,
    longitude,
    current_latitude,
    current_longitude,
    source,
    feedback_image,
):
    fields = [
        id,
        date,
        created_at,
        bytes.fromhex(keccak_256(comment.encode("utf-8")).hexdigest()),
        bytes.fromhex(
            keccak_256(feedback_address.encode("utf-8")).hexdigest()),
        bytes.fromhex(keccak_256(latitude.encode("utf-8")).hexdigest()),
        bytes.fromhex(keccak_256(longitude.encode("utf-8")).hexdigest()),
        bytes.fromhex(
            keccak_256(current_latitude.encode("utf-8")).hexdigest()),
        bytes.fromhex(
            keccak_256(current_longitude.encode("utf-8")).hexdigest()),
        bytes.fromhex(keccak_256(source.encode("utf-8")).hexdigest()),
        bytes.fromhex(keccak_256(feedback_image.encode("utf-8")).hexdigest()),
    ]

    feedback = getFeedback(address, id)
    for i in range(len(fields)):
        if feedback[i] != fields[i]:
            return False
    return True
예제 #15
0
def sign(private_key: str,
         message: Optional[str] = None,
         message_hash: Optional[str] = None) -> str:
    """
    Sign XinFin message data by private key.

    :param private_key: XinFin private key.
    :type private_key: str.
    :param message: Message data, default to ``None``.
    :type message: str.
    :param message_hash: Message data hash, default to ``None``.
    :type message_hash: str.

    :return: str -- XinFin signed message or signature.

    >>> from pyxdc.signature import sign
    >>> sign(private_key="4235d9ffc246d488d527177b654e7dd5c02f5c5abc2e2054038d6825224a24de", message="meherett")
    "74ad07a84b87fa3efa2f0e825506fb8bbee41021ca77a30e8ffa2bd66d47d99917d4a0587185e78a051a9cb80ebf65c7d62dbeedb7f9a029f961d70b52a10dc001"
    >>> sign(private_key="4235d9ffc246d488d527177b654e7dd5c02f5c5abc2e2054038d6825224a24de", message_hash="4bbbfd0c33fea618f4a9aa75c02fe76e50fa59798af021bc34f7856f3259c685")
    "74ad07a84b87fa3efa2f0e825506fb8bbee41021ca77a30e8ffa2bd66d47d99917d4a0587185e78a051a9cb80ebf65c7d62dbeedb7f9a029f961d70b52a10dc001"
    """

    if message:
        message_bytes = curried.to_bytes(primitive=None,
                                         hexstr=None,
                                         text=message)
        msg_length = str(len(message_bytes)).encode('utf-8')
        joined = b'\x19' + b'E' + b'thereum Signed Message:\n' + msg_length + message_bytes
        keccak_256_message = keccak_256()
        keccak_256_message.update(joined)
        message_hash = keccak_256_message.digest()
    elif message_hash:
        message_hash = unhexlify(message_hash)
    else:
        raise ValueError("Message data or hash is required to sign.")

    return ecdsa_raw_sign(msg_hash=message_hash,
                          private_key_bytes=unhexlify(private_key)).hex()
예제 #16
0
    def submit_data_to_logger(self, data):

        try:
            # calculate hash locally
            hashes = []
            padded_data = list(data)
            for x in range(
                    int(self.__page_size / self.__bytes_of_word) - len(data)):
                # padding zero to page size
                padded_data.append(bytes(self.__bytes_of_word))
            for x in range(int(self.__page_size / self.__bytes_of_word)):
                k = sha3.keccak_256()
                # padding zero to word size
                padded_data[x] += b'0' * (self.__bytes_of_word -
                                          len(padded_data[x]))
                k.update(padded_data[x])
                hashes.append(bytes.fromhex(k.hexdigest()))

            root = self.__calculate_root_from_hashes(hashes)

            (exists,
             index) = self.__get_index_from_root(root, self.__page_log_2_size)
            if exists:
                return (index, root)

            # submit data if is the first time
            nonce = self.__w3.eth.getTransactionCount(self.__user, "pending")
            txn = self.__logger.functions.calculateMerkleRootFromData(
                self.__page_log_2_size, data).buildTransaction({
                    "nonce":
                    nonce,
                    "from":
                    self.__user
                })
            return self.__send_txn_to_logger(txn, True)

        except ValueError as e:
            print("calculateMerkleRoot REVERT transaction: " + str(e))
예제 #17
0
def check_point_update(checkpoint_path, checkpoints, path, ts, current_pos, checkpoint_timediff):
    with checkpoint_lock:
        if path not in checkpoints:
            checkpoints[path] = {
                'last_ts': ts,
                'last_pos': current_pos,
                'history': []
            }

        # Time to make a checkpoint.
        print(ts - checkpoints[path]['last_ts'])
        if ts - checkpoints[path]['last_ts'] > checkpoint_timediff:
            print('making checkpoint')
            last_pos = checkpoints[path]['last_pos']

            with open(path, 'rb') as logfile:
                logfile.seek(last_pos)
                total = current_pos - last_pos

                _hash = sha3.keccak_256()
                while total > 0:
                    bufsize = 1024 if math.floor(total / 1024) else total
                    _hash.update(logfile.read(bufsize))
                    total -= bufsize

                checkpoints[path]['history'].append({
                    'hash': _hash.hexdigest(),
                    'from_date': checkpoints[path]['last_ts'].isoformat(),
                    'to_date': ts.isoformat(),
                    'from_pos': last_pos,
                    'to_pos': current_pos,
                    'root_hash': None
                })

                checkpoints[path]['last_pos'] = current_pos
                checkpoints[path]['last_ts'] = ts

            save_checkpoints(checkpoint_path, checkpoints)
예제 #18
0
def ed25519_generate_key_pair_from_secret(secret):
    """
    Generate a new key pair.
    Args:
        secret (:class:`string`): A secret that serves as a seed
    Returns:
        A tuple of (private_key, public_key) encoded in base58.
    """

    # if you want to do this correctly, use a key derivation function!
    if not isinstance(secret, bytes):
        secret = secret.encode()

    hash_bytes = sha3.keccak_256(secret).digest()
    sk = Ed25519SigningKeyFromHash.generate(hash_bytes=hash_bytes)
    # Private key
    private_value_base58 = sk.encode(encoding='base58')

    # Public key
    public_value_compressed_base58 = sk.get_verifying_key().encode(
        encoding='base58')

    return private_value_base58, public_value_compressed_base58
예제 #19
0
파일: utils.py 프로젝트: codyli2002hk/pmes
def abi_to_func_hashes(abi):
    func_hashes = {}
    abi = json.loads(abi)

    for fn in abi:
        if 'name' not in fn:
            continue
        if fn['type'] != 'function':
            continue
        fn_sig = fn['name']
        fn_sig += '('
        for in_param in fn['inputs']:
            fn_sig += in_param['type']
            fn_sig += ','
        if fn_sig[-1] == ',':
            fn_sig = fn_sig[:-1] + ')'
        else:
            fn_sig = fn_sig + ')'
        k = sha3.keccak_256()
        k.update(fn_sig.encode())
        hash = k.hexdigest()[:8]
        func_hashes[fn['name']] = hash
    return func_hashes
예제 #20
0
    def _parse_abi(abi: str, func_name2quota: Dict[str,
                                                   int]) -> Dict[str, ABI]:
        """解析ABI到函数签名."""
        result: Dict[str, ABI] = {}
        for func_def in json.loads(abi):
            if func_def['type'] not in ('function', 'constructor'):  # 比如 event
                continue
            func_name = func_def.get('name', '')
            return_types = ','.join(i['type']
                                    for i in func_def.get('outputs', []))
            mutable = func_def['stateMutability'] not in ('view', 'pure',
                                                          'constant')
            param_types = ','.join(i['type'] for i in func_def['inputs'])
            sig = f'{func_name}({param_types})'
            func_addr = '0x' + sha3.keccak_256(sig.encode()).hexdigest()[:8]
            t = ABI(func_name, func_addr, param_types, return_types, mutable,
                    func_name2quota.get(func_name, DEFAULT_QUOTA))

            # 重载函数只支持第一个名字的自动映射, 其他都要使用方法地址.
            if func_name not in result:
                result[func_name] = t
            if func_name != '':  # 跳过构造函数
                result[func_addr] = t
        return result
예제 #21
0
 def ecrecover(self, block_identifier):
     block = self.getBlock(block_identifier)
     extra = block.proofOfAuthorityData[0:32]
     sign = block.proofOfAuthorityData[32:]
     raw_data = [
         bytes.fromhex(remove_0x_prefix(block.parentHash.hex())),
         bytes.fromhex(remove_0x_prefix(block.miner)),
         bytes.fromhex(remove_0x_prefix(block.stateRoot.hex())),
         bytes.fromhex(remove_0x_prefix(block.transactionsRoot.hex())),
         bytes.fromhex(remove_0x_prefix(block.receiptsRoot.hex())),
         bytes.fromhex(remove_0x_prefix(block.logsBloom.hex())),
         block.number, block.gasLimit, block.gasUsed, block.timestamp,
         extra,
         bytes.fromhex(remove_0x_prefix(block.nonce))
     ]
     message_hash = sha3.keccak_256(rlp.encode(raw_data)).digest()
     hash_bytes = HexBytes(message_hash)
     signature_bytes = HexBytes(sign)
     signature_bytes_standard = to_standard_signature_bytes(signature_bytes)
     signature_obj = self.account._keys.Signature(
         signature_bytes=signature_bytes_standard)
     return remove_0x_prefix(
         signature_obj.recover_public_key_from_msg_hash(
             hash_bytes).to_hex())
예제 #22
0
    def signMessage(msg: Union[str, Dict], key=None):
        """Sign the message using an Ethereum private key.

        This method signs the message for the user authentication mechanism
        Args:
        msg: message to be signed
        private_key: the key can be an app key or a user key used to sign the message
        Returns:
        string: a signed message
        """
        k = sha3.keccak_256()
        if isinstance(msg, str):
            encoded_message = msg.encode('utf-8')
        else:
            encoded_message = (json.dumps(msg)).encode("utf-8")
        k.update(encoded_message)
        message_hash = k.hexdigest()
        if key is not None:
            signed_message = Account.signHash(message_hash, key)
            sig_hx = signed_message.signature.hex()
            return str(sig_hx.replace("0x", ""))

        else:
            return " "
예제 #23
0
def hash_header(header, height):
    if header is None:
        return '0' * 64
    if header.get('prev_block_hash') is None:
        header['prev_block_hash'] = '00' * 32

    header2 = bfh(serialize_header(header, (not is_postfork(height))))
    s = sha3.keccak_256()

    nonce = int(hash_encode(header2[132:140]), 16)
    mixhash = hash_encode(header2[141:173])
    header_hash_hex = header2[:108] + bytes(32)
    s.update(header_hash_hex)
    header_hash = swap(s.hexdigest())

    go_wrapper_url = "https://progpow.bitcoininterest.io/" \
                     "?header_hash={0}" \
                     "&nonce={1}" \
                     "&mix_hash={2}".format(header_hash, nonce, mixhash)
    r = r_ses.get(go_wrapper_url)

    block_hash = r.json().get('digest')

    return block_hash
예제 #24
0
    def Sign_CompactPin(m, msgHash, xk, indices, Pin, random):
        assert(len(xk) == m)
        assert(len(indices) == m)
        assert( (len(Pin) % m ) == 0)
        n = (len(Pin) // m) + 1
        assert( len(random) == m*n )

        #Initialize Output Arrays
        Pout = [0]*(m*n)
        signature = [0]*(m*n+1)

        #Initialize c1 hasher (total length of array + message hash)
        hasher = sha3.keccak_256()
        hasher.update(int_to_bytes32(2*m+1))
        hasher.update(msgHash)

        #Calulate 1st half of all rings (for c1 calculation)
        for i in range(0, m):
            #Make sure index is mod n
            indices[i] = indices[i] % n

            #Store public key for known private key
            Pout[m*indices[i]+i] = multiply(G1, xk[i])
            
            if (indices[i] == (n-1)):
                point = MSAG.StartRing_NoHash(random[m*indices[i]+i])
            else:
                ck = MSAG.StartRing(msgHash, random[m*indices[i]+i])

                for j in range((indices[i]+1)%n,(n-1)):
                    #Calculate array index for easy reference
                    index = m*j+i
                    
                    #Extract input public key
                    if (j > indices[i]):
                        point = Pin[index - m]
                    else:
                        point = Pin[index]

                    #Store public key in output
                    Pout[index] = point

                    #Calculate ring segment
                    ck = MSAG.CalculateRingSegment(msgHash, ck, random[index], point)

                    #Store s value
                    signature[index+1] = random[index]

                #Calculate last ring segment before c1
                index = m*(n-1) + i

                #Extract Public Key
                point = Pin[index-m]
                Pout[index] = point

                point = MSAG.CalculateRingSegment_NoHash(ck, random[index], point)

                #Store s value
                signature[index+1] = random[index]
                
            #Store update c1 hash
            hasher.update(int_to_bytes32(point[0].n))
            hasher.update(int_to_bytes32(point[1].n))

        #Store c1
        signature[0] = bytes_to_int(hasher.digest())

        #Calculate 2nd half of each ring
        for i in range(0, m):
            #Fetch c1
            ck = signature[0]

            #Calculate remaining ring segments
            for j in range(0, indices[i]):
                index = m*j+i

                #Extract public key
                point = Pin[index]
                Pout[index] = point

                #Calculate Ring Segment
                ck = MSAG.CalculateRingSegment(msgHash, ck, random[index], point)

                #Store s value
                signature[index+1] = random[index]

            #Close Ring
            index = m*indices[i] + i
            signature[index+1] = MSAG.CompleteRing(random[index], ck, xk[i])

        return MSAG(msgHash, m, Pout, signature)
예제 #25
0
#!/usr/bin/python3

from secrets import token_bytes
from coincurve import PublicKey
from sha3 import keccak_256

with open('keys.txt') as fp:
    key = fp.readline()

    # Debug
    print("readed key: ", key)

    encoded_key = key.encode()
    print("encoded_key: ", encoded_key.decode())

    striped_key = encoded_key.strip()
    print("striped_key: ", striped_key.strip())

    cnt = 1
    while key:
        # private_key = keccak_256(token_bytes(32)).digest()
        public_key = PublicKey.from_valid_secret(striped_key).format(
            compressed=False)[1:]
        addr = keccak_256(public_key).digest()[-20:]

        print('private_key:', striped_key.hex())
        print('eth addr: 0x' + addr.hex())
        key = fp.readline()
        cnt += 1
예제 #26
0
파일: utils.py 프로젝트: totaltrader/mmgen
	def sha3_256(x): return _sha3.keccak_256(x).digest()
except:
예제 #27
0
def save_to_mew(priv_keys, n=1 << 18, p=1, r=8, dklen=32):
    try:
        passwd = getpass('Enter the password for saving (utf-8): ').encode(
            'utf-8')
        passwd2 = getpass('Enter the password again (utf-8): ').encode('utf-8')
        if passwd != passwd2:
            raise KeytreeError("mismatching passwords")

        for priv_key in priv_keys:
            addr = get_eth_addr(priv_key.get_verifying_key())
            priv_key = priv_key.to_string()
            with open("mew-{}.json".format(addr), "w") as f:
                iv = os.urandom(16)
                salt = os.urandom(16)

                m = 128 * r * (n + p + 2)
                dk = hashlib.scrypt(passwd,
                                    salt=salt,
                                    n=n,
                                    r=r,
                                    p=p,
                                    dklen=dklen,
                                    maxmem=m)
                obj = AES.new(dk[:dklen >> 1],
                              mode=AES.MODE_CTR,
                              counter=Counter.new(128,
                                                  initial_value=int.from_bytes(
                                                      iv, 'big')))
                enc_pk = obj.encrypt(priv_key)

                # generate MAC
                h = keccak_256()
                h.update(dk[len(dk) >> 1:])
                h.update(enc_pk)
                mac = h.digest()

                crypto = {
                    'ciphertext': enc_pk.hex(),
                    'cipherparams': {
                        'iv': iv.hex()
                    },
                    'cipher': 'aes-128-ctr',
                    'kdf': 'scrypt',
                    'kdfparams': {
                        'dklen': dklen,
                        'salt': salt.hex(),
                        'n': n,
                        'r': r,
                        'p': p
                    },
                    'mac': mac.hex()
                }
                json.dump(
                    {
                        'version': 3,
                        'id': str(uuid4()),
                        'address': addr,
                        'Crypto': crypto
                    }, f)
    except FileNotFoundError:
        raise KeytreeError("failed while saving")
예제 #28
0
 def address(self):
     keccak_256 = sha3.keccak_256()
     keccak_256.update(self.verified_key.to_string())
     address = keccak_256.hexdigest()[24:]
     return checksum_encode(address)
def make_4byte_signature(text_signature):
    from .encoding import force_bytes
    return keccak_256(force_bytes(text_signature)).digest()[:4]
예제 #30
0
 def hash(self, message: bytes):
     keccak = sha3.keccak_256()
     keccak.update(message)
     return keccak.hexdigest()
예제 #31
0
def keccak256(data):
    hasher = sha3.keccak_256()
    hasher.update(data)
    return hasher.digest()
예제 #32
0
파일: addr.py 프로젝트: onedot618/mmgen
	def to_addr(self,pubhex):
		assert type(pubhex) == PubKey
		import sha3
		return CoinAddr(sha3.keccak_256(pubhex[2:].decode('hex')).digest()[12:].encode('hex'))
예제 #33
0
파일: addr.py 프로젝트: onedot618/mmgen
	def to_viewkey(self,sk_hex):
		assert len(sk_hex) == 64,'{}: incorrect privkey length'.format(len(sk_hex))
		import sha3
		return MoneroViewKey(g.proto.preprocess_key(sha3.keccak_256(sk_hex.decode('hex')).hexdigest(),None))
from sha3 import keccak_256

from jsonschema import (
    validate,
    ValidationError,
)


# sanity check we are using the right sha3 function
assert keccak_256(b'').hexdigest() == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', keccak_256(b'').hexdigest()  # NOQA


def make_4byte_signature(text_signature):
    from .encoding import force_bytes
    return keccak_256(force_bytes(text_signature)).digest()[:4]


ARGUMENT_SCHEMA = {
    'type': 'object',
    'properties': {
        'name': {
            'type': 'string',
        },
        'type': {
            'type': 'string',
        },
    },
    'required': ['name', 'type'],
}

예제 #35
0
    def test_201503110346PYTHON_PUSH24(self):
        """
        Testcase taken from https://github.com/ethereum/tests
        File: 201503110346PYTHON_PUSH24.json
        sha256sum: 0f512fa3c9cf0e24e246ca46e8e072745df14f1cdfc8fcf6d201aba5e55f7932
        Code:     
        """    
    
        def solve(val):
            return self._solve(constraints, val)

        constraints = ConstraintSet()

        blocknumber = constraints.new_bitvec(256, name='blocknumber')
        constraints.add(blocknumber == 300)

        timestamp = constraints.new_bitvec(256, name='timestamp')
        constraints.add(timestamp == 2)

        difficulty = constraints.new_bitvec(256, name='difficulty')
        constraints.add(difficulty == 115792089237316195423570985008687907853269984665640564039457584007913129639935)

        coinbase = constraints.new_bitvec(256, name='coinbase')
        constraints.add(coinbase == 244687034288125203496486448490407391986876152250)

        gaslimit = constraints.new_bitvec(256, name='gaslimit')
        constraints.add(gaslimit == 1000000)

        world = evm.EVMWorld(constraints, blocknumber=blocknumber, timestamp=timestamp, difficulty=difficulty,
                             coinbase=coinbase, gaslimit=gaslimit)
    
        acc_addr = 0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6
        acc_code = unhexlify('7745414245403745f31387900a8d55')
            
        acc_balance = constraints.new_bitvec(256, name='balance_0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6')
        constraints.add(acc_balance == 1000000000000000000)

        acc_nonce = constraints.new_bitvec(256, name='nonce_0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6')
        constraints.add(acc_nonce == 0)

        world.create_account(address=acc_addr, balance=acc_balance, code=acc_code, nonce=acc_nonce)

        address = 0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6
        caller = 0xcd1722f3947def4cf144679da39c4c32bdc35681
        price = constraints.new_bitvec(256, name='price')
        constraints.add(price == 100000000000000)

        value = constraints.new_bitvec(256, name='value')
        constraints.add(value == 1000000000000000000)

        gas = constraints.new_bitvec(256, name='gas')
        constraints.add(gas == 10000)

        data = ''
        # open a fake tx, no funds send
        world._open_transaction('CALL', address, price, data, caller, value, gas=gas)

        # This variable might seem redundant in some tests - don't forget it is auto generated
        # and there are cases in which we need it ;)
        result, returndata = self._test_run(world)

        # World sanity checks - those should not change, right?
        self.assertEqual(solve(world.block_number()), 300)
        self.assertEqual(solve(world.block_gaslimit()), 1000000)
        self.assertEqual(solve(world.block_timestamp()), 2)
        self.assertEqual(solve(world.block_difficulty()), 115792089237316195423570985008687907853269984665640564039457584007913129639935)
        self.assertEqual(solve(world.block_coinbase()), 0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba)

        # Add post checks for account 0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6
        # check nonce, balance, code
        self.assertEqual(solve(world.get_nonce(0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6)), 0)
        self.assertEqual(solve(world.get_balance(0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6)), 1000000000000000000)
        self.assertEqual(world.get_code(0xf572e5295c57f15886f9b263e2f6d2d6c7b5ec6), unhexlify('7745414245403745f31387900a8d55'))
        # check outs
        self.assertEqual(returndata, unhexlify(''))
        # check logs
        logs = [Log(unhexlify('{:040x}'.format(l.address)), l.topics, solve(l.memlog)) for l in world.logs]
        data = rlp.encode(logs)
        self.assertEqual(sha3.keccak_256(data).hexdigest(), '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347')

        # test used gas
        self.assertEqual(solve(world.current_vm.gas), 9997)
예제 #36
0
def sha3(seed):
    return keccak_256(seed).digest()
예제 #37
0
    hasher = hashlib.new('ripemd160')
    hasher.update(r)
    r = hasher.digest()

    return '1' + encode58_check(r, version=0)

priv = SigningKey.generate(curve=SECP256k1)
pub = b'\x04' + priv.get_verifying_key().to_string()

print('Private:', priv.to_string().hex())
print('Private58:', encode58_check(priv.to_string(), 128))
print('Public:', pub.hex())
print('Address:', getAddress(pub))

print('----------------------------------------------')
keccak = sha3.keccak_256()

priv = SigningKey.generate(curve=SECP256k1)
pub = priv.get_verifying_key().to_string()

keccak.update(pub)
address = keccak.hexdigest()[24:]

print("Private key:", priv.to_string().hex())
print("Public key: ", pub.hex())
print("Address:     0x" + address)

#priv = SigningKey.generate(curve=SECP256k1)
#pub = priv.get_verifying_key()
#print(priv.to_string())
#print(pub.to_string())
예제 #38
0
 def sign_message(self, message):
     msg = '0x' + keccak_256(message.encode('utf-8')).hexdigest()
     msg = '\x19Ethereum Signed Message:\n%d%s' % (len(msg), msg)
     msg = bytearray(msg.encode('utf-8'))
     return self.sign_digest(bytearray(
         keccak_256(msg).digest())).eth_signature_format()
예제 #39
0
datasetLocationEnvvar = 'IEXEC_INPUT_FILES_FOLDER'
datasetFilenameEnvvar = 'IEXEC_DATASET_FILENAME'

if __name__ == '__main__':

	# Seed using the arguments → still not deterministic event with arguments
	random.seed(" ".join(sys.argv), random.random())

	# OPTIONAL: reseed using dataset to reseed the random → still not deterministic even with a dataset
	try:
		root = os.environ.get(datasetLocationEnvvar, inFolder),
		file = os.environ.get(datasetFilenameEnvvar),
		if file:
			with open('{root}{file}'.format(root=root, file=file), 'r') as file:
				random.seed(file.read(), random.random())
	except FileNotFoundError:
		pass

	# Generate random value and write it to the callback file
	callback = '{:064x}'.format(random.getrandbits(256))
	with open(callbackFilePath, 'w') as callbackFile:
		callbackFile.write('0x{}'.format(callback))

	# Generate the determinism file for verification and write it to the determinism file
	determinism = sha3.keccak_256()
	determinism.update(bytes.fromhex(callback))

	with open(determinismFilePath, 'w') as determinismFile:
		determinismFile.write('0x{}'.format(determinism.hexdigest()))
예제 #40
0
파일: contract.py 프로젝트: mmgen/mmgen
def create_method_id(sig): return keccak_256(sig.encode()).hexdigest()[:8]

class Token(MMGenObject): # ERC20
예제 #41
0
import binascii
import ecdsa
import sha3
from Crypto.Cipher import AES
from getTrueRandom import generateTrueRandom

privateKey = generateTrueRandom(32)
print "Private key is:" + binascii.hexlify(privateKey)

signingObj = ecdsa.SigningKey.from_string(privateKey, curve=ecdsa.SECP256k1)
publicKeyObj = signingObj.verifying_key
publicKeyString = binascii.hexlify(publicKeyObj.to_string())

print "Public key is:" + publicKeyString

keccakObj = sha3.keccak_256()
keccakObj.update(publicKeyObj.to_string())
publicAdress64 = keccakObj.hexdigest()
publicAdressFinal = "0x" + publicAdress64[-40:]

print "Public ETH adress is: " + publicAdressFinal
예제 #42
0
 def _do_op_call(self, msg):
     r = sha3.keccak_256(bytes(msg)).digest()
     assert len(r) == self.DIGEST_LENGTH
     return r
예제 #43
0
def eth_to_address(prefix, subkey):
    hasher = sha3.keccak_256()
    hasher.update(subkey.sec(True)[1:])
    return hexlify(hasher.digest()[-20:]).decode()
예제 #44
0
def identityCreation():
    print art
    print "\nIdentity Creation Script - Block SSL\n"
    keybaseCheck()
    ans1 = raw_input("Do you own a Keybase.io account? [Y]es [N]o, default: [Y]\n")
    if ans1 == "Y" or ans1 == "y" or ans1 == "" or ans1 == " ":
        os.system("keybase version") #check for keybase version
        print "Checking for Updates...\n"
        os.system("echo 3 | keybase update check >/dev/null 2>&1") #check for keybase updates without terminal output
        os.system("keybase login") #login to keybase through terminal
    else:
        os.system("keybase version")
        print "Checking for Updates...\n"
        os.system('echo 3 | keybase update check >/dev/null 2>&1')
        os.system("keybase signup") #signup to keybase through terminal
    keccak = sha3.keccak_256()
    ex = raw_input("Do you already own an Ethereum address that you want to use? [Y]es [N]o, default: [Y]")
    if ex == "Y" or ex == "y" or ex == "" or ex == " ":
        gen_priv = raw_input("Which is your private key? (in hexadecimal format)\n")  #Private Key of the owner
        gen_priv = BitcoinPrivateKey(gen_priv)
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation."
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    else:
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation.\n"

        print "Generating \"Generation\" Private Key..."
        gen_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Generation" private key
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    print "Generating \"Certificate\" Private Key..."
    cert_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Certificate" private key
    print "Saving to Certificate_Private.pem file..."
    open("Certificate_Private.pem", "w").write(cert_priv.to_pem())  #Saving to file
    print "Generating \"Certificate\" Public Key..."
    cert_pub = cert_priv.get_verifying_key()  #Generate the "Certificate" public key from cert_priv
    print "Saving to Certificate_Public.pem file..."
    open("Certificate_Public.pem", "w").write(cert_pub.to_pem())  #Saving to file
    cert_pub = cert_pub.to_string()
    keccak.update(cert_pub)
    cert_address = keccak.hexdigest()[24:]
    open("Cert_Address.txt", "w").write("0x" + cert_address)

    print "Generating \"Revocation\" Private Key..."
    rev_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Revocation" private key
    print "Saving to Revocation_Private.pem file..."
    open("Revocation_Private.pem", "w").write(rev_priv.to_pem())  #Saving to file
    print "Generating \"Revocation\" Public Key..."
    rev_pub = rev_priv.get_verifying_key()  #Generate the "Revocation" public key from rev_priv
    print "Saving to Revocation_Public.pem file..."
    open("Revocation_Public.pem", "w").write(rev_pub.to_pem())  #Saving to file
    rev_pub = rev_pub.to_string()
    keccak.update(rev_pub)
    rev_address = keccak.hexdigest()[24:]
    open("Rev_Address.txt", "w").write("0x" + rev_address)

    print "\nYour addresses are:"
    print "\nGeneration Address: 0x" + gen_address
    print "\nCertificate Address: 0x" + cert_address
    print "\nRevocation Address: 0x" + rev_address
    os.system("echo 3 | keybase currency add --force " + cert_address + " >/dev/null 2>&1") #add cert address to keybase account - (todo)
    print "\nCertificate address added to your keybase.io account.\n"
    print "\nPlease load your Generation and Revocation addresses with some ether."
    print "\nWarning: Please keep your Revocation address secret!"
    ans = raw_input("Do you want to encrypt your private key files? [Y]es [N]o, default: [Y]")
    if ans == "Y" or ans == "y" or ans == "" or ans == " ":
        password = getpass.getpass("Give a strong password: "******"Generation_Private.pem")
        os.remove("Generation_Private.pem")
        encrypt_file(key, "Certificate_Private.pem")
        os.remove("Certificate_Private.pem")
        encrypt_file(key, "Revocation_Private.pem")
        os.remove("Revocation_Private.pem")
        sys.exit()
    else:
        sys.exit()
예제 #45
0
def get_eth_addr(pk):
    pub_key = pk.to_string()
    m = keccak_256()
    m.update(pub_key)
    return m.hexdigest()[24:]
예제 #46
0
def hash_of_point(p):
    hasher = sha3.keccak_256()
    hasher.update(int_to_bytes32(p[0].n))
    hasher.update(int_to_bytes32(p[1].n))
    x = bytes_to_int(hasher.digest())
    return x
예제 #47
0
def auth_view(request):
    """
    This view handle all authentication-related logic
    """
    response_data = {}
    if request.method == 'GET':
        # Obtain authentication information - `is_authenticated`, `username`, `nonce`
        response_data.update(
            {'is_authenticated': request.user.is_authenticated})
        if request.user.is_authenticated:
            response_data.update({'username': request.user.username})
        else:
            nonce = ''.join(
                random.choice(settings.AUTH_NONCE_CHOICES)
                for _ in range(settings.AUTH_NONCE_LENGTH))
            response_data.update({'nonce': nonce})
            request.session['login_nonce'] = nonce
    elif request.method == 'POST':
        if settings.DEBUG:  # pragma: no cover
            # Allow username/password auth in debug mode
            if 'username' in request.data and 'password' in request.data:
                username = request.data['username']
                password = request.data['password']
                user = get_object_or_404(User, username=username)
                if user.check_password(password):
                    login(request,
                          user,
                          backend="django.contrib.auth.backends.ModelBackend")
                    response_data.update(
                        {'is_authenticated': request.user.is_authenticated})
                    response_data.update({'username': request.user.username})
                    return Response(data=response_data,
                                    status=status.HTTP_200_OK)

        # Authenticate user by signed `nonce` == `user_signature` and verify against `user_address`
        login_nonce = request.session.pop('login_nonce', None)
        if not login_nonce:
            return Response(
                data={
                    "login_nonce": "Session id doesn't have a `login_nonce`"
                },
                status=status.HTTP_400_BAD_REQUEST,
            )
        else:
            user_address = request.data.get('user_address')
            if not user_address:
                return Response(
                    data={
                        "user_address": "Request doesn't have a `user_address`"
                    },
                    status=status.HTTP_400_BAD_REQUEST,
                )

            user_signature = request.data.get('user_signature')
            if not user_signature:
                return Response(
                    data={
                        "user_signature":
                        "Request doesn't have a `user_signature`"
                    },
                    status=status.HTTP_400_BAD_REQUEST,
                )
            # Start the sign-up process
            seed = "\x19Ethereum Signed Message:\n" + str(
                len(login_nonce)) + login_nonce
            buffered_hashed_msg = ethereum.utils.sha3(seed)
            vrs = utils.sig_to_vrs(user_signature)
            recovered_addr = '0x' + sha3.keccak_256(
                ethereum.utils.ecrecover_to_pub(buffered_hashed_msg, *
                                                vrs)).hexdigest()[24:]
            if not recovered_addr == user_address:
                return Response(
                    data={
                        "user_signature":
                        "User signature doesn't match `user_address`"
                    },
                    status=status.HTTP_400_BAD_REQUEST,
                )

            user, created = User.objects.get_or_create(
                username=recovered_addr, )
            login(request,
                  user,
                  backend="django.contrib.auth.backends.ModelBackend")

            response_data.update(
                {'is_authenticated': request.user.is_authenticated})
            response_data.update({'username': request.user.username})
            response_data.update({'created': created})
    return Response(data=response_data, status=status.HTTP_200_OK)
예제 #48
0
def hash_of_int(i):
    hasher = sha3.keccak_256(int_to_bytes32(i))
    x = bytes_to_int(hasher.digest())
    return x
예제 #49
0
 def public_key_to_ethereum_address(public_key):
     public_key = Bip32Keys.to_uncompressed_public_key(public_key)[2:]  # drop pub key version byte
     k = sha3.keccak_256()
     k.update(decode_hex(public_key)[0])
     hash = k.hexdigest()
     return hash[24:]
예제 #50
0
#coding:utf-8

import sha3
import binascii
from ecdsa import SigningKey, SECP256k1

priv = SigningKey.generate(curve=SECP256k1) #生成私钥
pub = priv.get_verifying_key() #生成公钥

keccak = sha3.keccak_256()
keccak.update( pub.to_string()) #keccak_256哈希运算
address = "0x" + keccak.hexdigest()[24:]

priv_key = binascii.hexlify( priv.to_string())
pub_key = binascii.hexlify( pub.to_string())

print("Private key: " + priv_key.decode() )
print("Public key:  " + pub_key.decode() )
print("Address:     " + address)

print "#############################"

_openssl_pub_key = "04d061e9c5891f579fd548cfd22ff29f5c642714cc7e7a9215f0071ef5a5723f691757b28e31be71f09f24673eed52348e58d53bcfd26f4d96ec6bf1489eab429d"

_pub_key = _openssl_pub_key[2:]
_pub_hex = binascii.unhexlify(_pub_key)

keccak = sha3.keccak_256()
keccak.update(_pub_hex)

address = "0x" + keccak.hexdigest()[24:]
예제 #51
0
 def generateID(self):
     k = keccak_256()
     k.update(unhexlify(self.question_id[2:]) + bytes(self.block_id))
     self.event_id = "0x" + k.hexdigest()
예제 #52
0
 def RingHashFunction(msgHash, point):
     hasher = sha3.keccak_256()
     hasher.update(msgHash)
     hasher.update(int_to_bytes32(point[0].n))
     hasher.update(int_to_bytes32(point[1].n))
     return bytes_to_int(hasher.digest())