Python hashlib.sha512() Examples

The following are 30 code examples of hashlib.sha512(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hashlib , or try the search function .
Example #1
Source File: test_network_permissioning.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def send(self):
        name = uuid4().hex[:20]
        txns = [
            self._factory.create_transaction(
                cbor.dumps({
                    'Name': name,
                    'Verb': 'set',
                    'Value': 1000
                }),
                inputs=[
                    self._namespace + self._factory.sha512(name.encode())[-64:]
                ],
                outputs=[
                    self._namespace + self._factory.sha512(name.encode())[-64:]
                ],
                deps=[])
        ]
        self._rest.send_batches(self._factory.create_batch(txns)) 
Example #2
Source File: run.py    From minicps with MIT License 6 votes vote down vote up
def check_auth(username, password):

    ADMIN_512 = 'bf33ea356054cbac9cc9b65c475b8b7ea0a1347d1f28b8f92cf065614cc7853b4f1d66e498111aed84f8741feeda553229c970fdaec5cf60b8c00250bbdcb6cf'

    ATTACKER_512 = '56aff393533461d974487c1222171a5a6a0a6fe883c7658070ee3c38022c52a3de0d74a634a909b2eb78bd109bc830d81939033a11e7fc77b5458848264f57f3'


    if username == 'admin':

        admin_512 = sha512(password.strip()).hexdigest()
        return admin_512 == ADMIN_512

    elif username == 'attacker':

        attacker_512 = sha512(password.strip()).hexdigest()
        return attacker_512 == ATTACKER_512

    else:
        return False 
Example #3
Source File: signature_verifier.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def is_valid_transaction(txn):
    # validate transactions signature
    header = TransactionHeader()
    header.ParseFromString(txn.header)

    context = create_context('secp256k1')
    public_key = Secp256k1PublicKey.from_hex(header.signer_public_key)
    if not context.verify(txn.header_signature,
                          txn.header,
                          public_key):
        LOGGER.debug("transaction signature invalid for txn: %s",
                     txn.header_signature)
        return False

    # verify the payload field matches the header
    txn_payload_sha512 = hashlib.sha512(txn.payload).hexdigest()
    if txn_payload_sha512 != header.payload_sha512:
        LOGGER.debug("payload doesn't match payload_sha512 of the header"
                     "for txn: %s", txn.header_signature)
        return False

    return True 
Example #4
Source File: proxy.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def _wrap_consensus_message(self, content, message_type, connection_id):
        _, name, version, _ = self._consensus_registry.get_active_engine_info()
        header = ConsensusPeerMessageHeader(
            signer_id=self._public_key,
            content_sha512=hashlib.sha512(content).digest(),
            message_type=message_type,
            name=name,
            version=version,
        ).SerializeToString()

        signature = bytes.fromhex(self._identity_signer.sign(header))
        message = ConsensusPeerMessage(
            header=header,
            content=content,
            header_signature=signature)

        return message 
Example #5
Source File: block_tree_manager.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def generate_transaction(self, payload='txn', deps=None):
        payload_encoded = payload.encode('utf-8')
        hasher = hashlib.sha512()
        hasher.update(payload_encoded)

        txn_header = TransactionHeader(
            dependencies=([] if deps is None else deps),
            batcher_public_key=self.signer.get_public_key().as_hex(),
            family_name='test',
            family_version='1',
            nonce=_generate_id(16),
            payload_sha512=hasher.hexdigest().encode(),
            signer_public_key=self.signer.get_public_key().as_hex()
        ).SerializeToString()

        txn = Transaction(
            header=txn_header,
            header_signature=self.signer.sign(txn_header),
            payload=payload_encoded)

        return txn 
Example #6
Source File: onepass.py    From opvault with GNU General Public License v3.0 6 votes vote down vote up
def _derive_keys(master_password, salt, iterations):
        derived_key = hashlib.pbkdf2_hmac(
            'sha512', master_password, salt, iterations)
        key = derived_key[:32]
        hmac_key = derived_key[32:64]

        return key, hmac_key 
Example #7
Source File: _pfish_tools.py    From hacking-tools with MIT License 6 votes vote down vote up
def parse_command_line():
    parser= argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required = True)
    group.add_argument('--md5',help='specifies MD5 algorithm',action='store_true')
    group.add_argument('--sha256', help='specifies SHA256 algorithm', action='store_true')
    group.add_argument('--sha512', help='specifies SHA512 algorithm', action='store_true')
    parser.add_argument('-d','--dirpath',type=ValidateDirectory,required=True,help="specify the root path for hashing")
    parser.add_argument('-r','--reportpath',type=ValidateDirectoryWritable,required=True,help="specify the path for reports and logs will be written")
    global gl_args
    global gl_hashType
    gl_args = parser.parse_args()
    if gl_args.md5:
        gl_hashType='MD5'
    elif gl_args.sha256:
        gl_hashType='SHA256'
    elif gl_args.sha512:
        gl_hashType='SHA512'
    else:
        gl_hashType='unknown' 
