Python cryptography.hazmat.primitives.hashes.SHA1 Examples

The following are 30 code examples of cryptography.hazmat.primitives.hashes.SHA1(). 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: certificates.py    From core with GNU General Public License v3.0 7 votes vote down vote up
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) 
Example #2
Source File: utils.py    From wechatpy with MIT License 7 votes vote down vote up
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 
Example #3
Source File: hotp.py    From teleport with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: hotp.py    From oss-ftp with MIT License 6 votes vote down vote up
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 #5
Source File: test_mock_key_manager.py    From castellan with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: __init__.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
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']) 
Example #7
Source File: cloudfront_utils.py    From marsha with MIT License 6 votes vote down vote up
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 
Example #8
Source File: utils.py    From wechatpy with MIT License 6 votes vote down vote up
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 
Example #9
Source File: hotp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: hotp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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 #11
Source File: _auth.py    From teleport with Apache License 2.0 6 votes vote down vote up
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,
        ),
    ) 
Example #12
Source File: hotp.py    From teleport with Apache License 2.0 6 votes vote down vote up
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: hotp.py    From teleport with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: s3boto3.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #15
Source File: rsakey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #16
Source File: decrypt_key.py    From SupergirlOnCrypt with Do What The F*ck You Want To Public License 6 votes vote down vote up
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 
Example #17
Source File: SupergirlOnCrypt.py    From SupergirlOnCrypt with Do What The F*ck You Want To Public License 6 votes vote down vote up
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 
Example #18
Source File: _auth.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
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,
        ),
    ) 
Example #19
Source File: __init__.py    From commandment with MIT License 6 votes vote down vote up
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 
Example #20
Source File: _auth.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
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,
        ),
    ) 
Example #21
Source File: pkcs1.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
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
##################################################################### 
Example #22
Source File: _auth.py    From teleport with Apache License 2.0 6 votes vote down vote up
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,
        ),
    ) 
Example #23
Source File: sign_cryptography.py    From adb_shell with Apache License 2.0 5 votes vote down vote up
def Sign(self, data):
        """Signs given data using a private key.

        Parameters
        ----------
        data : TODO
            TODO

        Returns
        -------
        TODO
            The signed ``data``

        """
        return self.rsa_key.sign(data, padding.PKCS1v15(), utils.Prehashed(hashes.SHA1())) 
Example #24
Source File: models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def cache_crls(self, password=None, algorithm=None):
        password = password or self.get_password()
        ca_key = self.key(password)
        if isinstance(ca_key, dsa.DSAPrivateKey) and algorithm is None:
            algorithm = hashes.SHA1()

        for name, config in ca_settings.CA_CRL_PROFILES.items():
            overrides = config.get('OVERRIDES', {}).get(self.serial, {})

            if overrides.get('skip'):
                continue

            algorithm = algorithm or parse_hash_algorithm(overrides.get('algorithm', config.get('algorithm')))
            expires = overrides.get('expires', config.get('expires', 86400))
            scope = overrides.get('scope', config.get('scope'))
            full_name = overrides.get('full_name', config.get('full_name'))
            relative_name = overrides.get('relative_name', config.get('relative_name'))
            encodings = overrides.get('encodings', config.get('encodings', ['DER', ]))
            crl = None  # only compute crl when it is actually needed

            for encoding in encodings:
                encoding = parse_encoding(encoding)
                cache_key = get_crl_cache_key(self.serial, algorithm, encoding, scope=scope)

                if expires >= 600:  # pragma: no branch
                    # for longer expiries we substract a random value so that regular CRL regeneration is
                    # distributed a bit
                    cache_expires = expires - random.randint(1, 5) * 60

                if cache.get(cache_key) is None:
                    if crl is None:
                        crl = self.get_crl(expires=expires, algorithm=algorithm, password=password,
                                           scope=scope, full_name=full_name, relative_name=relative_name)

                    encoded_crl = crl.public_bytes(encoding)
                    cache.set(cache_key, encoded_crl, cache_expires) 
Example #25
Source File: acme.py    From hass-nabucasa with GNU General Public License v3.0 5 votes vote down vote up
def fingerprint(self) -> Optional[str]:
        """Return SHA1 hex string as fingerprint."""
        if not self._x509:
            return None
        fingerprint = self._x509.fingerprint(hashes.SHA1())
        return fingerprint.hex() 
Example #26
Source File: cloud.py    From quay with Apache License 2.0 5 votes vote down vote up
def _get_rsa_signer(self):
        private_key = self.cloudfront_privatekey

        def handler(message):
            return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())

        return handler 
Example #27
Source File: crypto_common.py    From torpy with Apache License 2.0 5 votes vote down vote up
def rsa_encrypt(key, data):
    return key.encrypt(
        data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)
    ) 
Example #28
Source File: crypto_common.py    From torpy with Apache License 2.0 5 votes vote down vote up
def sha1_stream(init_msg=None):
    hash = hashes.Hash(hashes.SHA1(), backend=bend)
    if init_msg:
        sha1_stream_update(hash, init_msg)
    return hash 
Example #29
Source File: crypto_common.py    From torpy with Apache License 2.0 5 votes vote down vote up
def sha1(msg):
    sha = hashes.Hash(hashes.SHA1(), backend=bend)
    sha.update(msg)
    return sha.finalize() 
Example #30
Source File: generate_wrapped_rsa_key.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def wrap_rsa_key(public_key, private_key_bytes):
    # Use the Google public key to encrypt the customer private key.
    # This means that only the Google private key is capable of decrypting
    # the customer private key.
    wrapped_key = public_key.encrypt(
        private_key_bytes,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None))
    encoded_wrapped_key = base64.b64encode(wrapped_key)
    return encoded_wrapped_key