本文整理汇总了Python中Crypto.Hash.SHA1属性的典型用法代码示例。如果您正苦于以下问题:Python Hash.SHA1属性的具体用法?Python Hash.SHA1怎么用?Python Hash.SHA1使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类Crypto.Hash
的用法示例。
在下文中一共展示了Hash.SHA1属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def create(vek, keySizeBytes, certificatePath):
#print("VEK: " + str(binascii.hexlify(vek)))
publicKeyPem = open(certificatePath).read()
publicKey = RSA.importKey(publicKeyPem)
# Convert from PEM to DER
lines = publicKeyPem.replace(" ", '').split()
publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1]))
cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend())
subjectName = cert.subject.rfc4514_string()
serial = cert.serial_number
cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
wrapped_key = cipher.encrypt(vek)
#print("WrappedKey: " + str(binascii.hexlify(wrapped_key)))
return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key)
示例2: sha1
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def sha1(self):
"""Get SHA1 hash
The SHA (Secure Hash Algorithm) hash functions were designed by the NSA.
SHA-1 is the most established of the existing SHA hash functions and it is
used in a variety of security applications and protocols. However, SHA-1's
collision resistance has been weakening as new attacks are discovered or improved.
Returns:
Chepy: The Chepy object.
Examples:
>>> Chepy("A").sha1().output
"6dcd4ce23d88e2ee9568ba546c007c63d9131c1b"
"""
self.state = hashlib.sha1(self._convert_to_bytes()).hexdigest()
return self
示例3: testEncryptDecrypt2
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def testEncryptDecrypt2(self):
# Helper function to monitor what's requested from RNG
global asked
def localRng(N):
global asked
asked += N
return self.rng(N)
# Verify that OAEP is friendly to all hashes
for hashmod in (MD2,MD5,SHA1,SHA256,RIPEMD160):
# Verify that encrypt() asks for as many random bytes
# as the hash output size
asked = 0
pt = self.rng(40)
cipher = PKCS.new(self.key1024, hashmod, randfunc=localRng)
ct = cipher.encrypt(pt)
self.assertEqual(cipher.decrypt(ct), pt)
self.assertEqual(asked, hashmod.digest_size)
示例4: hash_token
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def hash_token(self):
try:
from Crypto.Hash import SHA1, HMAC
command = "{}".format(CMD_GET_KEY)
enc_command = await self.encrypt(command)
await self._ws.send(enc_command)
message = await self._ws.recv()
await self.parse_loxone_message(message)
message = await self._ws.recv()
resp_json = json.loads(message)
if 'LL' in resp_json:
if "value" in resp_json['LL']:
key = resp_json['LL']['value']
if key != "":
digester = HMAC.new(binascii.unhexlify(key),
self._token.token.encode("utf-8"), SHA1)
return digester.hexdigest()
return ERROR_VALUE
except:
return ERROR_VALUE
示例5: unwrap_key
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def unwrap_key(self, privateKey):
key = RSA.importKey(open(privateKey).read())
cipher = PKCS1_OAEP.new(key=key, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
vek = cipher.decrypt(self.wrappedKey)
#print("VEK: " + str(binascii.hexlify(vek)))
return vek
示例6: testPKIWrap
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def testPKIWrap(self):
vek = binascii.unhexlify("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")
publicKey = RSA.importKey(open(cert).read())
cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
ciphertext = cipher.encrypt(vek)
key = RSA.importKey(open(privateKey).read())
cipher = PKCS1_OAEP.new(key=key, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
vek2 = cipher.decrypt(ciphertext)
self.assertEquals(vek, vek2)
示例7: PBKDF1
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
"""Derive one key from a password (or passphrase).
This function performs key derivation according to an old version of
the PKCS#5 standard (v1.5) or `RFC2898
<https://www.ietf.org/rfc/rfc2898.txt>`_.
Args:
password (string):
The secret password to generate the key from.
salt (byte string):
An 8 byte string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation.
dkLen (integer):
The length of the desired key. The default is 16 bytes, suitable for
instance for :mod:`Crypto.Cipher.AES`.
count (integer):
The number of iterations to carry out. The recommendation is 1000 or
more.
hashAlgo (module):
The hash algorithm to use, as a module or an object from the :mod:`Crypto.Hash` package.
The digest length must be no shorter than ``dkLen``.
The default algorithm is :mod:`Crypto.Hash.SHA1`.
Return:
A byte string of length ``dkLen`` that can be used as key.
"""
if not hashAlgo:
hashAlgo = SHA1
password = tobytes(password)
pHash = hashAlgo.new(password+salt)
digest = pHash.digest_size
if dkLen > digest:
raise TypeError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
if len(salt) != 8:
raise ValueError("Salt is not 8 bytes long (%d bytes instead)." % len(salt))
for i in iter_range(count-1):
pHash = pHash.new(pHash.digest())
return pHash.digest()[:dkLen]
示例8: runTest
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def runTest(self):
key = b"\x04" * 20
one = HMAC.new(key, b"", SHA1).digest()
two = HMAC.new(key, None, SHA1).digest()
self.assertEqual(one, two)
示例9: test1
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def test1(self):
v = self._testData[0]
res = PBKDF1(v[0], t2b(v[1]), v[2], v[3], SHA1)
self.assertEqual(res, t2b(v[4]))
示例10: test2
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def test2(self):
# Verify that prf and hmac_hash_module are mutual exclusive
def prf_SHA1(p,s):
return HMAC.new(p,s,SHA1).digest()
self.assertRaises(ValueError, PBKDF2, b("xxx"), b("yyy"), 16, 100,
prf=prf_SHA1, hmac_hash_module=SHA1)
示例11: add_tests
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def add_tests(self, filename):
comps = "Crypto.SelfTest.Protocol.test_vectors.wycheproof".split(".")
with open(pycryptodome_filename(comps, filename), "rt") as file_in:
tv_tree = json.load(file_in)
algo_name = tv_tree['algorithm']
if algo_name == "HKDF-SHA-1":
hash_module = SHA1
elif algo_name == "HKDF-SHA-256":
hash_module = SHA256
elif algo_name == "HKDF-SHA-384":
hash_module = SHA384
elif algo_name == "HKDF-SHA-512":
hash_module = SHA512
else:
raise ValueError("Unknown algorithm " + algo_name)
for group in tv_tree['testGroups']:
from collections import namedtuple
TestVector = namedtuple('TestVector', 'id comment ikm salt info size okm hash_module valid warning filename')
for test in group['tests']:
tv = TestVector(
test['tcId'],
test['comment'],
unhexlify(test['ikm']),
unhexlify(test['salt']),
unhexlify(test['info']),
int(test['size']),
unhexlify(test['okm']),
hash_module,
test['result'] != "invalid",
test['result'] == "acceptable",
filename
)
self.tv.append(tv)
示例12: _refresh_token
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def _refresh_token(self):
from Crypto.Hash import SHA1, HMAC
command = "{}".format(CMD_GET_KEY)
enc_command = await self.encrypt(command)
await self._ws.send(enc_command)
message = await self._ws.recv()
resp_json = json.loads(message)
token_hash = None
if 'LL' in resp_json:
if "value" in resp_json['LL']:
key = resp_json['LL']['value']
if key == "":
digester = HMAC.new(binascii.unhexlify(key),
self._token.token.encode("utf-8"), SHA1)
token_hash = digester.hexdigest()
if token_hash is not None:
if self._version < 10.2:
command = "{}{}/{}".format(CMD_REFRESH_TOKEN, token_hash,
self._username)
else:
command = "{}{}/{}".format(CMD_REFRESH_TOKEN_JSON_WEB, token_hash,
self._username)
enc_command = await self.encrypt(command)
await self._ws.send(enc_command)
message = await self._ws.recv()
resp_json = json.loads(message)
_LOGGER.debug("Seconds before refresh: {}".format(
self._token.get_seconds_to_expire()))
if 'LL' in resp_json:
if "value" in resp_json['LL']:
if "validUntil" in resp_json['LL']['value']:
self._token.set_vaild_until(
resp_json['LL']['value']['validUntil'])
self.save_token()
示例13: send_secured
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def send_secured(self, device_uuid, value, code):
from Crypto.Hash import SHA1, HMAC
pwd_hash_str = code + ":" + self._visual_hash.salt
m = hashlib.sha1()
m.update(pwd_hash_str.encode('utf-8'))
pwd_hash = m.hexdigest().upper()
digester = HMAC.new(binascii.unhexlify(self._visual_hash.key),
pwd_hash.encode("utf-8"), SHA1)
command = "jdev/sps/ios/{}/{}/{}".format(digester.hexdigest(), device_uuid, value)
await self._ws.send(command)
示例14: hash_credentials
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def hash_credentials(self, key_salt):
try:
from Crypto.Hash import SHA1, HMAC
pwd_hash_str = self._pasword + ":" + key_salt.salt
m = hashlib.sha1()
m.update(pwd_hash_str.encode('utf-8'))
pwd_hash = m.hexdigest().upper()
pwd_hash = self._username + ":" + pwd_hash
digester = HMAC.new(binascii.unhexlify(key_salt.key),
pwd_hash.encode("utf-8"), SHA1)
_LOGGER.debug("hash_credentials successfully...")
return digester.hexdigest()
except ValueError:
_LOGGER.debug("error hash_credentials...")
return None
示例15: derive_pbkdf2_key
# 需要导入模块: from Crypto import Hash [as 别名]
# 或者: from Crypto.Hash import SHA1 [as 别名]
def derive_pbkdf2_key(
self,
password: Union[str, bytes],
salt: Union[str, bytes],
key_size: int = 256,
iterations: int = 1000,
hash_type: Literal["md5", "sha1", "sha256", "sh512"] = "sha1",
hex_salt: bool = True,
show_full_key: bool = False,
):
"""Derive a PBKDF2 key
Args:
password (Union[str, bytes]): Password
salt (Union[str, bytes]): Salt
key_size (int, optional): Key size. Defaults to 256.
iterations (int, optional): Number of iterations. Defaults to 1000.
hash_type (Literal[, optional): Hash type. Defaults to "sha1".
hex_salt (bool, optional): If salt is in hex format. Defaults to True.
show_full_key (bool, optional): Show AES256 64 bit key only. Defaults to False.
Raises:
TypeError: If hash type is not one of md5, sha1, sha256, sha512
Returns:
Chepy: The Chepy object.
Examples:
>>> Chepy(".").derive_pbkdf2_key("mR3m", "d9016d44c374f5fb62604683f4d61578").o[:10]
"7c8898f222"
"""
if isinstance(salt, str):
salt = salt.encode()
if hex_salt:
salt = binascii.unhexlify(salt)
if hash_type == "md5":
h = PBKDF2(password, salt, key_size, count=iterations, hmac_hash_module=MD5)
elif hash_type == "sha1":
h = PBKDF2(password, salt, key_size, count=iterations, hmac_hash_module=SHA1)
elif hash_type == "sha256":
h = PBKDF2(password, salt, key_size, count=iterations, hmac_hash_module=SHA256)
elif hash_type == "sha512":
h = PBKDF2(password, salt, key_size, count=iterations, hmac_hash_module=SHA512)
else: # pragma: no cover
raise TypeError(
"Currently supported digests are md5, sha1, sha256 and sha512"
)
if show_full_key:
self.state = h.hex()
else:
self.state = h.hex()[:64]
return self