Python hashlib.sha1() Examples

The following are 30 code examples for showing how to use hashlib.sha1(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module hashlib , or try the search function .

Example 1
Project: macops   Author: google   File: can_haz_image.py    License: Apache License 2.0 7 votes vote down vote up
def GetFileChecksum(self, filepath):
    """Generates checksum of given file.

    Args:
      filepath: String of filepath.

    Returns:
      f_hash: SHA1 hash for the file provided in filepath.
    """
    statinfo = os.stat(filepath)
    if statinfo.st_size/1048576 < 200:
      f_content = open(filepath, 'r').read()
      f_hash = hashlib.sha1(f_content).hexdigest()
      return f_hash
    else:
      cmd = ['shasum', filepath]
      (stdout, unused_sterr, unused_rc) = RunProcess(cmd)
      return stdout.split()[0] 
Example 2
Project: wechatpy   Author: wechatpy   File: utils.py    License: MIT License 6 votes vote down vote up
def check_wxa_signature(session_key, raw_data, client_signature):
    """校验前端传来的rawData签名正确
    详情请参考
    https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html # noqa

    :param session_key: code换取的session_key
    :param raw_data: 前端拿到的rawData
    :param client_signature: 前端拿到的signature
    :raises: InvalidSignatureException
    :return: 返回数据dict
    """
    str2sign = (raw_data + session_key).encode("utf-8")
    signature = hashlib.sha1(str2sign).hexdigest()
    if signature != client_signature:
        from wechatpy.exceptions import InvalidSignatureException

        raise InvalidSignatureException() 
Example 3
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def check_sha1(filename, sha1_hash):
    """Check whether the sha1 hash of the file content matches the expected hash.

    Parameters
    ----------
    filename : str
        Path to the file.
    sha1_hash : str
        Expected sha1 hash in hexadecimal digits.

    Returns
    -------
    bool
        Whether the file content matches the expected hash.
    """
    sha1 = hashlib.sha1()
    with open(filename, 'rb') as f:
        while True:
            data = f.read(1048576)
            if not data:
                break
            sha1.update(data)

    return sha1.hexdigest() == sha1_hash 
Example 4
Project: ipmisim   Author: rhtyd   File: ipmisim.py    License: Apache License 2.0 6 votes vote down vote up
def _got_rakp3(self, data):
        RmRc = struct.pack('B' * len(self.Rm + self.Rc), *(self.Rm + self.Rc))
        self.sik = hmac.new(self.kg, RmRc + struct.pack("2B", self.rolem, len(self.username)) +
                            self.username, hashlib.sha1).digest()
        self.session.k1 = hmac.new(self.sik, '\x01' * 20, hashlib.sha1).digest()
        self.session.k2 = hmac.new(self.sik, '\x02' * 20, hashlib.sha1).digest()
        self.session.aeskey = self.session.k2[0:16]

        hmacdata = struct.pack('B' * len(self.Rc), *self.Rc) + struct.pack("4B", *self.clientsessionid) +\
            struct.pack("2B", self.rolem, len(self.username)) + self.username
        expectedauthcode = hmac.new(self.kuid, hmacdata, hashlib.sha1).digest()
        authcode = struct.pack("%dB" % len(data[8:]), *data[8:])
        if expectedauthcode != authcode:
            self.close_server_session()
            return
        clienttag = data[0]
        if data[1] != 0:
            self.close_server_session()
            return
        self.session.localsid = struct.unpack('<I', struct.pack('4B', *self.managedsessionid))[0]

        logger.debug('IPMI rakp3 request')
        self.session.ipmicallback = self.handle_client_request
        self._send_rakp4(clienttag, 0) 
Example 5
Project: QCElemental   Author: MolSSI   File: molecule.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_hash(self):
        """
        Returns the hash of the molecule.
        """

        m = hashlib.sha1()
        concat = ""

        np.set_printoptions(precision=16)
        for field in self.hash_fields:
            data = getattr(self, field)
            if field == "geometry":
                data = float_prep(data, GEOMETRY_NOISE)
            elif field == "fragment_charges":
                data = float_prep(data, CHARGE_NOISE)
            elif field == "molecular_charge":
                data = float_prep(data, CHARGE_NOISE)
            elif field == "masses":
                data = float_prep(data, MASS_NOISE)

            concat += json.dumps(data, default=lambda x: x.ravel().tolist())

        m.update(concat.encode("utf-8"))
        return m.hexdigest() 
Example 6
Project: gazetteer   Author: LibraryOfCongress   File: history.py    License: MIT License 6 votes vote down vote up
def generate_history(gz_file, dump_path, place_index):
    f = gzip.open(gz_file, 'rb')
    uid = uuid.uuid4()
    unique_name = uid.hex
    dump = Dump(dump_path + "/historydump/history"+unique_name+".%04d.json.gz")
    histindex = place_index+"-history"  #i.e. gazetest2-history
    
    for line in f:
        index_json = line
        doc_id = json.loads(index_json)["index"]["_id"]
        
        doc_json = f.next()  #nextline
        doc = json.loads(doc_json)

        digest = hashlib.sha1(json.dumps(doc, sort_keys=True)).hexdigest()

        #SAVE HISTORY (the records tied to a place which have revisions)
        history_doc = {"index" : place_index, "type": "place", "id" : doc_id, "revisions": [{"user_created":"ETL", "created_at":time.time(),"digest":digest}]}
        
        dump.write_bulk(histindex, "place", doc_id, history_doc)

    f.close()
    dump.close() 
Example 7
Project: TaskBot   Author: EvilPsyCHo   File: WXBizMsgCrypt_py3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getSHA1(self, token, timestamp, nonce, encrypt):
        """用SHA1算法生成安全签名
        @param token:  票据
        @param timestamp: 时间戳
        @param encrypt: 密文
        @param nonce: 随机字符串
        @return: 安全签名
        """
        try:
            token = token.decode()
            sortlist = [token, timestamp, nonce, encrypt]
            sortlist.sort()
            sha = hashlib.sha1()
            sha.update("".join(sortlist).encode("utf8"))
            return ierror.WXBizMsgCrypt_OK, sha.hexdigest()
        except Exception as e:
            print(e)
            return ierror.WXBizMsgCrypt_ComputeSignature_Error, None 
Example 8
Project: TaskBot   Author: EvilPsyCHo   File: WXBizMsgCrypt_py3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def EncryptMsg(self, sReplyMsg, sNonce, timestamp=None):
        # 将公众号回复用户的消息加密打包
        # @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
        # @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
        # @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
        # sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
        # return:成功0,sEncryptMsg,失败返回对应的错误码None
        pc = Prpcrypt(self.key)
        ret, encrypt = pc.encrypt(sReplyMsg, self.appid)
        if ret != 0:
            return ret, None
        if timestamp is None:
            timestamp = str(int(time.time()))
        # 生成安全签名
        sha1 = SHA1()
        ret, signature = sha1.getSHA1(self.token, timestamp, sNonce, encrypt)

        if ret != 0:
            return ret, None
        xmlParse = XMLParse()
        return ret, xmlParse.generate(encrypt, signature, timestamp, sNonce) 
Example 9
Project: TaskBot   Author: EvilPsyCHo   File: WXBizMsgCrypt_py3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def DecryptMsg(self, sPostData, sMsgSignature, sTimeStamp, sNonce):
        # 检验消息的真实性,并且获取解密后的明文
        # @param sMsgSignature: 签名串,对应URL参数的msg_signature
        # @param sTimeStamp: 时间戳,对应URL参数的timestamp
        # @param sNonce: 随机串,对应URL参数的nonce
        # @param sPostData: 密文,对应POST请求的数据
        #  xml_content: 解密后的原文,当return返回0时有效
        # @return: 成功0,失败返回对应的错误码
        # 验证安全签名
        xmlParse = XMLParse()
        ret, encrypt, touser_name = xmlParse.extract(sPostData)
        if ret != 0:
            return ret, None
        sha1 = SHA1()
        ret, signature = sha1.getSHA1(self.token, sTimeStamp, sNonce, encrypt)
        if ret != 0:
            return ret, None
        if not signature == sMsgSignature:
            return ierror.WXBizMsgCrypt_ValidateSignature_Error, None
        pc = Prpcrypt(self.key)
        ret, xml_content = pc.decrypt(encrypt, self.appid)
        return ret, xml_content 
Example 10
Project: oscrypto   Author: wbond   File: trust_list.py    License: MIT License 6 votes vote down vote up
def _cert_details(cert_pointer):
    """
    Return the certificate and a hash of it

    :param cert_pointer:
        A SecCertificateRef

    :return:
        A 2-element tuple:
         - [0]: A byte string of the SHA1 hash of the cert
         - [1]: A byte string of the DER-encoded contents of the cert
    """

    data_pointer = None

    try:
        data_pointer = Security.SecCertificateCopyData(cert_pointer)
        der_cert = CFHelpers.cf_data_to_bytes(data_pointer)
        cert_hash = hashlib.sha1(der_cert).digest()

        return (der_cert, cert_hash)

    finally:
        if data_pointer is not None:
            CoreFoundation.CFRelease(data_pointer) 
Example 11
Project: wechat-analyse   Author: qinyuanpei   File: auth.py    License: MIT License 6 votes vote down vote up
def app_sign(self, expired=0):
        if not self._secret_id or not self._secret_key:
            return self.AUTH_SECRET_ID_KEY_ERROR

        puserid = ''
        if self._userid != '':
            if len(self._userid) > 64:
                return self.AUTH_URL_FORMAT_ERROR
            puserid = self._userid
 
        now = int(time.time())
        rdm = random.randint(0, 999999999)
        plain_text = 'a=' + self._appid + '&k=' + self._secret_id + '&e=' + str(expired) + '&t=' + str(now) + '&r=' + str(rdm) + '&u=' + puserid + '&f=' 
        bin = hmac.new(self._secret_key.encode(), plain_text.encode(), hashlib.sha1)
        s = bin.hexdigest()
        s = binascii.unhexlify(s)
        s = s + plain_text.encode('ascii')
        signature = base64.b64encode(s).rstrip()    #生成签名
        return signature 
Example 12
Project: Telethon   Author: LonamiWebs   File: helpers.py    License: MIT License 6 votes vote down vote up
def generate_key_data_from_nonce(server_nonce, new_nonce):
    """Generates the key data corresponding to the given nonce"""
    server_nonce = server_nonce.to_bytes(16, 'little', signed=True)
    new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
    hash1 = sha1(new_nonce + server_nonce).digest()
    hash2 = sha1(server_nonce + new_nonce).digest()
    hash3 = sha1(new_nonce + new_nonce).digest()

    key = hash1 + hash2[:12]
    iv = hash2[12:20] + hash3 + new_nonce[:4]
    return key, iv


# endregion

# region Custom Classes 
Example 13
Project: Telethon   Author: LonamiWebs   File: authkey.py    License: MIT License 6 votes vote down vote up
def key(self, value):
        if not value:
            self._key = self.aux_hash = self.key_id = None
            return

        if isinstance(value, type(self)):
            self._key, self.aux_hash, self.key_id = \
                value._key, value.aux_hash, value.key_id
            return

        self._key = value
        with BinaryReader(sha1(self._key).digest()) as reader:
            self.aux_hash = reader.read_long(signed=False)
            reader.read(4)
            self.key_id = reader.read_long(signed=False)

    # TODO This doesn't really fit here, it's only used in authentication 
Example 14
Project: insightface   Author: deepinsight   File: download.py    License: MIT License 6 votes vote down vote up
def check_sha1(filename, sha1_hash):
    """Check whether the sha1 hash of the file content matches the expected hash.
    Parameters
    ----------
    filename : str
        Path to the file.
    sha1_hash : str
        Expected sha1 hash in hexadecimal digits.
    Returns
    -------
    bool
        Whether the file content matches the expected hash.
    """
    sha1 = hashlib.sha1()
    with open(filename, 'rb') as f:
        while True:
            data = f.read(1048576)
            if not data:
                break
            sha1.update(data)

    sha1_file = sha1.hexdigest()
    l = min(len(sha1_file), len(sha1_hash))
    return sha1.hexdigest()[0:l] == sha1_hash[0:l] 
Example 15
Project: Radium   Author: mehulj94   File: skype.py    License: Apache License 2.0 6 votes vote down vote up
def get_md5_hash(self, enc_hex, key):
        # convert hash from hex to binary
        enc_binary = binascii.unhexlify(enc_hex)

        # retrieve the salt
        salt = hashlib.sha1('\x00\x00\x00\x00' + key).digest() + hashlib.sha1('\x00\x00\x00\x01' + key).digest()

        # encrypt value used with the XOR operation
        aes_key = self.aes_encrypt(struct.pack('I', 0) * 4, salt[0:32])[0:16]

        # XOR operation
        decrypted = []
        for d in range(16):
            decrypted.append(struct.unpack('B', enc_binary[d])[0] ^ struct.unpack('B', aes_key[d])[0])

        # cast the result byte
        tmp = ''
        for dec in decrypted:
            tmp = tmp + struct.pack(">I", dec).strip('\x00')

        # byte to hex
        return binascii.hexlify(tmp)

    # used for dictionary attack, if user specify a specific file 
Example 16
Project: tornado-zh   Author: tao12345666333   File: auth.py    License: MIT License 6 votes vote down vote up
def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))
    base_string = "&".join(_oauth_escape(e) for e in base_elems)

    key_elems = [escape.utf8(consumer_token["secret"])]
    key_elems.append(escape.utf8(token["secret"] if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1] 
Example 17
Project: tornado-zh   Author: tao12345666333   File: auth.py    License: MIT License 6 votes vote down vote up
def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))

    base_string = "&".join(_oauth_escape(e) for e in base_elems)
    key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))]
    key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1] 