Example #8
Source File: test_block_info_injector.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def make_intkey_address(name):
    return INTKEY_ADDRESS_PREFIX + hashlib.sha512(
        name.encode('utf-8')).hexdigest()[-64:] 
Example #9
Source File: tests.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _generate_id(self):
        return hashlib.sha512(''.join(
            [random.choice(string.ascii_letters)
                for _ in range(0, 1024)]).encode()).hexdigest() 
Example #10
Source File: test_block_info_injector.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def create_transaction(signer, verb, name, value):
    payload = cbor.dumps({'Verb': verb, 'Name': name, 'Value': value},
                         sort_keys=True)

    addresses = [make_intkey_address(name)]

    nonce = hex(random.randint(0, 2**64))

    txn_pub_key = signer.get_public_key().as_hex()
    header = TransactionHeader(
        signer_public_key=txn_pub_key,
        family_name="intkey",
        family_version="1.0",
        inputs=addresses,
        outputs=addresses,
        dependencies=[],
        payload_sha512=hashlib.sha512(payload).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex(),
        nonce=nonce
    )

    signature = signer.sign(header.SerializeToString())

    return Transaction(
        header=header.SerializeToString(),
        payload=payload,
        header_signature=signature) 
Example #11
Source File: __init__.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def digest(path):
    with open(path, 'r') as f:
        s = f.read()
    return sha512(s).digest() 
Example #12
Source File: onepass.py    From opvault with GNU General Public License v3.0 5 votes vote down vote up
def decrypt_keys(self, encrypted_key, derived_key, derived_mac_key):
        """Decrypt all encrypted keys"""
        key_base = self.decrypt_opdata(
            encrypted_key, derived_key, derived_mac_key)

        keys = hashlib.sha512(bytes(key_base))
        digest = keys.digest()

        key_from_digest = digest[:32]
        hmac_from_digest = digest[32:64]

        return key_from_digest, hmac_from_digest 
Example #13
Source File: public_endpoint.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_device_login(device_id: str, cache: SeleneCache) -> dict:
    """Generates a login session for a given device id"""
    sha512 = hashlib.sha512()
    sha512.update(bytes(str(uuid.uuid4()), 'utf-8'))
    access = sha512.hexdigest()
    sha512.update(bytes(str(uuid.uuid4()), 'utf-8'))
    refresh = sha512.hexdigest()
    login = dict(
        uuid=device_id,
        accessToken=access,
        refreshToken=refresh,
        expiration=ONE_DAY
    )
    login_json = json.dumps(login)
    # Storing device access token for one:
    cache.set_with_expiration(
        'device.token.access:{access}'.format(access=access),
        login_json,
        ONE_DAY
    )
    # Storing device refresh token for ever:
    cache.set('device.token.refresh:{refresh}'.format(refresh=refresh), login_json)

    # Storing the login session by uuid (that allows us to delete session using the uuid)
    cache.set('device.session:{uuid}'.format(uuid=device_id), login_json)
    return login 
Example #14
Source File: device_code.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def _generate_token():
        """Generate the token used by this API to identify pairing session"""
        sha512 = hashlib.sha512()
        sha512.update(bytes(str(uuid.uuid4()), 'utf-8'))
        return sha512.hexdigest() 
Example #15
Source File: device_refresh_token.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super(DeviceRefreshTokenEndpoint, self).__init__()
        self.sha512 = hashlib.sha512() 
