本文整理汇总了Python中hashlib.new方法的典型用法代码示例。如果您正苦于以下问题:Python hashlib.new方法的具体用法?Python hashlib.new怎么用?Python hashlib.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hashlib
的用法示例。
在下文中一共展示了hashlib.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: modifyIfStmt
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def modifyIfStmt(self, node, *args, **kwargs):
''' Convert if-else if-else statements into just if-else statements by nesting them inside each other '''
# modify the if condition and the statements in the if-body
if_condition, stmts = node.condition_stmts_tuples[0]
if_condition, stmts = (self.modify(if_condition, *args, **kwargs),
flatten([self.modify(s, *args, **kwargs) for s in stmts]))
node.condition_stmts_tuples[0] = (if_condition, stmts)
# if if-else statement (i.e. no else-if part)
if len(node.condition_stmts_tuples) == 2 and node.condition_stmts_tuples[1][0] is None:
stmts = node.condition_stmts_tuples[1][1]
stmts = flatten([self.modify(s, *args, **kwargs) for s in stmts])
node.condition_stmts_tuples[1] = (None, stmts)
# else if there is any "else if" part
elif len(node.condition_stmts_tuples) > 1 and node.condition_stmts_tuples[1][0] is not None:
else_if_condition, else_if_stmts = node.condition_stmts_tuples[1]
# create a new if-statement consisting of the that 'else if' and all the following 'else if'/'else' clauses, and modify this recursively
new_if_stmt = self.modifyIfStmt(ksp_ast.IfStmt(node.condition_stmts_tuples[1][0].lexinfo, node.condition_stmts_tuples[1:]), *args, **kwargs)[0]
# the new contents of the else part will be the if-statement just created
node.condition_stmts_tuples = [node.condition_stmts_tuples[0],
(None, [new_if_stmt])]
return [node]
示例2: digest
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def digest(self, message_parts):
if self.key_id == 0:
assert self.algorithm == "null"
return b''
elif "hmac" in self.algorithm:
assert self.algorithm in ALGORITHMS
digestmod = ALGORITHM_TO_DIGESTMOD[self.algorithm]
the_hmac = hmac.new(self.secret.encode(), digestmod=digestmod)
for message_part in message_parts:
if message_part is not None:
the_hmac.update(message_part)
return the_hmac.digest()
else:
assert self.algorithm in ALGORITHMS
digestmod = ALGORITHM_TO_DIGESTMOD[self.algorithm]
the_hash = hashlib.new(name=digestmod)
the_hash.update(self.secret.encode())
for message_part in message_parts:
if message_part is not None:
the_hash.update(message_part)
return the_hash.digest()
示例3: get_file_hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def get_file_hash(algorithm, path):
'''
Calculates a file's hash.
.. WARNING::
The hashing algorithm must be supported on your system, as documented at `hashlib documentation page <http://docs.python.org/3/library/hashlib.html>`_.
:param algorithm: Hashing algorithm.
:type algorithm: string
:param path: The file path
:type path: string
:rtype: string
'''
hashAlg = hashlib.new(algorithm)
block_sz = 1*1024**2 # 1 MB
with open(path, 'rb') as f:
data = f.read(block_sz)
while data:
hashAlg.update(data)
data = f.read(block_sz)
return hashAlg.hexdigest()
示例4: seeded_range
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def seeded_range(seed, start, stop=None, step=1, extra=None):
"""
A filter to produce deterministic random numbers.
Produce a random item from range(start, stop[, step]), use the value and
optional ``extra`` value to set the seed for the random number generator.
Basic usage::
ansible_fqdn|seeded_range(60)
"hello"|seeded_range(1, 10, extra="world")
"""
hashed_seed = new_hash('sha1')
hashed_seed.update(seed)
if extra is not None:
hashed_seed.update(extra)
hashed_seed = hashed_seed.digest()
# We rely on randrange's interpretation of parameters
return Random(hashed_seed).randrange(start, stop, step)
示例5: generate_password
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def generate_password(input_seed):
"""
Generate some hard-to-guess but deterministic password.
(deterministic so we have some hope of password recovery if something gets lost)
Note: settings.SECRET_KEY is different (and actually secret) in production.
"""
# generate seed integer
secret = settings.SECRET_KEY
seed_str = '_'.join([secret, input_seed, PW_SERIES, secret])
h = hashlib.new('sha512')
h.update(seed_str.encode('utf8'))
seed = int(h.hexdigest(), 16)
# use seed to pick characters: one letter, one digit, one punctuation, length 6-10
letter, seed = _choose_from(LETTERS, seed)
digit, seed = _choose_from(DIGITS, seed)
punc, seed = _choose_from(PUNCTUATION, seed)
pw = letter + digit + punc
for i in range(7):
c, seed = _choose_from(ALL_CHARS, seed)
pw += c
return pw
示例6: check_against_chunks
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def check_against_chunks(self, chunks):
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
gots[hash_name] = hashlib.new(hash_name)
except (ValueError, TypeError):
raise InstallationError('Unknown hash name: %s' % hash_name)
for chunk in chunks:
for hash in itervalues(gots):
hash.update(chunk)
for hash_name, got in iteritems(gots):
if got.hexdigest() in self._allowed[hash_name]:
return
self._raise(gots)
示例7: computehasharchive
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def computehasharchive((filedir, checksums, version, filename)):
resolved_path = os.path.join(filedir, filename)
try:
os.stat(resolved_path)
except:
print >>sys.stderr, "Can't find %s" % filename
return None
if checksums.has_key(filename):
filehash = checksums[filename]
else:
scanfile = open(resolved_path, 'r')
h = hashlib.new('sha256')
h.update(scanfile.read())
scanfile.close()
filehash = h.hexdigest()
return (filename, version, filehash)
## per package:
## 1. unpack archive
## 2. scan all files and compute hashes
## 3. lookup what is available in the database from the same package and origin
## 4. copy unique and unscanned files to new archive dir
## 5. create text file with metadata
## 6. pack archive
## 7. pack archive + metadata into BAT archive
示例8: computehash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def computehash((filedir, filename, extrahashes, sha256sum)):
resolved_path = os.path.join(filedir, filename)
filehashes = {}
filehashes['sha256'] = sha256sum
scanfile = open(resolved_path, 'r')
data = scanfile.read()
scanfile.close()
for i in extrahashes:
if i == 'crc32':
filehashes[i] = zlib.crc32(data) & 0xffffffff
elif i == 'tlsh':
if os.stat(resolved_path).st_size >= 256:
tlshhash = tlsh.hash(data)
filehashes[i] = tlshhash
else:
filehashes[i] = None
else:
h = hashlib.new(i)
h.update(data)
filehashes[i] = h.hexdigest()
filehashes['sha256'] = sha256sum
return (filedir, filename, filehashes)
示例9: checkalreadyscanned
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def checkalreadyscanned((filedir, filename, checksum)):
resolved_path = os.path.join(filedir, filename)
try:
os.stat(resolved_path)
except:
print >>sys.stderr, "Can't find %s" % filename
return None
if checksum != None:
filehash = checksum
else:
scanfile = open(resolved_path, 'r')
h = hashlib.new('sha256')
h.update(scanfile.read())
scanfile.close()
filehash = h.hexdigest()
return (filename, filehash)
示例10: getHBootKey
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def getHBootKey(self):
LOG.debug('Calculating HashedBootKey from SAM')
QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0"
DIGITS = "0123456789012345678901234567890123456789\0"
F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1]
domainData = DOMAIN_ACCOUNT_F(F)
rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS)
rc4 = ARC4.new(rc4Key)
self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum'])
# Verify key with checksum
checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)
if checkSum != self.__hashedBootKey[16:]:
raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(')
示例11: copy
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def copy(self, new_command=None, add_location=None):
""" returns a copy of the line.
If the new_command parameter is specified that will be the command of the new line
and it will get the same indentation as the old line. """
line = Line(self.command, self.locations, self.namespaces)
if add_location:
line.locations = line.locations + [add_location]
if new_command:
line.command = new_command
return line
示例12: modifyVarRef
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def modifyVarRef(self, node, *args, **kwargs):
if node.identifier.identifier_first_part in self.name_subst_dict:
new_expr = self.name_subst_dict[node.identifier.identifier_first_part]
if isinstance(new_expr, ksp_ast.VarRef):
if self.subscript_addition:
# figure out which subscript to use or add if there are two
if not new_expr.subscripts and not node.subscripts:
subscripts = []
elif len(new_expr.subscripts) == 1 and not node.subscripts:
subscripts = [self.modify(s, *args, **kwargs) for s in new_expr.subscripts]
elif not new_expr.subscripts and len(node.subscript) == 1:
subscripts = [self.modify(s, *args, **kwargs) for s in node.subscripts]
elif len(new_expr.subscripts) == 1 and len(node.subscripts) == 1:
subscripts = [ksp_ast.BinOp(node.lexinfo, new_expr.subscripts[0], '+', node.subscripts[0])]
#else:
# raise ksp_ast.ParseException(node, 'Double subscript not allowed: %s' % unicode(node))
else:
subscripts = [self.modify(s, *args, **kwargs) for s in node.subscripts] + new_expr.subscripts
# build a new VarRef where the first part of the identifier has been replaced by the new_expr name.
return ksp_ast.VarRef(new_expr.lexinfo,
ksp_ast.ID(new_expr.identifier.lexinfo, new_expr.identifier.prefix + new_expr.identifier.identifier + node.identifier.identifier_last_part),
subscripts=subscripts)
else:
return new_expr
else:
return ASTModifierBase.modifyVarRef(self, node, *args, **kwargs)
示例13: modifyFunctionCall
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def modifyFunctionCall(self, node, *args, **kwargs):
''' Check if the function name in a function call is a parameter and substitute its name if that's the case '''
func_call = node
if node.function_name.identifier_first_part in self.name_subst_dict:
# fetch the replacement expression and ensure that it's a variable reference
new_expr = self.name_subst_dict[node.function_name.identifier_first_part]
if not isinstance(new_expr, ksp_ast.VarRef):
raise ksp_ast.ParseException(node, 'Expected a function name parameter')
# create a new FunctionCall object with the substituted function name
function_name = ksp_ast.ID(new_expr.identifier.lexinfo, new_expr.identifier.identifier + node.function_name.identifier_last_part)
func_call = ksp_ast.FunctionCall(new_expr.lexinfo, function_name, node.parameters, node.is_procedure, node.using_call_keyword)
return ASTModifierBase.modifyFunctionCall(self, func_call, *args, **kwargs)
示例14: compute_hash
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def compute_hash(filename, algorithm='md5', chunk_size=io.DEFAULT_BUFFER_SIZE):
""" Compute the hash of a large file using hashlib """
h = hashlib.new(algorithm)
with io.open(filename, mode='rb') as fh:
for chunk in iter(lambda: fh.read(chunk_size), b''):
h.update(chunk)
return h.hexdigest()
示例15: ecdsa_exploit_reused_nonce
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import new [as 别名]
def ecdsa_exploit_reused_nonce(self, msg1, sig1, msg2, sig2):
"""Given two different messages msg1 and msg2 and their corresponding
signatures sig1, sig2, try to calculate the private key that was used
for signing if during signature generation no unique nonces were
used."""
assert(isinstance(msg1, bytes))
assert(isinstance(msg2, bytes))
assert(msg1 != msg2)
assert(sig1.r == sig2.r)
# Hash the messages
dig1 = hashlib.new(sig1.hashalg)
dig1.update(msg1)
dig1 = dig1.digest()
dig2 = hashlib.new(sig2.hashalg)
dig2.update(msg2)
dig2 = dig2.digest()
# Calculate hashes of messages
e1 = Tools.ecdsa_msgdigest_to_int(dig1, self.point.curve.n)
e2 = Tools.ecdsa_msgdigest_to_int(dig2, self.point.curve.n)
# Take them modulo n
e1 = FieldElement(e1, self.point.curve.n)
e2 = FieldElement(e2, self.point.curve.n)
(s1, s2) = (FieldElement(sig1.s, self.point.curve.n), FieldElement(sig2.s, self.point.curve.n))
r = sig1.r
# Recover (supposedly) random nonce
nonce = (e1 - e2) // (s1 - s2)
# Recover private key
priv = ((nonce * s1) - e1) // r
return { "nonce": nonce, "privatekey": priv }