本文整理汇总了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()
示例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
示例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
示例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
示例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},
)
示例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},
)
示例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!")
示例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))
示例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.
#:
示例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)
示例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)
示例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
示例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
示例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)
示例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)