當前位置: 首頁>>代碼示例>>Python>>正文


Python hashlib.md5方法代碼示例

本文整理匯總了Python中hashlib.md5方法的典型用法代碼示例。如果您正苦於以下問題:Python hashlib.md5方法的具體用法?Python hashlib.md5怎麽用?Python hashlib.md5使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在hashlib的用法示例。


在下文中一共展示了hashlib.md5方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: hash

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def hash(self, state: str) -> str:
        """Generate a hash representing the current sample state.

        :param state: string capturing the current system configuration state

        This function must be overridden to generate a meaningful hash for the current
        set of input samples."""

        newstate = io.BytesIO(state.encode('utf-8'))

        for k in ('input_patterns', 'samples_dir', 'val_dir', 'val_num', 'val_perc',
                  'test_dir', 'test_num', 'test_perc', 'random_seed'):
            newstate.write(str(getattr(self, k)).encode('utf-8'))

        md5 = hashlib.md5()
        md5.update(newstate.getvalue())
        return md5.hexdigest() 
開發者ID:mme,項目名稱:vergeml,代碼行數:19,代碼來源:io.py

示例2: create_user

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def create_user(conn, username, password):
    try:
        cur = conn.cursor()
        cur.execute("SELECT passwd FROM pg_shadow WHERE usename = %s", [username])
        row = cur.fetchone()
        if row:
            m = hashlib.md5()
            m.update(password + username)
            encrypted_password = "md5" + m.hexdigest()
            if encrypted_password != row[0]:
                cur.execute("ALTER USER " + username + " ENCRYPTED PASSWORD %s SUPERUSER REPLICATION", [password])
        else:
            cur.execute("CREATE USER " + username + " WITH ENCRYPTED PASSWORD %s SUPERUSER REPLICATION", [password])
        conn.commit()
        return True
    except psycopg2.Error as e:
        print(e)
        conn.rollback()
        return False 
開發者ID:rtshome,項目名稱:pgrepup,代碼行數:21,代碼來源:database.py

示例3: get_file_md5_2

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def get_file_md5_2(file_path):
    """
    分段讀取,獲取文件的md5值
    :param file_path:
    :return:
    """
    with open(file_path, 'rb') as file:
        md5_obj = hashlib.md5()
        while True:
            buffer = file.read(8096)
            if not buffer:
                break
            md5_obj.update(buffer)
        hash_code = md5_obj.hexdigest()
    md5 = str(hash_code).lower()
    return md5 
開發者ID:xingag,項目名稱:tools_python,代碼行數:18,代碼來源:視頻特殊處理.py

示例4: ingest_data

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def ingest_data(self, **kwargs):
        """Parse and save design data.

        :param content: String of valid Deckhand YAML

        :returns: a tuple of a status response and a list of parsed objects from drydock_provisioner.objects
        """
        def local_parse():
            return self.parse_docs(kwargs.get('content'))

        if 'content' in kwargs:
            try:
                # Hash the input to use as the cache key. This is not a security
                # related hash, so use cheap and fast MD5
                hv = hashlib.md5(kwargs.get('content', b'')).hexdigest()
                local_cache = cache.get_cache('parsed_docs')
                results = local_cache.get(key=hv, createfunc=local_parse)
                parse_status, models = results
            except Exception as ex:
                self.logger.debug("Error parsing design - hash %s", hv, exc_info=ex)
                raise ex
        else:
            raise ValueError('Missing parameter "content"')

        return parse_status, models 
開發者ID:airshipit,項目名稱:drydock,代碼行數:27,代碼來源:deckhand.py

示例5: add_account

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def add_account(self, account, nickname, password):
        """
        添加客服賬號
        詳情請參考
        http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html

        :param account: 完整客服賬號,格式為:賬號前綴@公眾號微信號
        :param nickname: 客服昵稱,最長6個漢字或12個英文字符
        :param password: 客服賬號登錄密碼
        :return: 返回的 JSON 數據包
        """
        password = to_binary(password)
        password = hashlib.md5(password).hexdigest()
        return self._post(
            "https://api.weixin.qq.com/customservice/kfaccount/add",
            data={"kf_account": account, "nickname": nickname, "password": password},
        ) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:19,代碼來源:customservice.py