Example 18
Project: tornado-zh   Author: tao12345666333   File: auth.py    License: MIT License 6 votes vote down vote up
def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
    """Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process
    """
    parts = urlparse.urlparse(url)
    scheme, netloc, path = parts[:3]
    normalized_url = scheme.lower() + "://" + netloc.lower() + path

    base_elems = []
    base_elems.append(method.upper())
    base_elems.append(normalized_url)
    base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
                               for k, v in sorted(parameters.items())))
    base_string = "&".join(_oauth_escape(e) for e in base_elems)

    key_elems = [escape.utf8(consumer_token["secret"])]
    key_elems.append(escape.utf8(token["secret"] if token else ""))
    key = b"&".join(key_elems)

    hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
    return binascii.b2a_base64(hash.digest())[:-1] 
Example 19
Project: wechatpy   Author: wechatpy   File: utils.py    License: MIT License 5 votes vote down vote up
def signature(self):
        """Get data signature"""
        self._data.sort()
        str_to_sign = self._delimiter.join(self._data)
        return hashlib.sha1(str_to_sign).hexdigest() 
Example 20
Project: gated-graph-transformer-network   Author: hexahedria   File: util.py    License: MIT License 5 votes vote down vote up
def object_hash(thing):
    class EnumEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, enum.Enum):
                return obj.name
            return super().default(obj)
    strform = json.dumps(thing, sort_keys=True, cls=EnumEncoder)
    h = hashlib.sha1()
    h.update(strform.encode('utf-8'))
    return h.hexdigest() 
