Python hashlib.sha256() Examples

The following are 30 code examples of hashlib.sha256(). 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: mtprotostate.py    From Telethon with MIT License 7 votes vote down vote up
def encrypt_message_data(self, data):
        """
        Encrypts the given message data using the current authorization key
        following MTProto 2.0 guidelines core.telegram.org/mtproto/description.
        """
        data = struct.pack('<qq', self.salt, self.id) + data
        padding = os.urandom(-(len(data) + 12) % 16 + 12)

        # Being substr(what, offset, length); x = 0 for client
        # "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)"
        msg_key_large = sha256(
            self.auth_key.key[88:88 + 32] + data + padding).digest()

        # "msg_key = substr (msg_key_large, 8, 16)"
        msg_key = msg_key_large[8:24]
        aes_key, aes_iv = self._calc_key(self.auth_key.key, msg_key, True)

        key_id = struct.pack('<Q', self.auth_key.key_id)
        return (key_id + msg_key +
                AES.encrypt_ige(data + padding, aes_key, aes_iv)) 
Example #2
Source File: utils.py    From wechatpy with MIT License 7 votes vote down vote up
def calculate_signature_hmac(params, api_key):
    url = format_url(params, api_key)
    sign = to_text(hmac.new(api_key.encode(), msg=url, digestmod=hashlib.sha256).hexdigest().upper())
    return sign 
Example #3
Source File: file_utils.py    From cmrc2019 with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def url_to_filename(url: str, etag: str = None) -> str:
    """
    Convert `url` into a hashed filename in a repeatable way.
    If `etag` is specified, append its hash to the url's, delimited
    by a period.
    """
    url_bytes = url.encode('utf-8')
    url_hash = sha256(url_bytes)
    filename = url_hash.hexdigest()

    if etag:
        etag_bytes = etag.encode('utf-8')
        etag_hash = sha256(etag_bytes)
        filename += '.' + etag_hash.hexdigest()

    return filename 
Example #4
Source File: utils.py    From indy-anoncreds with Apache License 2.0 6 votes vote down vote up
def get_hash_as_int(*args, group: cmod.PairingGroup = None):
    """
    Enumerate over the input tuple and generate a hash using the tuple values

    :param args: sequence of either group or integer elements
    :param group: pairing group if an element is a group element
    :return:
    """

    group = group if group else cmod.PairingGroup(PAIRING_GROUP)
    h_challenge = sha256()

    serialedArgs = [group.serialize(arg) if isGroupElement(arg)
                    else cmod.Conversion.IP2OS(arg)
                    for arg in args]

    for arg in sorted(serialedArgs):
        h_challenge.update(arg)
    return bytes_to_int(h_challenge.digest()) 
Example #5
Source File: setup.py    From EarthSim with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def build_custom_models():
    """
    Compiles custom bokeh models and stores the compiled JSON alongside
    the original code.
    """
    import earthsim.models.custom_tools
    from earthsim.models import _CUSTOM_MODELS
    from bokeh.util.compiler import _get_custom_models, _compile_models
    custom_models = _get_custom_models(list(_CUSTOM_MODELS.values()))
    compiled_models = _compile_models(custom_models)
    for name, model in custom_models.items():
        compiled = compiled_models.get(name)
        if compiled is None:
            return
        print('\tBuilt %s custom model' % name)
        impl = model.implementation
        hashed = hashlib.sha256(impl.code.encode('utf-8')).hexdigest()
        compiled['hash'] = hashed
        fp = impl.file.replace('.ts', '.json')
        with open(fp, 'w') as f:
            json.dump(compiled, f) 
Example #6
Source File: __init__.py    From EarthSim with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_compiled_models(custom_model, implementation):
    """
    Custom hook to load cached implementation of custom models.
    """
    compiled = old_hook(custom_model, implementation)
    if compiled is not None:
        return compiled

    model = CUSTOM_MODELS.get(custom_model.full_name)
    if model is None:
        return
    ts_file = model.__implementation__
    json_file = ts_file.replace('.ts', '.json')
    if not os.path.isfile(json_file):
        return
    with io.open(ts_file, encoding="utf-8") as f:
        code = f.read()
    with io.open(json_file, encoding="utf-8") as f:
        compiled = json.load(f)
    hashed = hashlib.sha256(code.encode('utf-8')).hexdigest()
    if compiled['hash'] == hashed:
        return AttrDict(compiled)
    return None 
