我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cryptography.hazmat.primitives.hashes.SHA1。
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
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
def create_decryptor(private_location, public_location): try: with open(private_location, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend() ) except FileNotFoundError: with open(private_location, "wb") as key_file: private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) key_file.write(private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() )) with open(public_location, "wb") as public_file: public_key = private_key.public_key() pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) public_file.write(pem) def decrypt(ciphertext): return private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) return decrypt
def show_Certificate(cert, short=False): """ Print Fingerprints, Issuer and Subject of an X509 Certificate. :param cert: X509 Certificate to print :param short: Print in shortform for DN (Default: False) :type cert: :class:`cryptography.x509.Certificate` :type short: Boolean """ for h in [hashes.MD5, hashes.SHA1, hashes.SHA256, hashes.SHA512]: print("{}: {}".format(h.name, binascii.hexlify(cert.fingerprint(h())).decode("ascii"))) print("Issuer: {}".format(get_Name(cert.issuer, short=short))) print("Subject: {}".format(get_Name(cert.subject, short=short))) ################################## AXML FORMAT ######################################## # Translated from # http://code.google.com/p/android4me/source/browse/src/android/content/res/AXmlResourceParser.java
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
def __init__(self, pem_private_key, private_key_password=None): """ RSA Certificate Authority used to sign certificates. :param pem_private_key: PEM formatted RSA Private Key. It should be encrypted with a password, but that is not required. :param private_key_password: Password to decrypt the PEM RSA Private Key, if it is encrypted. Which it should be. """ super(SSHCertificateAuthority, self).__init__() self.public_key_type = SSHPublicKeyType.RSA self.private_key = load_pem_private_key(pem_private_key, private_key_password, default_backend()) self.signer = self.private_key.signer(padding.PKCS1v15(), hashes.SHA1()) ca_pub_numbers = self.private_key.public_key().public_numbers() self.e = ca_pub_numbers.e self.n = ca_pub_numbers.n
def _enc_dec_rsa(backend, key, data, padding): if not isinstance(padding, AsymmetricPadding): raise TypeError("Padding must be an instance of AsymmetricPadding.") if isinstance(padding, PKCS1v15): padding_enum = backend._lib.RSA_PKCS1_PADDING elif isinstance(padding, OAEP): padding_enum = backend._lib.RSA_PKCS1_OAEP_PADDING if not isinstance(padding._mgf, MGF1): raise UnsupportedAlgorithm( "Only MGF1 is supported by this backend.", _Reasons.UNSUPPORTED_MGF ) if not isinstance(padding._mgf._algorithm, hashes.SHA1): raise UnsupportedAlgorithm( "This backend supports only SHA1 inside MGF1 when " "using OAEP.", _Reasons.UNSUPPORTED_HASH ) if padding._label is not None and padding._label != b"": raise ValueError("This backend does not support OAEP labels.") if not isinstance(padding._algorithm, hashes.SHA1): raise UnsupportedAlgorithm( "This backend only supports SHA1 when using OAEP.", _Reasons.UNSUPPORTED_HASH ) else: raise UnsupportedAlgorithm( "{0} is not supported by this backend.".format( padding.name ), _Reasons.UNSUPPORTED_PADDING ) if backend._lib.Cryptography_HAS_PKEY_CTX: return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum) else: return _enc_dec_rsa_098(backend, key, data, padding_enum)
def pbkdf2_hmac_supported(self, algorithm): if self._lib.Cryptography_HAS_PBKDF2_HMAC: return self.hmac_supported(algorithm) else: # OpenSSL < 1.0.0 has an explicit PBKDF2-HMAC-SHA1 function, # so if the PBKDF2_HMAC function is missing we only support # SHA1 via PBKDF2_HMAC_SHA1. return isinstance(algorithm, hashes.SHA1)
def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, key_material): buf = self._ffi.new("char[]", length) if self._lib.Cryptography_HAS_PBKDF2_HMAC: evp_md = self._lib.EVP_get_digestbyname( algorithm.name.encode("ascii")) self.openssl_assert(evp_md != self._ffi.NULL) res = self._lib.PKCS5_PBKDF2_HMAC( key_material, len(key_material), salt, len(salt), iterations, evp_md, length, buf ) self.openssl_assert(res == 1) else: if not isinstance(algorithm, hashes.SHA1): raise UnsupportedAlgorithm( "This version of OpenSSL only supports PBKDF2HMAC with " "SHA1.", _Reasons.UNSUPPORTED_HASH ) res = self._lib.PKCS5_PBKDF2_HMAC_SHA1( key_material, len(key_material), salt, len(salt), iterations, length, buf ) self.openssl_assert(res == 1) return self._ffi.buffer(buf)[:]
def rsa_padding_supported(self, padding): if isinstance(padding, PKCS1v15): return True elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): return self._mgf1_hash_supported(padding._mgf._algorithm) elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): return isinstance(padding._mgf._algorithm, hashes.SHA1) else: return False
def dsa_hash_supported(self, algorithm): if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f: return isinstance(algorithm, hashes.SHA1) else: return self.hash_supported(algorithm)
def _mgf1_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_MGF1_MD: return self.hash_supported(algorithm) else: return isinstance(algorithm, hashes.SHA1)
def encrypt_rsa(text, key): private_key = load_key(key) public_key = private_key.public_key() return public_key.encrypt( text, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) )
def decrypt_rsa(text, key): private_key = load_key(key) return private_key.decrypt( text, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) )
def sign(self, message): canonicalization = NoFWSCanonicalization() signer = self._key.signer(padding.PKCS1v15(), hashes.SHA1()) headers, body = _rfc822_parse(message) h_field = [] for header, value in headers: if self._signed_headers is None or header in self._signed_headers: h_field.append(header) header, value = canonicalization.canonicalize_header( header, value) signer.update(header) signer.update(b":") signer.update(value) body = canonicalization.canonicalize_body(body) if body: signer.update(b"\r\n") signer.update(body) return _fold( b"DomainKey-Signature: a=rsa-sha1; c=nofws; d={domain}; " b"s={selector}; q=dns; h={headers}; b={signature}".format( domain=self._domain, selector=self._selector, headers=b": ".join(h_field), signature=base64.b64encode(signer.finalize()) )) + b"\r\n"
def __init__(self, key_pair): self.key_pair = key_pair self._padding = asym_padding.OAEP( mgf=asym_padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None )
def hash_create(algorithm=hashes.SHA1()): ''' Create and return a new hash context for algorithm. Tor cells use SHA1 as a hash algorithm, except for v3 onion services, which use SHA3-256 for client to service cells. ''' # cryptography doesn't have a SHA3 implementation (as of July 2017) return hashes.Hash(algorithm, backend=backends.default_backend())
def hash_bytes(data_bytes, output_len=None, algorithm=hashes.SHA1()): ''' Extract and return output_len bytes from a hash of data_bytes. If output_len is None, return the full hash length. ''' hash_context = hash_create(algorithm=algorithm) hash_context = hash_update(hash_context, data_bytes) return hash_extract(hash_context, output_len=output_len, make_context_reusable=False) # Tor-specific hash functions
def _oaep_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_RSA_OAEP_MD: return isinstance( algorithm, ( hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512, ) ) else: return isinstance(algorithm, hashes.SHA1)
def _pss_mgf1_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_MGF1_MD: return self.hash_supported(algorithm) else: return isinstance(algorithm, hashes.SHA1)