Python cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15() Examples

The following are 30 code examples of cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15(). 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.asymmetric.padding , or try the search function .
Example #1
Source File: attestation.py    From pywarp with Apache License 2.0 6 votes vote down vote up
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 #2
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 #3
Source File: test_engine.py    From PyKMIP with Apache License 2.0 6 votes vote down vote up
def test_sign_invalid_key_bytes(self):
        """
        Test that an InvalidField exception is raised when
        sign is called with invalid key bytes.
        """
        engine = crypto.CryptographyEngine()

        args = (
            None,
            enums.CryptographicAlgorithm.RSA,
            enums.HashingAlgorithm.MD5,
            enums.PaddingMethod.PKCS1v15,
            'thisisnotavalidkey',
            None
        )

        self.assertRaisesRegex(
            exceptions.InvalidField,
            'Unable to deserialize key '
            'bytes, unknown format.',
            engine.sign,
            *args
        ) 
Example #4
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 #5
Source File: crypto.py    From manuale with MIT License 6 votes vote down vote up
def sign_request(key, header, protected_header, payload):
    """
    Creates a JSON Web Signature for the request header and payload using the
    specified account key.
    """
    protected = jose_b64(json.dumps(protected_header).encode('utf8'))
    payload = jose_b64(json.dumps(payload).encode('utf8'))

    signer = key.signer(padding.PKCS1v15(), hashes.SHA256())
    signer.update(protected.encode('ascii'))
    signer.update(b'.')
    signer.update(payload.encode('ascii'))

    return json.dumps({
        'header': header,
        'protected': protected,
        'payload': payload,
        'signature': jose_b64(signer.finalize()),
    }) 
Example #6
Source File: pkcs1.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def _get_padding(padStr, mgf=padding.MGF1, h=hashes.SHA256, label=None):
        if padStr == "pkcs":
            return padding.PKCS1v15()
        elif padStr == "pss":
            # Can't find where this is written, but we have to use the digest
            # size instead of the automatic padding.PSS.MAX_LENGTH.
            return padding.PSS(mgf=mgf(h), salt_length=h.digest_size)
        elif padStr == "oaep":
            return padding.OAEP(mgf=mgf(h), algorithm=h, label=label)
        else:
            warning("Key.encrypt(): Unknown padding type (%s)", padStr)
            return None


#####################################################################
# Asymmetric Cryptography wrappers
#####################################################################

# Make sure that default values are consistent across the whole TLS module,
# lest they be explicitly set to None between cert.py and pkcs1.py. 
Example #7
Source File: powershell.py    From pypsrp with MIT License 6 votes vote down vote up
def _process_encrypted_session_key(self, message):
        log.debug("Received EncryptedSessionKey response")
        enc_sess_key = base64.b64decode(message.data.session_key)

        # strip off Win32 Crypto Blob Header and reverse the bytes
        encrypted_key = enc_sess_key[12:][::-1]
        pad_method = padding.PKCS1v15()
        decrypted_key = self._exchange_key.decrypt(encrypted_key, pad_method)

        iv = b"\x00" * 16  # PSRP doesn't use an IV
        algorithm = algorithms.AES(decrypted_key)
        mode = modes.CBC(iv)
        cipher = Cipher(algorithm, mode, default_backend())

        self._serializer.cipher = cipher
        self._key_exchanged = True
        self._exchange_key = None 
Example #8
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sign(self, sigdata, hash_alg):
        return self.__privkey__().sign(sigdata, padding.PKCS1v15(), hash_alg) 
Example #9
Source File: travis_pypi_setup.py    From django-spa with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #10
Source File: crypto.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, digest, padding=None):
        self._digest = digest
        self._padding = padding or PKCS1v15() 
Example #11
Source File: cryptography_backend.py    From python-jose with MIT License 5 votes vote down vote up
def sign(self, msg):
        try:
            signature = self.prepared_key.sign(
                msg,
                padding.PKCS1v15(),
                self.hash_alg()
            )
        except Exception as e:
            raise JWKError(e)
        return signature 
Example #12
Source File: travis_pypi_setup.py    From qpic with GNU General Public License v3.0 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #13
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify(self, subj, sigbytes, hash_alg):
        # zero-pad sigbytes if necessary
        sigbytes = (b'\x00' * (self.n.byte_length() - len(sigbytes))) + sigbytes
        try:
            self.__pubkey__().verify(sigbytes, subj, padding.PKCS1v15(), hash_alg)
        except InvalidSignature:
            return False
        return True 