Example #16
Source File: hd.py    From btcpy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_hash(self, index, hardened=False):
        cls = self.__class__
        if hardened:
            data = self._serialize_key() + (index + cls.first_hardened_index).to_bytes(4, 'big')
        else:
            data = self._serialized_public() + index.to_bytes(4, 'big')
        h = bytearray(hmac.new(bytes(self.chaincode), bytes(data), sha512).digest())
        left, right = int.from_bytes(h[:32], 'big'), h[32:]
        if left > cls.curve_order:
            raise ValueError('Left side of hmac generated number bigger than SECP256k1 curve order')
        return left, right 
Example #17
Source File: djbec.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def H(m):
    return hashlib.sha512(m).digest() 
Example #18
Source File: identity.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _create_role_txn(signer, role_name, policy_name):
    role = Role(name=role_name, policy_name=policy_name)
    payload = IdentityPayload(type=IdentityPayload.ROLE,
                              data=role.SerializeToString())

    policy_address = _policy_to_address(policy_name)
    role_address = _role_to_address(role_name)

    header = TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name='sawtooth_identity',
        family_version='1.0',
        inputs=[_REQUIRED_INPUT, policy_address, role_address],
        outputs=[role_address],
        dependencies=[],
        payload_sha512=hashlib.sha512(
            payload.SerializeToString()).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex(),
        nonce=hex(random.randint(0, 2**64)))

    header_bytes = header.SerializeToString()

    transaction = Transaction(
        header=header_bytes,
        payload=payload.SerializeToString(),
        header_signature=signer.sign(header_bytes))

    return transaction 
Example #19
Source File: test_events_and_receipts.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def create_transaction(signer, verb, name, value):
    payload = cbor.dumps({'Verb': verb, 'Name': name, 'Value': value},
                         sort_keys=True)

    addresses = [make_intkey_address(name)]

    nonce = hex(random.randint(0, 2**64))

    txn_pub_key = signer.get_public_key().as_hex()
    header = TransactionHeader(
        signer_public_key=txn_pub_key,
        family_name="intkey",
        family_version="1.0",
        inputs=addresses,
        outputs=addresses,
        dependencies=[],
        payload_sha512=hashlib.sha512(payload).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex(),
        nonce=nonce
    )

    signature = signer.sign(header.SerializeToString())

    return Transaction(
        header=header.SerializeToString(),
        payload=payload,
        header_signature=signature) 
Example #20
Source File: test_events_and_receipts.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def make_intkey_address(name):
    return INTKEY_ADDRESS_PREFIX + hashlib.sha512(
        name.encode('utf-8')).hexdigest()[-64:] 
Example #21
Source File: test_network_permissioning.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def __init__(self, rest_endpoint):
        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        self.priv_key = private_key.as_hex()
        self.pub_key = context.get_public_key(private_key).as_hex()

        self.signer = CryptoFactory(context).new_signer(private_key)
        self._namespace = hashlib.sha512('intkey'.encode()).hexdigest()[:6]
        self._factory = MessageFactory(
            'intkey',
            '1.0',
            self._namespace,
            signer=self.signer)
        self._rest = RestClient(rest_endpoint) 
Example #22
Source File: tests.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _create_transactions(self, count):
        txn_list = []

        for _ in range(count):
            payload = {
                'Verb': 'set',
                'Name': 'name',
                'Value': 1,
            }

            intkey_prefix = \
                hashlib.sha512('intkey'.encode('utf-8')).hexdigest()[0:6]

            addr = intkey_prefix + \
                hashlib.sha512(payload["Name"].encode('utf-8')).hexdigest()

            payload_encode = hashlib.sha512(cbor.dumps(payload)).hexdigest()

            header = TransactionHeader(
                signer_public_key=self.public_key,
                family_name='intkey',
                family_version='1.0',
                inputs=[addr],
                outputs=[addr],
                dependencies=[],
                payload_sha512=payload_encode)

            header.batcher_public_key = self.public_key

            header_bytes = header.SerializeToString()

            signature = self.signer.sign(header_bytes)

            transaction = Transaction(
                header=header_bytes,
                payload=cbor.dumps(payload),
                header_signature=signature)

            txn_list.append(transaction)

        return txn_list 