Example 21
Project: fishroom   Author: tuna   File: textstore.py    License: GNU General Public License v3.0 5 votes vote down vote up
def new_paste(self, text, sender, **kwargs):
        now = get_now().strftime("%Y-%m-%d %H:%M:%S")
        s = hashlib.sha1()
        s.update((text+sender+now).encode("utf-8"))
        _id = s.hexdigest()[:16]
        key = self.KEY_TMPL.format(id=_id)
        value = json.dumps({
            "title": "Text from {}".format(sender),
            "time": now,
            "content": text,
        })
        self.r.set(key, value)
        return self.URL_TMPL.format(id=_id) 
Example 22
Project: fishroom   Author: tuna   File: api_client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def auth(self, token_id, token_key):
        saved = self.r.hget(self.clients_key, token_id)
        if not saved:
            return False

        m = hashlib.sha1()
        m.update(token_key.encode('utf-8'))
        return m.digest() == saved 
Example 23
Project: fishroom   Author: tuna   File: api_client.py    License: GNU General Public License v3.0 5 votes vote down vote up
def add(self, token_id, token_key, name):
        if self.r.hexists(self.clients_key, token_id):
            raise TokenException("Token Id Existed!")

        m = hashlib.sha1()
        m.update(token_key.encode('utf-8'))
        self.r.hset(self.clients_key, token_id, m.digest())
        self.r.hset(self.clients_name_key, token_id, name) 