Example #7
Source File: file_utils.py    From mrc-for-flat-nested-ner with Apache License 2.0 6 votes vote down vote up
def url_to_filename(url: str, etag: str = None) -> str:
    """
    Convert `url` into a hashed filename in a repeatable way.
    If `etag` is specified, append its hash to the url's, delimited
    by a period.
    """
    url_bytes = url.encode('utf-8')
    url_hash = sha256(url_bytes)
    filename = url_hash.hexdigest()

    if etag:
        etag_bytes = etag.encode('utf-8')
        etag_hash = sha256(etag_bytes)
        filename += '.' + etag_hash.hexdigest()

    return filename 
Example #8
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 #9
Source File: rp.py    From pywarp with Apache License 2.0 6 votes vote down vote up
def verify(self, authenticator_data, client_data_json, signature, user_handle, raw_id, email):
        "Ascertain the validity of credentials supplied by the client user agent via navigator.credentials.get()"
        email = email.decode()
        if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
            raise Exception("Invalid email address")
        client_data_hash = hashlib.sha256(client_data_json).digest()
        client_data = json.loads(client_data_json)
        assert client_data["type"] == "webauthn.get"
        expect_challenge = self.storage_backend.get_challenge_for_user(email=email, type="authentication")
        assert b64url_decode(client_data["challenge"]) == expect_challenge
        print("expect RP ID:", self.rp_id)
        if self.rp_id:
            assert "https://" + self.rp_id == client_data["origin"]
        # Verify that the value of C.origin matches the Relying Party's origin.
        # Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
        authenticator_data = AuthenticatorData(authenticator_data)
        assert authenticator_data.user_present
        credential = self.storage_backend.get_credential_by_email(email)
        credential.verify(signature, authenticator_data.raw_auth_data + client_data_hash)
        # signature counter check
        return {"verified": True} 
Example #10
Source File: beyondcorp.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _GetHash(self, file_path: Text) -> bytes:
    """Calculates the hash of the boot wim.

    Args:
      file_path: path to the file to be hashed

    Returns:
      hash of boot wim in hex
    """
    block_size = 33554432  # define bytes to read at a time when hashing (32mb)
    hasher = hashlib.sha256()

    with open(file_path, 'rb') as f:
      fb = f.read(block_size)
      while fb:
        hasher.update(fb)
        fb = f.read(block_size)
    return base64.b64encode(hasher.digest()) 
Example #11
Source File: allennlp_file_utils.py    From ConvLab with MIT License 6 votes vote down vote up
def url_to_filename(url: str, etag: str = None) -> str:
    """
    Convert `url` into a hashed filename in a repeatable way.
    If `etag` is specified, append its hash to the url's, delimited
    by a period.
    """
    url_bytes = url.encode('utf-8')
    url_hash = sha256(url_bytes)
    filename = url_hash.hexdigest()

    if etag:
        etag_bytes = etag.encode('utf-8')
        etag_hash = sha256(etag_bytes)
        filename += '.' + etag_hash.hexdigest()

    return filename 
Example #12
Source File: storage.py    From sarlacc with MIT License 6 votes vote down vote up
def get_attachment_by_selector(self, selector):
        """Gets an attachment using a mongodb query.

        Args:
            selector -- a query object for mongodb as documented here: https://docs.mongodb.com/manual/reference/method/db.collection.findOne/

        Returns:
            The attachment object in the following format:
                {
                    tags[]: a list of tag strings attached to this attachment,
                    sha256: the sha256 hash of this attachment,
                    content: the raw file,
                    filename: the filename,
                    _id: the id of the attachment's postgresql record
                }
        """

        sarlacc = self.mongo["sarlacc"]
        return await sarlacc["samples"].find_one(selector) 