示例6: update_account

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def update_account(self, account, nickname, password):
        """
        更新客服賬號
        詳情請參考
        http://mp.weixin.qq.com/wiki/1/70a29afed17f56d537c833f89be979c9.html

        :param account: 完整客服賬號,格式為:賬號前綴@公眾號微信號
        :param nickname: 客服昵稱,最長6個漢字或12個英文字符
        :param password: 客服賬號登錄密碼
        :return: 返回的 JSON 數據包
        """
        password = to_binary(password)
        password = hashlib.md5(password).hexdigest()
        return self._post(
            "https://api.weixin.qq.com/customservice/kfaccount/update",
            data={"kf_account": account, "nickname": nickname, "password": password},
        ) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:19,代碼來源:customservice.py

示例7: verifyChecksumForDir

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def verifyChecksumForDir(dirName, settings, type):
    """
        For each file listed in a list, verifies its checksum.
    """

    dirName = os.path.join(settings.getLocalDst(type), dirName)

    urlChecksumFile = settings.getRemoteSrc() + '/' + os.path.basename(dirName) + '.checksum'
    print("Verification of the decompressed directory '%s' started." % dirName)
    try:
        for line in urllib2.urlopen(urlChecksumFile):
            f, checksum = line.split('\t')
            f = os.path.join(dirName, f)
            # if checksum.strip() != hashlib.md5(open(f).read()).hexdigest():
            if checksum.strip() != getChecksumForFile(f):
                raise Exception("File '%s' is corrupted, it has a wrong checksum." % f)
    except Exception as e:
        print("Unable to verify directory: %s" % dirName)
        raise e

    print("Checksum verification completed successfully!") 
開發者ID:CAMI-challenge,項目名稱:CAMISIM,代碼行數:23,代碼來源:update.py

示例8: send

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def send(self):
        pwhash = md5(self.conf['sms_http_password']).hexdigest()

        params = {
            'username'  : self.conf['sms_http_user'],
            'password'  : pwhash,
            'message'   : self.body,
            'from'      : self.sender,
            'to'        : self.recipient,
        }

        if self.msg:
            dlruri = settings.SERVO_URL + '/api/messages/?id={0}'.format(self.msg.code)
            params['notify_url'] = dlruri

        params = urllib.urlencode(params)
        r = urllib.urlopen(self.URL, params, context=_create_unverified_context()).read()

        if 'ERROR:' in r:
            raise ValueError(self.ERRORS.get(r, _('Unknown error (%s)') % r)) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:22,代碼來源:sms.py

示例9: _sign_fields

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def _sign_fields(signable_fields):  # type: (SignableFields) -> str
    """
    Common signing code.
    """
    for (k, v) in signable_fields:
        assert isinstance(k, str), repr(k)
        assert isinstance(v, str), repr(v)

    if sys.version_info < (3,):
        # Python 2 doesn't do IRI encoding.
        text = urlencode([
            (k.encode('utf-8'), v.encode('utf-8'))
            for (k, v) in signable_fields
        ])
    else:
        text = urlencode(signable_fields, encoding='utf-8', errors='strict')

    return md5(text.encode('ascii')).hexdigest()


#: The checkout signature should ignore these leading and trailing whitespace characters.
#:
#: This list is an educated guess based on the PHP trim() function.
#: 
開發者ID:PiDelport,項目名稱:django-payfast,代碼行數:26,代碼來源:api.py