Example #14
Source File: travis_pypi_setup.py    From plumbery with Apache License 2.0 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #15
Source File: travis_pypi_setup.py    From akagi with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #16
Source File: cryptography_backend.py    From python-jose with MIT License 5 votes vote down vote up
def verify(self, msg, sig):
        try:
            self.prepared_key.verify(
                sig,
                msg,
                padding.PKCS1v15(),
                self.hash_alg()
            )
            return True
        except InvalidSignature:
            return False 
Example #17
Source File: jwk.py    From python-jwt with Apache License 2.0 5 votes vote down vote up
def verify(self, message: bytes, signature: bytes, **options) -> bool:
        hash_fun = self._get_hash_fun(options)
        if self.is_sign_key():
            pubkey = self.keyobj.public_key()
        else:
            pubkey = self.keyobj
        try:
            pubkey.verify(signature, message, padding.PKCS1v15(), hash_fun())
            return True
        except InvalidSignature:
            return False 
Example #18
Source File: jwk.py    From python-jwt with Apache License 2.0 5 votes vote down vote up
def sign(self, message: bytes, **options) -> bytes:
        hash_fun = self._get_hash_fun(options)
        return self.keyobj.sign(message, padding.PKCS1v15(), hash_fun()) 
Example #19
Source File: travis_pypi_setup.py    From alexafsm with Apache License 2.0 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #20
Source File: travis_pypi_setup.py    From drf_openapi with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #21
Source File: travis_pypi_setup.py    From pyseqlogo with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #22
Source File: __init__.py    From commandment with MIT License 5 votes vote down vote up
def _cryptography_pad_function(algorithm: SignedDigestAlgorithm) -> Union[None, Type[padding.PKCS1v15]]:
    """Find the cryptography pad function given a signed digest algorithm from asn1crypto.

    Args:
        algorithm (SignedDigestAlgorithm): The asn1crypto Signed Digest Algorithm
    Returns:
        Union[None, Type[padding.PKCS1v15]]: The padding function for the signed digest
        """
    signature_algo = algorithm.signature_algo

    if signature_algo == "rsassa_pkcs1v15":
        return padding.PKCS1v15
    else:
        return None 
Example #23
Source File: cms.py    From zentral with Apache License 2.0 5 votes vote down vote up
def get_cryptography_asymmetric_padding(signer):
    padding_name = signer["signature_algorithm"].signature_algo
    if padding_name == "rsassa_pkcs1v15":
        return padding.PKCS1v15
    else:
        raise ValueError("Unknown padding {}".format(padding_name)) 
Example #24
Source File: travis_pypi_setup.py    From kibitzr with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #25
Source File: travis_pypi_setup.py    From underthesea with GNU General Public License v3.0 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #26
Source File: utils.py    From lemur with Apache License 2.0 5 votes vote down vote up
def check_cert_signature(cert, issuer_public_key):
    """
    Check a certificate's signature against an issuer public key.
    Before EC validation, make sure we support the algorithm, otherwise raise UnsupportedAlgorithm
    On success, returns None; on failure, raises UnsupportedAlgorithm or InvalidSignature.
    """
    if isinstance(issuer_public_key, rsa.RSAPublicKey):
        # RSA requires padding, just to make life difficult for us poor developers :(
        if cert.signature_algorithm_oid == x509.SignatureAlgorithmOID.RSASSA_PSS:
            # In 2005, IETF devised a more secure padding scheme to replace PKCS #1 v1.5. To make sure that
            # nobody can easily support or use it, they mandated lots of complicated parameters, unlike any
            # other X.509 signature scheme.
            # https://tools.ietf.org/html/rfc4056
            raise UnsupportedAlgorithm("RSASSA-PSS not supported")
        else:
            padder = padding.PKCS1v15()
        issuer_public_key.verify(
            cert.signature,
            cert.tbs_certificate_bytes,
            padder,
            cert.signature_hash_algorithm,
        )
    elif isinstance(issuer_public_key, ec.EllipticCurvePublicKey) and isinstance(
        ec.ECDSA(cert.signature_hash_algorithm), ec.ECDSA
    ):
        issuer_public_key.verify(
            cert.signature,
            cert.tbs_certificate_bytes,
            ec.ECDSA(cert.signature_hash_algorithm),
        )
    else:
        raise UnsupportedAlgorithm(
            "Unsupported Algorithm '{var}'.".format(
                var=cert.signature_algorithm_oid._name
            )
        ) 
Example #27
Source File: travis_pypi_setup.py    From swagger-aggregator with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #28
Source File: travis_pypi_setup.py    From logzero with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #29
Source File: travis_pypi_setup.py    From hydrofunctions with MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example #30
Source File: travis_pypi_setup.py    From pyucwa with Apache License 2.0 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password)