Python cryptography.hazmat.primitives.hashes.SHA256 Examples
The following are 30
code examples of cryptography.hazmat.primitives.hashes.SHA256().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.hashes
, or try the search function
.
Example #1
Source File: app_utils.py From dash-masternode-tool with MIT License | 7 votes |
def decrypt(input_str, key, iterations=100000): try: input_str = binascii.unhexlify(input_str) salt = b'D9\x82\xbfSibW(\xb1q\xeb\xd1\x84\x118' kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=iterations, backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(key.encode('utf-8'))) fer = Fernet(key) h = fer.decrypt(input_str) h = h.decode('utf-8') except: raise return h
Example #2
Source File: attestation.py From pywarp with Apache License 2.0 | 6 votes |
def validate(self, authenticator_data, rp_id_hash, client_data_hash): # See https://www.w3.org/TR/webauthn/#fido-u2f-attestation, "Verification procedure" credential = authenticator_data.credential public_key_u2f = b'\x04' + credential.public_key.x + credential.public_key.y verification_data = b'\x00' + rp_id_hash + client_data_hash + credential.id + public_key_u2f assert len(credential.public_key.x) == 32 assert len(credential.public_key.y) == 32 self.cert_public_key.verify(self.signature, verification_data, ec.ECDSA(hashes.SHA256())) key_id = x509.SubjectKeyIdentifier.from_public_key(self.cert_public_key).digest.hex() att_root_cert_chain = self.metadata_for_key_id(key_id)["attestationRootCertificates"] # TODO: implement full cert chain validation # See https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.tbs_certificate_bytes # See https://github.com/pyca/cryptography/issues/2381 # See https://github.com/wbond/certvalidator assert len(att_root_cert_chain) == 1 att_root_cert = x509.load_der_x509_certificate(att_root_cert_chain[0].encode(), cryptography.hazmat.backends.default_backend()) att_root_cert.public_key().verify(self.att_cert.signature, self.att_cert.tbs_certificate_bytes, padding.PKCS1v15(), self.att_cert.signature_hash_algorithm) return self.validated_attestation(type="Basic", trust_path="x5c", credential=credential)
Example #3
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def decrypt(message, receiver_private_key): point = message[0:65] tag = message[65:81] ciphertext = message[81:] sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point) sender_public_key = sender_public_numbers.public_key(backend) shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key) iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) decryptor = Cipher( algorithms.AES(key), modes.GCM(iv,tag), backend = backend ).decryptor() message = decryptor.update(ciphertext) + decryptor.finalize() return message
Example #4
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
def _encrypt_from_parts(self, data, current_time, iv): utils._check_bytes("data", data) padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
Example #5
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def encrypt(message, receiver_public_key): sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend) shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key) sender_public_key = sender_private_key.public_key() point = sender_public_key.public_numbers().encode_point() iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend = backend ).encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() return point + encryptor.tag + ciphertext
Example #6
Source File: hotp.py From teleport with Apache License 2.0 | 6 votes |
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
Example #7
Source File: hotp.py From teleport with Apache License 2.0 | 6 votes |
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
Example #8
Source File: EncryptedPfx.py From ADFSpoof with Apache License 2.0 | 6 votes |
def _derive_keys(self, password=None): label = encode(self.encryption_oid) + encode(self.mac_oid) context = self.nonce.asOctets() backend = default_backend() kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=48, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, fixed=None, backend=backend ) key = kdf.derive(password) if self.DEBUG: sys.stderr.write("Derived key: {0}\n".format(key)) self.encryption_key = key[0:16] self.mac_key = key[16:]
Example #9
Source File: crypt.py From pgrepup with GNU General Public License v3.0 | 6 votes |
def _get_key(): if this.key: return this.key secret = getpass.getpass() try: salt = config().get('Security', 'salt') except NoOptionError: salt = base64.urlsafe_b64encode(os.urandom(16)) config().set('Security', 'salt', salt) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend() ) this.key = base64.urlsafe_b64encode(kdf.derive(secret)) return this.key
Example #10
Source File: cert_manager.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 6 votes |
def issue_certificate(self, ca_pem_key, ca_pem_cert, csr_pem): ca_cert = self.load_pem(entity_type="certificate", pem_text=ca_pem_cert) ca_key = self.load_pem(entity_type="key", pem_text=ca_pem_key) csr = self.load_pem(entity_type="csr", pem_text=csr_pem) builder = x509.CertificateBuilder( issuer_name=ca_cert.issuer, subject_name=csr.subject, public_key=csr.public_key(), not_valid_before=self.not_valid_before_date, not_valid_after=self.not_valid_after_date, extensions=csr.extensions, serial_number=self.serial_num, ) certificate = builder.sign( private_key=ca_key, algorithm=hashes.SHA256(), backend=default_backend(), ) self.pem_certificate = certificate.public_bytes( encoding=serialization.Encoding.PEM ) return certificate
Example #11
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
def _encrypt_from_parts(self, data, current_time, iv): utils._check_bytes("data", data) padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
Example #12
Source File: hotp.py From teleport with Apache License 2.0 | 6 votes |
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
Example #13
Source File: fernet.py From teleport with Apache License 2.0 | 6 votes |
def _encrypt_from_parts(self, data, current_time, iv): if not isinstance(data, bytes): raise TypeError("data must be bytes.") padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
Example #14
Source File: hotp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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
Example #15
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 6 votes |
def _get_key(self, alg, key, p2s, p2c): if isinstance(key, bytes): plain = key else: plain = key.encode('utf8') salt = bytes(self.name.encode('utf8')) + b'\x00' + p2s if self.hashsize == 256: hashalg = hashes.SHA256() elif self.hashsize == 384: hashalg = hashes.SHA384() elif self.hashsize == 512: hashalg = hashes.SHA512() else: raise ValueError('Unknown Hash Size') kdf = PBKDF2HMAC(algorithm=hashalg, length=_inbytes(self.keysize), salt=salt, iterations=p2c, backend=self.backend) rk = kdf.derive(plain) if _bitsize(rk) != self.keysize: raise InvalidJWEKeyLength(self.keysize, len(rk)) return JWK(kty="oct", use="enc", k=base64url_encode(rk))
Example #16
Source File: fernet.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _encrypt_from_parts(self, data, current_time, iv): if not isinstance(data, bytes): raise TypeError("data must be bytes.") padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
Example #17
Source File: app_utils.py From dash-masternode-tool with MIT License | 6 votes |
def encrypt(input_str, key, iterations=100000): """Basic encryption with a predefined key. Its purpose is to protect not very important data, just to avoid saving them as plaintext.""" salt = b'D9\x82\xbfSibW(\xb1q\xeb\xd1\x84\x118' kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=iterations, backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(key.encode('utf-8'))) fer = Fernet(key) h = fer.encrypt(input_str.encode('utf-8')) h = h.hex() return h
Example #18
Source File: ecies.py From pyquarkchain with MIT License | 6 votes |
def kdf(key_material: bytes) -> bytes: """NIST SP 800-56a Concatenation Key Derivation Function (see section 5.8.1). Pretty much copied from geth's implementation: https://github.com/ethereum/go-ethereum/blob/673007d7aed1d2678ea3277eceb7b55dc29cf092/crypto/ecies/ecies.go#L167 """ key = b"" hash_blocksize = hashes.SHA256().block_size reps = ((KEY_LEN + 7) * 8) / (hash_blocksize * 8) counter = 0 while counter <= reps: counter += 1 ctx = sha256() ctx.update(struct.pack(">I", counter)) ctx.update(key_material) key += ctx.digest() return key[:KEY_LEN]
Example #19
Source File: hotp.py From oss-ftp with MIT License | 6 votes |
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
Example #20
Source File: fernet.py From oss-ftp with MIT License | 6 votes |
def _encrypt_from_parts(self, data, current_time, iv): if not isinstance(data, bytes): raise TypeError("data must be bytes.") padder = padding.PKCS7(algorithms.AES.block_size).padder() padded_data = padder.update(data) + padder.finalize() encryptor = Cipher( algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend ).encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() basic_parts = ( b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext ) h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(basic_parts) hmac = h.finalize() return base64.urlsafe_b64encode(basic_parts + hmac)
Example #21
Source File: signature_handler.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 6 votes |
def generate_signature(self, pri_key: str, msg: bytes) -> str: if self.__scheme == SignatureScheme.SHA224withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP224R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA224()) ) elif self.__scheme == SignatureScheme.SHA256withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP256R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA256()) ) elif self.__scheme == SignatureScheme.SHA384withECDSA: private_key = ec.derive_private_key(int(pri_key, 16), ec.SECP384R1(), default_backend()) signature = private_key.sign( msg, ec.ECDSA(hashes.SHA384()) ) else: raise SDKException(ErrorCode.other_error('Invalid signature scheme.')) sign = SignatureHandler.dsa_der_to_plain(signature) return sign
Example #22
Source File: crypto.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def sign(self, s): """ Create a signature of the string s :param s: String to sign :type s: str :return: The hexlified and versioned signature of the string :rtype: str """ if not self.private: log.info('Could not sign message {0!s}, no private key!'.format(s)) # TODO: should we throw an exception in this case? return '' signature = self.private.sign( to_bytes(s), asym_padding.PSS( mgf=asym_padding.MGF1(hashes.SHA256()), salt_length=asym_padding.PSS.MAX_LENGTH), hashes.SHA256()) res = ':'.join([self.sig_ver, hexlify_and_unicode(signature)]) return res
Example #23
Source File: webauthn.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def _verify_signature(public_key, alg, data, signature): if alg == COSE_ALGORITHM.ES256: public_key.verify(signature, data, ECDSA(SHA256())) elif alg == COSE_ALGORITHM.RS256: public_key.verify(signature, data, PKCS1v15(), SHA256()) elif alg == COSE_ALGORITHM.PS256: padding = PSS(mgf=MGF1(SHA256()), salt_length=PSS.MAX_LENGTH) public_key.verify(signature, data, padding, SHA256()) else: raise NotImplementedError()
Example #24
Source File: test_f_aws_encryption_sdk_client.py From aws-encryption-sdk-python with Apache License 2.0 | 5 votes |
def _mgf1_sha256_supported(): wk = serialization.load_pem_private_key( data=VALUES["raw"][b"asym1"][EncryptionKeyType.PRIVATE], password=None, backend=default_backend() ) try: wk.public_key().encrypt( plaintext=b"aosdjfoiajfoiaj;foijae;rogijaerg", padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None), ) except cryptography.exceptions.UnsupportedAlgorithm: return False return True
Example #25
Source File: webauthn.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def _get_client_data_hash(decoded_client_data): """ Compute the SHA256 hash of the client data. :param decoded_client_data: The client data to hash. :type decoded_client_data: bytes :return: The hash of the client data. :rtype: bytes """ if not isinstance(decoded_client_data, six.binary_type): return '' return hashlib.sha256(decoded_client_data).digest()
Example #26
Source File: backend.py From teleport with Apache License 2.0 | 5 votes |
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)
Example #27
Source File: encrypt.py From maple-blog with GNU General Public License v3.0 | 5 votes |
def password(self, raw_password, salt): kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) return urlsafe_b64encode(kdf.derive(raw_password.encode("utf-8")))
Example #28
Source File: crypt.py From jet-bridge with MIT License | 5 votes |
def decrypt(message_encrypted, secret_key): message_salt = message_encrypted[-24:] message_payload = message_encrypted[:-24] salt = base64.b64decode(message_salt) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=backend ) key = base64.urlsafe_b64encode(kdf.derive(bytes(secret_key, encoding='utf8'))) f = Fernet(key) return f.decrypt(bytes(message_payload, encoding='latin1')).decode('utf8')
Example #29
Source File: util.py From securesystemslib with MIT License | 5 votes |
def get_hashing_class(hash_algorithm_id): """ <Purpose> Return a pyca/cryptography hashing class reference for the passed RFC4880 hash algorithm ID. <Arguments> hash_algorithm_id: one of SHA1, SHA256, SHA512 (see securesystemslib.gpg.constants) <Exceptions> ValueError if the passed hash_algorithm_id is not supported. <Returns> A pyca/cryptography hashing class """ supported_hashing_algorithms = [securesystemslib.gpg.constants.SHA1, securesystemslib.gpg.constants.SHA256, securesystemslib.gpg.constants.SHA512] corresponding_hashing_classes = [hashing.SHA1, hashing.SHA256, hashing.SHA512] # Map supported hash algorithm ids to corresponding hashing classes hashing_class = dict(zip(supported_hashing_algorithms, corresponding_hashing_classes)) try: return hashing_class[hash_algorithm_id] except KeyError: raise ValueError("Hash algorithm '{}' not supported, must be one of '{}' " "(see RFC4880 9.4. Hash Algorithms).".format(hash_algorithm_id, supported_hashing_algorithms))
Example #30
Source File: test_gpg.py From securesystemslib with MIT License | 5 votes |
def test_get_hashing_class(self): # Assert return expected hashing class expected_hashing_class = [hashing.SHA1, hashing.SHA256, hashing.SHA512] for idx, hashing_id in enumerate([SHA1, SHA256, SHA512]): result = get_hashing_class(hashing_id) self.assertEqual(result, expected_hashing_class[idx]) # Assert raises ValueError with non-supported hashing id with self.assertRaises(ValueError): get_hashing_class("bogus_hashing_id")