Example #23
Source File: yaml_scheduler_tester.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _address(self, add, require_full=False):
        if ':sha' not in add and ',' not in add:
            return add

        if ',' in add:
            return binascii.hexlify(bytearray(
                [int(i) for i in add.split(',')]))

        parts = add.split(':')
        if len(parts) == 3 and parts[2] == 'sha':
            # eg. 'yy:aaabbbb:sha'
            namespace = hashlib.sha512(parts[0].encode()).hexdigest()[:6]
            address = namespace + hashlib.sha512(
                parts[1].encode()).hexdigest()[:64]
        elif len(parts) == 3 and not require_full:
            # eg. 'a:sha:56'
            length = min(int(parts[2]), 70)
            address = hashlib.sha512(parts[0].encode()).hexdigest()[:length]
        elif len(parts) == 2:
            # eg. 'aaabbbb:sha'
            intermediate = parts[0]
            address = hashlib.sha512(intermediate.encode()).hexdigest()[:70]
        else:
            raise ValueError("Address specified by {} could "
                             "not be formed".format(add))
        return address 
Example #24
Source File: yaml_scheduler_tester.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def create_transaction(payload, signer, inputs=None,
                       outputs=None, dependencies=None):
    addr = '000000' + hashlib.sha512(payload).hexdigest()[:64]

    if inputs is None:
        inputs = [addr]

    if outputs is None:
        outputs = [addr]

    if dependencies is None:
        dependencies = []

    header = transaction_pb2.TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name='scheduler_test',
        family_version='1.0',
        inputs=inputs,
        outputs=outputs,
        dependencies=dependencies,
        nonce=str(time.time()),
        payload_sha512=hashlib.sha512(payload).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex())

    header_bytes = header.SerializeToString()

    signature = signer.sign(header_bytes)

    transaction = transaction_pb2.Transaction(
        header=header_bytes,
        payload=payload,
        header_signature=signature)

    return transaction, header 
Example #25
Source File: tests.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _hash(key):
    return hashlib.sha512(key.encode()).hexdigest()[:64] 
Example #26
Source File: tests.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _create_address(self, value=None):
        """
        Args:
            value: (str)

        Returns: (str) sha512 of value or random

        """
        if value is None:
            value = time.time().hex()
        return hashlib.sha512(value.encode()).hexdigest()[:70] 
Example #27
Source File: block_info_injector.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def create_batch(self, block_info):
        payload = BlockInfoTxn(block=block_info).SerializeToString()
        public_key = self._signer.get_public_key().as_hex()
        header = TransactionHeader(
            signer_public_key=public_key,
            family_name=FAMILY_NAME,
            family_version=FAMILY_VERSION,
            inputs=[CONFIG_ADDRESS, BLOCK_INFO_NAMESPACE],
            outputs=[CONFIG_ADDRESS, BLOCK_INFO_NAMESPACE],
            dependencies=[],
            payload_sha512=hashlib.sha512(payload).hexdigest(),
            batcher_public_key=public_key,
        ).SerializeToString()

        transaction_signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=transaction_signature,
        )

        header = BatchHeader(
            signer_public_key=public_key,
            transaction_ids=[transaction_signature],
        ).SerializeToString()

        batch_signature = self._signer.sign(header)

        return Batch(
            header=header,
            transactions=[transaction],
            header_signature=batch_signature,
        ) 
Example #28
Source File: interconnect.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def connection_id(self):
        if not self._connection_id:
            self._connection_id = hashlib.sha512(
                self._send_receive_thread.connection.encode()).hexdigest()

        return self._connection_id 
Example #29
Source File: interconnect.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _do_dealer_heartbeat(self):
        if self._last_message_time and \
                self._is_connection_lost(self._last_message_time):
            LOGGER.info("No response from %s in %s seconds"
                        " - removing connection.",
                        self._connection,
                        self._last_message_time)
            connection_id = hashlib.sha512(
                self.connection.encode()).hexdigest()
            if connection_id in self._connections:
                del self._connections[connection_id]
            yield from self._stop() 
Example #30
Source File: cookiejar_tp.py    From sawtooth-cookiejar with Apache License 2.0 5 votes vote down vote up
def _hash(data):
    '''Compute the SHA-512 hash and return the result as hex characters.'''
    return hashlib.sha512(data).hexdigest()