Example #13
Source File: _asymmetric.py    From oscrypto with MIT License 6 votes vote down vote up
def fingerprint(self):
        """
        Creates a fingerprint that can be compared with a private key to see if
        the two form a pair.

        This fingerprint is not compatible with fingerprints generated by any
        other software.

        :return:
            A byte string that is a sha256 hash of selected components (based
            on the key type)
        """

        if self._fingerprint is None:
            self._fingerprint = _fingerprint(self.asn1, None)
        return self._fingerprint 
Example #14
Source File: authority.py    From certidude with MIT License 6 votes vote down vote up
def delete_request(common_name, user="root"):
    # Validate CN
    if not re.match(const.RE_COMMON_NAME, common_name):
        raise ValueError("Invalid common name")

    path, buf, csr, submitted = get_request(common_name)
    os.unlink(path)

    logger.info("Rejected signing request %s by %s" % (
        common_name, user))

    # Publish event at CA channel
    push.publish("request-deleted", common_name)

    # Write empty certificate to long-polling URL
    requests.delete(
        config.LONG_POLL_PUBLISH % hashlib.sha256(buf).hexdigest(),
        headers={"User-Agent": "Certidude API"}) 
Example #15
Source File: password.py    From Telethon with MIT License 5 votes vote down vote up
def sha256(*p: bytes) -> bytes:
    hash = hashlib.sha256()
    for q in p:
        hash.update(q)
    return hash.digest() 
Example #16
Source File: mtprotostate.py    From Telethon with MIT License 5 votes vote down vote up
def _calc_key(auth_key, msg_key, client):
        """
        Calculate the key based on Telegram guidelines for MTProto 2,
        specifying whether it's the client or not. See
        https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector
        """
        x = 0 if client else 8
        sha256a = sha256(msg_key + auth_key[x: x + 36]).digest()
        sha256b = sha256(auth_key[x + 40:x + 76] + msg_key).digest()

        aes_key = sha256a[:8] + sha256b[8:24] + sha256a[24:32]
        aes_iv = sha256b[:8] + sha256a[8:24] + sha256b[24:32]

        return aes_key, aes_iv 
Example #17
Source File: auth.py    From auth-server-sample with Apache License 2.0 5 votes vote down vote up
def generate_code_challenge(code_verifier):
  m = hashlib.sha256()
  m.update(code_verifier.encode())
  code_challenge = m.digest()
  return base64.b64encode(code_challenge, b'-_').decode().replace('=', '') 
Example #18
Source File: idUtil.py    From hsds with Apache License 2.0 5 votes vote down vote up
def createObjId(obj_type, rootid=None):
    if obj_type not in ('groups', 'datasets', 'datatypes', 'chunks', "roots"):
        raise ValueError("unexpected obj_type")

    prefix = None
    if obj_type == 'datatypes':
        prefix = 't'  # don't collide with datasets
    elif obj_type == "roots":
        prefix = 'g'  # root obj is a group
    else:
        prefix = obj_type[0]
    if (not rootid and obj_type != "roots") or (rootid and not isSchema2Id(rootid)):
        # v1 schema
        objid = prefix + '-' + str(uuid.uuid1())
    else:
        # schema v2
        salt = uuid.uuid4().hex
        # take a hash to randomize the uuid
        token = list(hashlib.sha256(salt.encode()).hexdigest())

        if rootid:
            # replace first 16 chars of token with first 16 chars of rootid
            root_hex = getIdHexChars(rootid)
            token[0:16] = root_hex[0:16]
        else:
            # obj_type == "roots"
            # use only 16 chars, but make it look a 32 char id
            for i in range(16):
                token[16+i] = hexRot(token[i])
        # format as a string
        token = "".join(token)
        objid = prefix + '-' + token[0:8] + '-' + token[8:16] + '-' + token[16:20] + '-' + token[20:26] + '-' + token[26:32]

    return objid 
