本文整理匯總了Python中cryptography.hazmat.primitives.hashes.SHA1屬性的典型用法代碼示例。如果您正苦於以下問題:Python hashes.SHA1屬性的具體用法?Python hashes.SHA1怎麽用?Python hashes.SHA1使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類cryptography.hazmat.primitives.hashes
的用法示例。
在下文中一共展示了hashes.SHA1屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: rsa_encrypt
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def rsa_encrypt(data, pem, b64_encode=True):
"""
rsa 加密
:param data: 待加密字符串/binary
:param pem: RSA public key 內容/binary
:param b64_encode: 是否對輸出進行 base64 encode
:return: 如果 b64_encode=True 的話,返回加密並 base64 處理後的 string;否則返回加密後的 binary
"""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
encoded_data = to_binary(data)
pem = to_binary(pem)
public_key = serialization.load_pem_public_key(pem, backend=default_backend())
encrypted_data = public_key.encrypt(
encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
)
if b64_encode:
encrypted_data = base64.b64encode(encrypted_data).decode("utf-8")
return encrypted_data
示例2: rsa_decrypt
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def rsa_decrypt(encrypted_data, pem, password=None):
"""
rsa 解密
:param encrypted_data: 待解密 bytes
:param pem: RSA private key 內容/binary
:param password: RSA private key pass phrase
:return: 解密後的 binary
"""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
encrypted_data = to_binary(encrypted_data)
pem = to_binary(pem)
private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
data = private_key.decrypt(
encrypted_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
)
return data
示例3: test_create_key_pair_encryption
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def test_create_key_pair_encryption(self):
private_key_uuid, public_key_uuid = self.key_mgr.create_key_pair(
self.context, 'RSA', 2048)
private_key = self.key_mgr.get(self.context, private_key_uuid)
public_key = self.key_mgr.get(self.context, public_key_uuid)
crypto_private_key = get_cryptography_private_key(private_key)
crypto_public_key = get_cryptography_public_key(public_key)
message = b'secret plaintext'
ciphertext = crypto_public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None))
plaintext = crypto_private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None))
self.assertEqual(message, plaintext)
示例4: _append_router_signature
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def _append_router_signature(content: bytes, private_key: 'cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey') -> bytes: # type: ignore
"""
Appends a router signature to a server or extrainfo descriptor.
:param content: descriptor content up through 'router-signature\\n'
:param private_key: private relay signing key
:returns: **bytes** with the signed descriptor content
"""
try:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
except ImportError:
raise ImportError('Signing requires the cryptography module')
signature = base64.b64encode(private_key.sign(content, padding.PKCS1v15(), hashes.SHA1()))
return content + b'\n'.join([b'-----BEGIN SIGNATURE-----'] + stem.util.str_tools._split_by_length(signature, 64) + [b'-----END SIGNATURE-----\n'])
示例5: rsa_signer
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def rsa_signer(message):
"""Sign a message with an rsa key pair found on the file system for CloudFront signed urls.
Parameters
----------
message : Type[string]
the message for which we want to compute a signature
Returns
-------
string
The rsa signature
"""
try:
with open(settings.CLOUDFRONT_PRIVATE_KEY_PATH, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), password=None, backend=default_backend()
)
except FileNotFoundError:
raise MissingRSAKey()
# The following line is excluded from bandit security check because cloudfront supports
# only sha1 hash for signed URLs.
return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1()) # nosec
示例6: __init__
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def __init__(self, key, length, algorithm, backend):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
"Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if len(key) < 16:
raise ValueError("Key length has to be at least 128 bits.")
if not isinstance(length, six.integer_types):
raise TypeError("Length parameter must be an integer type.")
if length < 6 or length > 8:
raise ValueError("Length of HOTP has to be between 6 to 8.")
if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")
self._key = key
self._length = length
self._algorithm = algorithm
self._backend = backend
示例7: __init__
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def __init__(self, key, length, algorithm, backend,
enforce_key_length=True):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
"Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if len(key) < 16 and enforce_key_length is True:
raise ValueError("Key length has to be at least 128 bits.")
if not isinstance(length, six.integer_types):
raise TypeError("Length parameter must be an integer type.")
if length < 6 or length > 8:
raise ValueError("Length of HOTP has to be between 6 to 8.")
if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")
self._key = key
self._length = length
self._algorithm = algorithm
self._backend = backend
示例8: sha2_rsa_encrypt
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def sha2_rsa_encrypt(password, salt, public_key):
"""Encrypt password with salt and public_key.
Used for sha256_password and caching_sha2_password.
"""
if not _have_cryptography:
raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
message = _xor_password(password + b'\0', salt)
rsa_key = serialization.load_pem_public_key(public_key, default_backend())
return rsa_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None,
),
)
示例9: _legacy_pkcs1_v1_5_encode_md5_sha1
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def _legacy_pkcs1_v1_5_encode_md5_sha1(M, emLen):
"""
Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash.
"""
M = bytes_encode(M)
md5_hash = hashes.Hash(_get_hash("md5"), backend=default_backend())
md5_hash.update(M)
sha1_hash = hashes.Hash(_get_hash("sha1"), backend=default_backend())
sha1_hash.update(M)
H = md5_hash.finalize() + sha1_hash.finalize()
if emLen < 36 + 11:
warning("pkcs_emsa_pkcs1_v1_5_encode: "
"intended encoded message length too short")
return None
PS = b'\xff' * (emLen - 36 - 3)
return b'\x00' + b'\x01' + PS + b'\x00' + H
#####################################################################
# Hash and padding helpers
#####################################################################
示例10: _cryptography_hash_function
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def _cryptography_hash_function(algorithm: DigestAlgorithm) -> Union[None, Type[hashes.SHA1], Type[hashes.SHA256], Type[hashes.SHA512]]:
"""Find the cryptography hash function given the string output from asn1crypto SignedDigestAlgorithm.
Todo: There should be a better way to do this?
Args:
algorithm (DigestAlgorithm): The asn1crypto Signed Digest Algorithm
Returns:
Union[Type[hashes.SHA1], Type[hashes.SHA256], Type[hashes.SHA512]] A cryptography hash function for use with
signature verification.
"""
hash_algo = algorithm['algorithm'].native
if hash_algo == "sha1":
return hashes.SHA1
elif hash_algo == "sha256":
return hashes.SHA256
elif hash_algo == "sha512":
return hashes.SHA512
else:
return None
示例11: encryptClientPrivKey
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def encryptClientPrivKey(priv_key):
"""Encrypt the Clients private key (given as a str) with the servers public key"""
with open(_helper.path('res/server.public.key'), "rb") as key_file:
public_key = serialization.load_ssh_public_key(
key_file.read(),
backend=default_backend()
)
key_file.close()
cipher = public_key.encrypt(
bytes(priv_key, 'utf-8'),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA1(),
label=None
)
)
_helper.info("Private Client Key is encrypted")
return cipher
示例12: decryptCPriv
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def decryptCPriv(server_priv, client_private_enc_key_filename):
"Decrypts the clients private key with the servers private key"
with open(client_private_enc_key_filename, 'rb') as x:
to_encrypt = x.read()
x.close()
to_encrypt = to_encrypt.decode('utf-8')
to_encrypt = base64.b64decode(to_encrypt)
to_encrypt = bytes(to_encrypt)
clear_key = server_priv.decrypt(
to_encrypt,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA1(),
label=None
)
)
return clear_key
示例13: verify_ssh_sig
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def verify_ssh_sig(self, data, msg):
if msg.get_text() != 'ssh-rsa':
return False
key = self.key
if isinstance(key, rsa.RSAPrivateKey):
key = key.public_key()
verifier = key.verifier(
signature=msg.get_binary(),
padding=padding.PKCS1v15(),
algorithm=hashes.SHA1(),
)
verifier.update(data)
try:
verifier.verify()
except InvalidSignature:
return False
else:
return True
示例14: _use_cryptography_signer
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def _use_cryptography_signer():
# https://cryptography.io as an RSA backend
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import (
load_pem_private_key
)
def _cloud_front_signer_from_pem(key_id, pem):
key = load_pem_private_key(
pem, password=None, backend=default_backend())
return CloudFrontSigner(
key_id, lambda x: key.sign(x, padding.PKCS1v15(), hashes.SHA1()))
return _cloud_front_signer_from_pem
示例15: _scan_a_cert
# 需要導入模塊: from cryptography.hazmat.primitives import hashes [as 別名]
# 或者: from cryptography.hazmat.primitives.hashes import SHA1 [as 別名]
def _scan_a_cert(id, cert_path, key_path, assigns, is_acme=False):
with open(cert_path, "rb") as f:
crt = x509.load_pem_x509_certificate(f.read(), default_backend())
with open(key_path, "rb") as f:
key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend()
)
sha1 = binascii.hexlify(crt.fingerprint(hashes.SHA1())).decode()
md5 = binascii.hexlify(crt.fingerprint(hashes.MD5())).decode()
sha1 = ":".join([sha1[i:i+2].upper() for i in range(0, len(sha1), 2)])
md5 = ":".join([md5[i:i+2].upper() for i in range(0, len(md5), 2)])
kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA"
common_name = crt.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
return Certificate(
id=id, cert_path=cert_path, key_path=key_path, keytype=kt,
keylength=key.key_size, domain=common_name[0].value,
assigns=assigns.get(id, []), expiry=crt.not_valid_after, sha1=sha1,
md5=md5, is_acme=is_acme)