示例10: __init__

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def __init__(self, Nplanets=1e8, **specs):
        
        # bring in inherited Completeness prototype __init__ values
        Completeness.__init__(self, **specs)
        
        # Number of planets to sample
        self.Nplanets = int(Nplanets)
       
        # get path to completeness interpolant stored in a pickled .comp file
        self.filename = self.PlanetPopulation.__class__.__name__ + self.PlanetPhysicalModel.__class__.__name__ + self.__class__.__name__

        # get path to dynamic completeness array in a pickled .dcomp file
        self.dfilename = self.PlanetPopulation.__class__.__name__ + \
                         self.PlanetPhysicalModel.__class__.__name__ +\
                         specs['modules']['OpticalSystem'] + \
                         specs['modules']['StarCatalog'] + \
                         specs['modules']['TargetList']
        atts = list(self.PlanetPopulation.__dict__)
        self.extstr = ''
        for att in sorted(atts, key=str.lower):
            if not callable(getattr(self.PlanetPopulation, att)) and att != 'PlanetPhysicalModel':
                self.extstr += '%s: ' % att + str(getattr(self.PlanetPopulation, att)) + ' '
        ext = hashlib.md5(self.extstr.encode("utf-8")).hexdigest()
        self.filename += ext
        self.filename.replace(" ","") #Remove spaces from string (in the case of prototype use) 
開發者ID:dsavransky,項目名稱:EXOSIMS,代碼行數:27,代碼來源:BrownCompleteness.py

示例11: get_file_meta_data

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def get_file_meta_data(self, filepath, filename=None, getHash=False):
        """
        helper function to get meta information about a file to include it's path, date modified, size
        :param filepath: path to a file
        :param filename: filename
        :param getHash: whether or not the hash should be computed
        :return: a tuple of format (filename, filepath, filesize, filemodified, md5)
        """
        if filename is None:
            filename = os.path.split(filepath)[1]

        filemodified = time.ctime(os.path.getmtime(filepath))
        filesize = os.path.getsize(filepath)
        md5 = np.nan
        if getHash:
            md5 = self.get_file_hash(filepath)
        return (filename, filepath, filesize, filemodified, md5) 
開發者ID:egaus,項目名稱:MaliciousMacroBot,代碼行數:19,代碼來源:mmbot.py

示例12: create_webinfo_db

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def create_webinfo_db(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS webinfo (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                time varchar(255),
                domain varchar(255),
                waf varchar(255) DEFAULT '',
                title varchar(255) DEFAULT '',
                apps varchar(255) DEFAULT '',
                server varchar(255) DEFAULT '',
                address varchar(255) DEFAULT '',
                ipaddr varchar(255) DEFAULT '',
                os varchar(255) DEFAULT '',
                md5 varchar(40) UNIQUE
                )
                """)
        except sqlite3.OperationalError as e:
            pass 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:22,代碼來源:sqldb.py

示例13: create_ports

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def create_ports(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS ports (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                time varchar(255),
                ipaddr varchar(255),
                service varchar(255) DEFAULT '',
                port varchar(255) DEFAULT '',
                banner varchar(255) DEFAULT '',
                md5 varchar(40) UNIQUE
                )
                """)
        except Exception as e:
            pass 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:18,代碼來源:sqldb.py

示例14: create_urls

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def create_urls(self):
        try:
            cursor = self.conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS urls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                time varchar(255),
                domain varchar(255) DEFAULT '',
                title varchar(255) DEFAULT '',
                url varchar(255) DEFAULT '',
                contype varchar(255) DEFAULT '',
                rsp_len varchar(255) DEFAULT '',
                rsp_code varchar(255) DEFAULT '',
                md5 varchar(40) UNIQUE
                )
                """)
        except Exception as e:
            logging.exception(e) 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:20,代碼來源:sqldb.py

示例15: get_ports

# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import md5 [as 別名]
def get_ports(self, ipaddr, ports):
        self.create_ports()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in ports:
            service = i.get('server')
            port = i.get('port')
            banner = i.get('banner')
            banner = re.sub('<', '', banner)
            banner = re.sub('>', '', banner)
            md5sum = hashlib.md5()
            strings = str(ipaddr) + str(service) + str(port)
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, ipaddr, service, port, banner, md5)
            query = "INSERT OR IGNORE INTO ports (time, ipaddr, service, port, banner,md5) VALUES (?,?,?,?,?,?)"
            self.insert_ports(query, values) 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:18,代碼來源:sqldb.py


注:本文中的hashlib.md5方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。