Example #19
Source File: idUtil.py    From hsds with Apache License 2.0 5 votes vote down vote up
def createObjId(obj_type, rootid=None):
    if obj_type not in ('groups', 'datasets', 'datatypes', 'chunks', "roots"):
        raise ValueError("unexpected obj_type")

    prefix = None
    if obj_type == 'datatypes':
        prefix = 't'  # don't collide with datasets
    elif obj_type == "roots":
        prefix = 'g'  # root obj is a group
    else:
        prefix = obj_type[0]
    if (not rootid and obj_type != "roots") or (rootid and not isSchema2Id(rootid)):
        # v1 schema
        objid = prefix + '-' + str(uuid.uuid1())
    else:
        # schema v2
        salt = uuid.uuid4().hex
        # take a hash to randomize the uuid
        token = list(hashlib.sha256(salt.encode()).hexdigest())

        if rootid:
            # replace first 16 chars of token with first 16 chars of rootid
            root_hex = getIdHexChars(rootid)
            token[0:16] = root_hex[0:16]
        else:
            # obj_type == "roots"
            # use only 16 chars, but make it look a 32 char id
            for i in range(16):
                token[16+i] = hexRot(token[i])
        # format as a string
        token = "".join(token)
        objid = prefix + '-' + token[0:8] + '-' + token[8:16] + '-' + token[16:20] + '-' + token[20:26] + '-' + token[26:32]

    return objid 
Example #20
Source File: utils.py    From indy-anoncreds with Apache License 2.0 5 votes vote down vote up
def encodeAttr(attrValue):
    return cmod.Conversion.bytes2integer(sha256(str(attrValue).encode()).digest()) 
Example #21
Source File: pipe.py    From Twitch-Chat-Downloader with MIT License 5 votes vote down vote up
def _map_user_colors(self, data: Dict[str, Any]):
        if 'message' in data:

            # Set color
            if 'user_color' not in data['message']:
                if 'default_user_color' in self.format_dictionary and self.format_dictionary[
                    'default_user_color'] not in ['random',
                                                  'hash']:
                    data['message']['user_color'] = self.format_dictionary['default_user_color']
                else:
                    # Assign color based on commenter's ID
                    sha256 = hashlib.sha256()
                    sha256.update(str.encode(data['commenter']['_id']))

                    # Truncate hash and mod it by 0xffffff-1 for color hex.
                    color: str = hex(int(sha256.hexdigest()[:32], 16) % int(hex(0xffffff), 16)).lstrip('0x')

                    # Add any missing digits
                    while len(color) < 6:
                        color = color + '0'

                    data['message']['user_color'] = '#{color}'.format(color=color[:6])

            # SSA Color
            if 'message[ssa_user_color]' in self.combined_formats:
                data['message']['ssa_user_color'] = '#{b}{g}{r}'.format(
                    b=data['message']['user_color'][5:7],
                    g=data['message']['user_color'][3:5],
                    r=data['message']['user_color'][1:3]) 
Example #22
Source File: ssl_.py    From jawfish with MIT License 5 votes vote down vote up
def assert_fingerprint(cert, fingerprint):
    """
    Checks if given fingerprint matches the supplied certificate.

    :param cert:
        Certificate as bytes object.
    :param fingerprint:
        Fingerprint as string of hexdigits, can be interspersed by colons.
    """

    # Maps the length of a digest to a possible hash function producing
    # this digest.
    hashfunc_map = {
        16: md5,
        20: sha1,
        32: sha256,
    }

    fingerprint = fingerprint.replace(':', '').lower()
    digest_length, odd = divmod(len(fingerprint), 2)

    if odd or digest_length not in hashfunc_map:
        raise SSLError('Fingerprint is of invalid length.')

    # We need encode() here for py32; works on py2 and p33.
    fingerprint_bytes = unhexlify(fingerprint.encode())

    hashfunc = hashfunc_map[digest_length]

    cert_digest = hashfunc(cert).digest()

    if not cert_digest == fingerprint_bytes:
        raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
                       .format(hexlify(fingerprint_bytes),
                               hexlify(cert_digest))) 
Example #23
Source File: importscan.py    From ptnotes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_item(self, ip, port, proto, note):
        """
        Only add new item to database if it does not exist. Use hash to
        determine if item is a duplicate.
        """
        h = hashlib.sha256(''.join([ip, str(port), proto, note])).hexdigest()

        if self.db.itemdb.get_items_by_hash(h) == []:
            if self.db.itemdb.create_item(ip, port, proto, note, h) is False:
                self.log.error('Unable to create new item in database.')
        else:
            self.log.info('Item already exists in database.') 