Example 24
Project: XFLTReaT   Author: earthquake   File: websocket_proto.py    License: MIT License 5 votes vote down vote up
def calculate_handshake(self, handshake_init):
		magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
		h = hashlib.sha1()
		h.update(handshake_init+magic_string)
		return base64.b64encode(h.digest()) 
Example 25
Project: lyrebird-api-coverage   Author: Meituan-Dianping   File: load_base.py    License: MIT License 5 votes vote down vote up
def get_file_sha1(path):
    with open(path, 'rb') as f:
        sha1obj = hashlib.sha1()
        sha1obj.update(f.read())
        hash_sha1 = sha1obj.hexdigest()
        return hash_sha1 
Example 26
Project: lyrebird-api-coverage   Author: Meituan-Dianping   File: import_file_handler.py    License: MIT License 5 votes vote down vote up
def import_base_handler(self):
        json_file = request.files.get('json-import')
        mimetype = json_file.content_type
        # 判断是不是json格式的文件
        if mimetype == 'application/json':
            # 读取文件流,注意文件流只能read一次
            bytes_obj = json_file.read()
            try:
                check_result = BaseDataHandler().check_base(json.loads(bytes_obj))
                if check_result:
                    return check_result

                self.write_wb(DEFAULT_BASE, bytes_obj)
                # 读取json文件
                json_obj = json.loads(codecs.open(DEFAULT_BASE, 'r', 'utf-8').read())
                # 获取文件的sha1
                app_context.base_sha1 = self.get_sha1(bytes_obj)
                # 初次处理,切换后的result
                mergeAlgorithm.first_result_handler(json_obj)
                mergeAlgorithm.coverage_arithmetic(json_obj)
                resp = context.make_ok_response()
                lyrebird.publish('api_coverage', 'operation', name='import_base')
            except Exception as e:
                resp = context.make_fail_response('导入文件内容格式有误:' + str(e))
                lyrebird.publish('api_coverage', 'error', name='import_base')
        else:
            resp = context.make_fail_response("Error.The selected non - JSON file.")
            lyrebird.publish('api_coverage', 'error', name='import_base')
        return resp 
