本文整理匯總了Python中hashlib.sha1方法的典型用法代碼示例。如果您正苦於以下問題:Python hashlib.sha1方法的具體用法?Python hashlib.sha1怎麽用?Python hashlib.sha1使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類hashlib
的用法示例。
在下文中一共展示了hashlib.sha1方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check_wxa_signature
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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()
示例2: check_sha1
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例3: GetFileChecksum
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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]
示例4: _got_rakp3
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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)
示例5: get_hash
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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()
示例6: generate_history
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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()
示例7: getSHA1
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例8: EncryptMsg
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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)
示例9: DecryptMsg
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例10: _cert_details
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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)
示例11: app_sign
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例12: generate_key_data_from_nonce
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例13: key
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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
示例14: check_sha1
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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]
示例15: get_md5_hash
# 需要導入模塊: import hashlib [as 別名]
# 或者: from hashlib import sha1 [as 別名]
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