Example #24
Source File: mmbot.py    From MaliciousMacroBot with MIT License 5 votes vote down vote up
def get_file_hash(self, pathtofile):
        """
        Computes the MD5 hash of the file
        :param pathtofile: absolute or relative path to a file
        :return: md5 hash of file as a string
        """
        if os.path.isfile(pathtofile):
            with open(pathtofile, 'rb') as file_to_hash:
                filedata = file_to_hash.read()
                md5 = hashlib.md5(filedata).hexdigest()
                # sha1 = hashlib.sha1(filedata).hexdigest()
                # sha256 = hashlib.sha256(filedata).hexdigest()
                return md5
        return None 
Example #25
Source File: checks.py    From cert-verifier with MIT License 5 votes vote down vote up
def do_execute(self):
        blockchain_hash = self.transaction_info.op_return
        local_hash = hashlib.sha256(self.content_to_verify).hexdigest()
        return hashes_match(blockchain_hash, local_hash) 
Example #26
Source File: checks.py    From cert-verifier with MIT License 5 votes vote down vote up
def hash_normalized(normalized):
    encoded = normalized.encode('utf-8')
    return hashlib.sha256(encoded).hexdigest() 
Example #27
Source File: account.py    From Authenticator with GNU General Public License v2.0 5 votes vote down vote up
def create(username, provider, token):
        """
        Create a new Account.
        :param username: the account's username
        :param provider: the account's provider
        :param token: the OTP secret token
        :return: Account object
        """
        # Encrypt the token to create a secret_id
        secret_id = sha256(token.encode('utf-8')).hexdigest()
        # Save the account
        obj = Database.get_default().insert(username, provider, secret_id)
        Keyring.insert(secret_id, provider, username, token)
        return Account(obj['id'], username, provider, secret_id) 
Example #28
Source File: pwnpass.py    From password_pwncheck with MIT License 5 votes vote down vote up
def hashToken(self,token):
        return hexlify(pbkdf2_hmac( 'sha256',
                                    token.encode('utf-8'), 
                                    sha1(   'CBoePassword'.encode('utf-8')).digest(),
                                            100000)) 
Example #29
Source File: pwnpass.py    From password_pwncheck with MIT License 5 votes vote down vote up
def makeHash(self,token):
        return hashlib.sha256(token.encode('utf-8')).hexdigest() 
Example #30
Source File: request.py    From certidude with MIT License 5 votes vote down vote up
def on_get(self, req, resp, cn):
        """
        Fetch certificate signing request as PEM
        """

        try:
            path, buf, _, submitted = self.authority.get_request(cn)
        except errors.RequestDoesNotExist:
            logger.warning("Failed to serve non-existant request %s to %s",
                cn, req.context.get("remote_addr"))
            raise falcon.HTTPNotFound()

        resp.set_header("Content-Type", "application/pkcs10")
        logger.debug("Signing request %s was downloaded by %s",
            cn, req.context.get("remote_addr"))

        preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))

        if preferred_type == "application/x-pem-file":
            # For certidude client, curl scripts etc
            resp.set_header("Content-Type", "application/x-pem-file")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
            resp.body = buf
        elif preferred_type == "application/json":
            # For web interface events
            resp.set_header("Content-Type", "application/json")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
            resp.body = json.dumps(dict(
                submitted = submitted,
                common_name = cn,
                address = getxattr(path, "user.request.address").decode("ascii"), # TODO: move to authority.py
                md5sum = hashlib.md5(buf).hexdigest(),
                sha1sum = hashlib.sha1(buf).hexdigest(),
                sha256sum = hashlib.sha256(buf).hexdigest(),
                sha512sum = hashlib.sha512(buf).hexdigest()), cls=MyEncoder)
        else:
            raise falcon.HTTPUnsupportedMediaType(
                "Client did not accept application/json or application/x-pem-file")