How to use the cryptography.hazmat.primitives.hashes.SHA256 function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github magma / magma / orc8r / gateway / python / magma / magmad / bootstrap_manager.py View on Github external
Returns:
            r_bytes, s_bytes: ecdsa signature R, S in bytes

        Raises:
            BootstrapError: if the gateway cannot be properly loaded
        """
        try:
            challenge_key = cert_utils.load_key(self._challenge_key_file)
        except (IOError, ValueError, TypeError) as e:
            raise BootstrapError(
                'Gateway does not have a proper challenge key: %s' % e,
            )

        try:
            signature = challenge_key.sign(
                challenge, ec.ECDSA(hashes.SHA256()),
            )
        except TypeError:
            raise BootstrapError(
                'Challenge key cannot be used for ECDSA signature',
            )

        r_int, s_int = decode_dss_signature(signature)
        r_bytes = r_int.to_bytes((r_int.bit_length() + 7) // 8, 'big')
        s_bytes = s_int.to_bytes((s_int.bit_length() + 7) // 8, 'big')
        return r_bytes, s_bytes
github pyca / cryptography / tests / hazmat / primitives / test_hkdf.py View on Github external
def test_invalid_backend():
    pretend_backend = object()

    with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
        HKDF(hashes.SHA256(), 16, None, None, pretend_backend)

    with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
        HKDFExpand(hashes.SHA256(), 16, None, pretend_backend)
github Yubico / python-fido2 / fido2 / cose.py View on Github external
}
        )

    @classmethod
    def from_ctap1(cls, data):
        """Creates an ES256 key from a CTAP1 formatted public key byte string.

        :param data: A 65 byte SECP256R1 public key.
        :return: A ES256 key.
        """
        return cls({1: 2, 3: cls.ALGORITHM, -1: 1, -2: data[1:33], -3: data[33:65]})


class RS256(CoseKey):
    ALGORITHM = -257
    _HASH_ALG = hashes.SHA256()

    def verify(self, message, signature):
        rsa.RSAPublicNumbers(bytes2int(self[-2]), bytes2int(self[-1])).public_key(
            default_backend()
        ).verify(signature, message, padding.PKCS1v15(), self._HASH_ALG)

    @classmethod
    def from_cryptography_key(cls, public_key):
        pn = public_key.public_numbers()
        return cls({1: 3, 3: cls.ALGORITHM, -1: int2bytes(pn.n), -2: int2bytes(pn.e)})


class PS256(CoseKey):
    ALGORITHM = -37
    _HASH_ALG = hashes.SHA256()
github komlog-io / komlogd / lib / komlogd / api / common / crypto.py View on Github external
def sign_message(privkey, message):
    plaintext = b64decode(message.encode('utf-8'))
    signature = privkey.sign(
        plaintext,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    return b64encode(signature).decode('utf-8')
github xeroc / python-graphenelib / graphenebase / ecdsa.py View on Github external
pub = secp256k1.PublicKey(flags=ALL_FLAGS)
        # Recover raw signature
        sig = pub.ecdsa_recoverable_deserialize(sig, recoverParameter)
        # Recover PublicKey
        verifyPub = secp256k1.PublicKey(pub.ecdsa_recover(message, sig))
        # Convert recoverable sig to normal sig
        normalSig = verifyPub.ecdsa_recoverable_convert(sig)
        # Verify
        verifyPub.ecdsa_verify(message, normalSig)
        phex = verifyPub.serialize(compressed=True)
    elif SECP256K1_MODULE == "cryptography":
        p = recover_public_key(digest, sig, recoverParameter, message)
        order = ecdsa.SECP256k1.order
        r, s = ecdsa.util.sigdecode_string(sig, order)
        sigder = encode_dss_signature(r, s)
        p.verify(sigder, message, ec.ECDSA(hashes.SHA256()))
        phex = compressedPubkey(p)
    else:  # pragma: no branch  # pragma: no cover
        p = recover_public_key(digest, sig, recoverParameter)
        # Will throw an exception of not valid
        p.verify_digest(sig, digest, sigdecode=ecdsa.util.sigdecode_string)
        phex = compressedPubkey(p)

    return phex
github ethereans / github-token / tools / encrypted_queries_tools.py View on Github external
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
github georgemarshall / django-cryptography / django_cryptography / conf.py View on Github external
from appconf import AppConf
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf import pbkdf2
from django.conf import settings
from django.utils.encoding import force_bytes


class CryptographyConf(AppConf):
    BACKEND = default_backend()
    DIGEST = hashes.SHA256()
    KEY = None
    SALT = 'django-cryptography'

    class Meta:
        prefix = 'cryptography'
        proxy = True

    def configure_salt(self, value):
        return force_bytes(value)

    def configure(self):
        backend = self.configured_data['BACKEND']
        digest = self.configured_data['DIGEST']
        salt = self.configured_data['SALT']
        # Key Derivation Function
        kdf = pbkdf2.PBKDF2HMAC(
github ansible / ansible / lib / ansible / modules / crypto / openssl_privatekey_info.py View on Github external
if isinstance(key, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):
        return bool(key._backend._lib.RSA_check_key(key._rsa_cdata))
    if isinstance(key, cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey):
        result = _check_dsa_consistency(key_public_data, key_private_data)
        if result is not None:
            return result
        try:
            signature = key.sign(SIGNATURE_TEST_DATA, cryptography.hazmat.primitives.hashes.SHA256())
        except AttributeError:
            # sign() was added in cryptography 1.5, but we support older versions
            return None
        try:
            key.public_key().verify(
                signature,
                SIGNATURE_TEST_DATA,
                cryptography.hazmat.primitives.hashes.SHA256()
            )
            return True
        except cryptography.exceptions.InvalidSignature:
            return False
    if isinstance(key, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey):
        try:
            signature = key.sign(
                SIGNATURE_TEST_DATA,
                cryptography.hazmat.primitives.asymmetric.ec.ECDSA(cryptography.hazmat.primitives.hashes.SHA256())
            )
        except AttributeError:
            # sign() was added in cryptography 1.5, but we support older versions
            return None
        try:
            key.public_key().verify(
                signature,
github google / grr / grr / core / grr_response_core / lib / rdfvalues / crypto.py View on Github external
def _CalculateHash(self, password, salt, iteration_count):
    kdf = pbkdf2.PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=iteration_count,
        backend=openssl.backend)
    return kdf.derive(password)
github privcount / privcount / privcount / crypto.py View on Github external
"""
    try:
        plaintext = priv_key.decrypt(
            b64decode(ciphertext),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=CryptoHash()),
                algorithm=CryptoHash(),
                label=None
                )
            )
    except UnsupportedAlgorithm as e:
        # a failure to dencrypt someone else's data is not typically a fatal
        # error, but in this particular case, the most likely cause of this
        # error is an old cryptography library
        logging.error("Fatal error: encryption hash {} unsupported, try upgrading to cryptography >= 1.4. Exception: {}".format(
                          CryptoHash, e))
        # re-raise the exception for the caller to handle
        raise e
    return plaintext