當前位置: 首頁>>代碼示例>>Python>>正文


Python padding.PKCS1v15方法代碼示例

本文整理匯總了Python中cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15方法的典型用法代碼示例。如果您正苦於以下問題:Python padding.PKCS1v15方法的具體用法?Python padding.PKCS1v15怎麽用?Python padding.PKCS1v15使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cryptography.hazmat.primitives.asymmetric.padding的用法示例。


在下文中一共展示了padding.PKCS1v15方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: validate

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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) 
開發者ID:pyauth,項目名稱:pywarp,代碼行數:25,代碼來源:attestation.py

示例2: _append_router_signature

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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']) 
開發者ID:torproject,項目名稱:stem,代碼行數:20,代碼來源:__init__.py

示例3: rsa_signer

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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 
開發者ID:openfun,項目名稱:marsha,代碼行數:27,代碼來源:cloudfront_utils.py

示例4: sign_request

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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()),
    }) 
開發者ID:veeti,項目名稱:manuale,代碼行數:21,代碼來源:crypto.py

示例5: _get_padding

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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. 
開發者ID:secdev,項目名稱:scapy,代碼行數:22,代碼來源:pkcs1.py

示例6: _process_encrypted_session_key

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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 
開發者ID:jborean93,項目名稱:pypsrp,代碼行數:19,代碼來源:powershell.py

示例7: test_sign_invalid_key_bytes

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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
        ) 
開發者ID:OpenKMIP,項目名稱:PyKMIP,代碼行數:25,代碼來源:test_engine.py

示例8: sign

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def sign(self, msg, key):
            return key.sign(msg, padding.PKCS1v15(), self.hash_alg()) 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:4,代碼來源:algorithms.py

示例9: verify

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def verify(self, msg, key, sig):
            try:
                key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg())
                return True
            except InvalidSignature:
                return False 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:8,代碼來源:algorithms.py

示例10: _decrypt_text

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def _decrypt_text(text):
    private_key_file = CONF.x509_root_private_key
    if not private_key_file:
        msg = _("Path to ca private key isn't configured")
        raise exception.EC2Exception(msg)
    with open(private_key_file, 'rb') as f:
        data = f.read()
    priv_key = serialization.load_pem_private_key(
        data, None, backends.default_backend())
    return priv_key.decrypt(text, padding.PKCS1v15()) 
開發者ID:openstack,項目名稱:ec2-api,代碼行數:12,代碼來源:image.py

示例11: __init__

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def __init__(self):
        super(_RS256, self).__init__(padding.PKCS1v15(), hashes.SHA256()) 
開發者ID:latchset,項目名稱:jwcrypto,代碼行數:4,代碼來源:jwa.py

示例12: _sign_blob

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def _sign_blob(self, blob):
        key = serialization.load_pem_private_key(
            str(self.private_key), password=None, backend=openssl.backend)
        signer = key.signer(padding.PKCS1v15(), hashes.SHA256())

        signer.update(str(blob))
        return signer.finalize() 
開發者ID:google,項目名稱:rekall,代碼行數:9,代碼來源:cloud.py

示例13: encrypt

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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) 
開發者ID:decentfox,項目名稱:aioh2,代碼行數:11,代碼來源:travis_pypi_setup.py

示例14: get_oauth_token

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
def get_oauth_token(scopes):
	with open("keys.json") as f:
		keys = json.load(f)
	t = int(time.time())

	header = json.dumps({"alg":"RS256", "typ":"JWT"}).encode("utf-8")
	claim = json.dumps({
		"iss": keys["client_email"],
		"scope": " ".join(scopes),
		"aud": "https://accounts.google.com/o/oauth2/token",
		"iat": t,
		"exp": t+60*60,
	}).encode("utf-8")

	data = base64_encode(header) + b'.' + base64_encode(claim)

	key = load_pem_private_key(keys["private_key"].encode("utf-8"), None, openssl.backend)
	signature = key.sign(data, PKCS1v15(), SHA256())

	jwt = (data + b'.' + base64_encode(signature)).decode("utf-8")

	data = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": jwt}

	ret = json.loads((await common.http.request_coro("https://oauth2.googleapis.com/token", data, "POST")))
	if "error" in ret:
		raise Exception(ret["error"])
	return ret 
開發者ID:mrphlip,項目名稱:lrrbot,代碼行數:29,代碼來源:gdata.py

示例15: _verify_signature

# 需要導入模塊: from cryptography.hazmat.primitives.asymmetric import padding [as 別名]
# 或者: from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 [as 別名]
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() 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:12,代碼來源:webauthn.py


注:本文中的cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。