Example 27
Project: lyrebird-api-coverage   Author: Meituan-Dianping   File: import_file_handler.py    License: MIT License 5 votes vote down vote up
def import_result_handler(self):
        json_file = request.files.get('json-import')
        mimetype = json_file.content_type
        # 读取文件流,注意文件流只能read一次
        bytes_obj = json_file.read()
        try:
            result_obj = json.loads(bytes_obj)
            # 获取import文件的sha1
            import_sha1 = result_obj.get('base_sha1')
            if app_context.base_sha1 == import_sha1:
                # merge import result and cache result
                # check_result_schema(result_obj)
                app_context.coverage = json.loads(bytes_obj).get('coverage')
                mergeAlgorithm.merge_resume(result_obj.get('test_data'))
                # 放入缓存
                # app_context.merge_list = json.loads(bytes_obj).get('test_data')
                # app_context.coverage = json.loads(bytes_obj).get('coverage')
                resp = context.make_ok_response()
                lyrebird.publish('api_coverage', 'operation', name='import_result')
            else:
                resp = context.make_fail_response('导入的测试结果和之前选择base不匹配')
                lyrebird.publish('api_coverage', 'error', name='import_result')
        except Exception as e:
            resp = context.make_fail_response('导入文件内容格式有误:' + str(e))
            lyrebird.publish('api_coverage', 'error', name='import_result')
        return resp 
Example 28
Project: lyrebird-api-coverage   Author: Meituan-Dianping   File: import_file_handler.py    License: MIT License 5 votes vote down vote up
def get_sha1(self, obj):
        sha1obj = hashlib.sha1()
        sha1obj.update(obj)
        hash_sha1 = sha1obj.hexdigest()
        return hash_sha1 
Example 29
Project: macops   Author: google   File: can_haz_image.py    License: Apache License 2.0 5 votes vote down vote up
def GetFileChecksum(self, filepath):
    """Generates checksum of given file.

    Args:
      filepath: String of filepath.

    Returns:
      f_hash: SHA1 hash for the file provided in filepath.
    """
    f_content = open(filepath, 'r').read()
    f_hash = hashlib.sha1(f_content).hexdigest()
    return f_hash 
Example 30
Project: microgear-python   Author: netpieio   File: client.py    License: ISC License 5 votes vote down vote up
def hmac(key, message):
    import base64
    import hmac
    import hashlib

    hash = hmac.new(key.encode('utf-8'),message.encode('utf-8'), hashlib.sha1).digest()
    password = base64.encodestring(hash)
    password = password.strip()

    return password.decode('utf-8')