本文整理汇总了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)
示例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'])
示例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
示例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()),
})
示例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.
示例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
示例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
)
示例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())
示例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
示例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())
示例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())
示例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()
示例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)
示例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
示例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()