azure.keyvault.keys.crypto package¶
- class azure.keyvault.keys.crypto.CryptographyClient(key: KeyVaultKey | str, credential: TokenCredential, **kwargs: Any)[source]¶
Performs cryptographic operations using Azure Key Vault keys.
This client will perform operations locally when it’s intialized with the necessary key material or is able to get that material from Key Vault. When the required key material is unavailable, cryptographic operations are performed by the Key Vault service.
- Parameters:
key (str or azure.keyvault.keys.KeyVaultKey) – Either a azure.keyvault.keys.KeyVaultKey instance as returned by
get_key()
, or a string. If a string, the value must be the identifier of an Azure Key Vault key. Including a version is recommended.credential (TokenCredential) – An object which can provide an access token for the vault, such as a credential from
azure.identity
- Keyword Arguments:
api_version (ApiVersion or str) – Version of the service API to use. Defaults to the most recent.
verify_challenge_resource (bool) – Whether to verify the authentication challenge resource matches the Key Vault or Managed HSM domain. Defaults to True.
# create a CryptographyClient using a KeyVaultKey instance key = key_client.get_key(key_name) crypto_client = CryptographyClient(key, credential) # or a key's id, which must include a version key_id = "https://<your vault>.vault.azure.net/keys/<key name>/fe4fdcab688c479a9aa80f01ffeac26" crypto_client = CryptographyClient(key_id, credential)
- close() None ¶
Close sockets opened by the client.
Calling this method is unnecessary when using the client as a context manager.
- create_rsa_private_key() KeyVaultRSAPrivateKey [source]¶
Create an RSAPrivateKey implementation backed by this CryptographyClient, as a KeyVaultRSAPrivateKey.
The CryptographyClient will attempt to download the key, if it hasn’t been already, as part of this operation.
- Returns:
A KeyVaultRSAPrivateKey, which implements cryptography’s RSAPrivateKey interface.
- Return type:
- create_rsa_public_key() KeyVaultRSAPublicKey [source]¶
Create an RSAPublicKey implementation backed by this CryptographyClient, as a KeyVaultRSAPublicKey.
The CryptographyClient will attempt to download the key, if it hasn’t been already, as part of this operation.
- Returns:
A KeyVaultRSAPublicKey, which implements cryptography’s RSAPublicKey interface.
- Return type:
- decrypt(algorithm: EncryptionAlgorithm, ciphertext: bytes, **kwargs: Any) DecryptResult [source]¶
Decrypt a single block of encrypted data using the client’s key.
Requires the keys/decrypt permission. This method decrypts only a single block of data, whose size depends on the key and encryption algorithm.
- Parameters:
algorithm (EncryptionAlgorithm) – Encryption algorithm to use
ciphertext (bytes) – Encrypted bytes to decrypt. Microsoft recommends you not use CBC without first ensuring the integrity of the ciphertext using, for example, an HMAC. See https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information.
- Keyword Arguments:
iv (bytes or None) – The initialization vector used during encryption. Required for AES decryption.
authentication_tag (bytes or None) – The authentication tag generated during encryption. Required for only AES-GCM decryption.
additional_authenticated_data (bytes or None) – Optional data that is authenticated but not encrypted. For use with AES-GCM decryption.
- Returns:
The result of the decryption operation.
- Return type:
- Raises:
ValueError – If parameters that are incompatible with the specified algorithm are provided.
from azure.keyvault.keys.crypto import EncryptionAlgorithm result = client.decrypt(EncryptionAlgorithm.rsa_oaep, ciphertext) print(result.plaintext)
- encrypt(algorithm: EncryptionAlgorithm, plaintext: bytes, **kwargs: Any) EncryptResult [source]¶
Encrypt bytes using the client’s key.
Requires the keys/encrypt permission. This method encrypts only a single block of data, whose size depends on the key and encryption algorithm.
- Parameters:
algorithm (EncryptionAlgorithm) – Encryption algorithm to use
plaintext (bytes) – Bytes to encrypt
- Keyword Arguments:
iv (bytes or None) – Initialization vector. Required for only AES-CBC(PAD) encryption. If you pass your own IV, make sure you use a cryptographically random, non-repeating IV. If omitted, an attempt will be made to generate an IV via os.urandom for local cryptography; for remote cryptography, Key Vault will generate an IV.
additional_authenticated_data (bytes or None) – Optional data that is authenticated but not encrypted. For use with AES-GCM encryption.
- Returns:
The result of the encryption operation.
- Return type:
- Raises:
ValueError – if parameters that are incompatible with the specified algorithm are provided, or if generating an IV fails on the current platform.
from azure.keyvault.keys.crypto import EncryptionAlgorithm # the result holds the ciphertext and identifies the encryption key and algorithm used result = client.encrypt(EncryptionAlgorithm.rsa_oaep, b"plaintext") ciphertext = result.ciphertext print(result.key_id) print(result.algorithm)
- classmethod from_jwk(jwk: JsonWebKey | Dict[str, Any]) CryptographyClient [source]¶
Creates a client that can only perform cryptographic operations locally.
- Parameters:
jwk (JsonWebKey or Dict[str, Any]) – the key’s cryptographic material, as a JsonWebKey or dictionary.
- Returns:
A client that can only perform local cryptographic operations.
- Return type:
- send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) HttpResponse ¶
Runs a network request using the client’s existing pipeline.
The request URL can be relative to the vault URL. The service API version used for the request is the same as the client’s unless otherwise specified. This method does not raise if the response is an error; to raise an exception, call raise_for_status() on the returned response object. For more information about how to send custom requests with this method, see https://aka.ms/azsdk/dpcodegen/python/send_request.
- Parameters:
request (HttpRequest) – The network request you want to make.
- Keyword Arguments:
stream (bool) – Whether the response payload will be streamed. Defaults to False.
- Returns:
The response of your network call. Does not do error handling on your response.
- Return type:
- sign(algorithm: SignatureAlgorithm, digest: bytes, **kwargs: Any) SignResult [source]¶
Create a signature from a digest using the client’s key.
Requires the keys/sign permission.
- Parameters:
algorithm (SignatureAlgorithm) – signing algorithm
digest (bytes) – hashed bytes to sign
- Returns:
The result of the signing operation.
- Return type:
import hashlib from azure.keyvault.keys.crypto import SignatureAlgorithm digest = hashlib.sha256(b"plaintext").digest() # sign returns the signature and the metadata required to verify it result = client.sign(SignatureAlgorithm.rs256, digest) print(result.key_id) print(result.algorithm) signature = result.signature
- unwrap_key(algorithm: KeyWrapAlgorithm, encrypted_key: bytes, **kwargs: Any) UnwrapResult [source]¶
Unwrap a key previously wrapped with the client’s key.
Requires the keys/unwrapKey permission.
- Parameters:
algorithm (KeyWrapAlgorithm) – wrapping algorithm to use
encrypted_key (bytes) – the wrapped key
- Returns:
The result of the unwrapping operation.
- Return type:
from azure.keyvault.keys.crypto import KeyWrapAlgorithm result = client.unwrap_key(KeyWrapAlgorithm.rsa_oaep, encrypted_key) key = result.key
- verify(algorithm: SignatureAlgorithm, digest: bytes, signature: bytes, **kwargs: Any) VerifyResult [source]¶
Verify a signature using the client’s key.
Requires the keys/verify permission.
- Parameters:
algorithm (SignatureAlgorithm) – verification algorithm
digest (bytes) – Pre-hashed digest corresponding to signature. The hash algorithm used must be compatible with
algorithm
.signature (bytes) – signature to verify
- Returns:
The result of the verifying operation.
- Return type:
from azure.keyvault.keys.crypto import SignatureAlgorithm result = client.verify(SignatureAlgorithm.rs256, digest, signature) assert result.is_valid
- wrap_key(algorithm: KeyWrapAlgorithm, key: bytes, **kwargs: Any) WrapResult [source]¶
Wrap a key with the client’s key.
Requires the keys/wrapKey permission.
- Parameters:
algorithm (KeyWrapAlgorithm) – wrapping algorithm to use
key (bytes) – key to wrap
- Returns:
The result of the wrapping operation.
- Return type:
from azure.keyvault.keys.crypto import KeyWrapAlgorithm # the result holds the encrypted key and identifies the encryption key and algorithm used result = client.wrap_key(KeyWrapAlgorithm.rsa_oaep, key_bytes) encrypted_key = result.encrypted_key print(result.key_id) print(result.algorithm)
- property key_id: str | None¶
The full identifier of the client’s key.
This property may be None when a client is constructed with
from_jwk()
.- Returns:
The full identifier of the client’s key.
- Return type:
str or None
- property vault_url: str | None¶
The base vault URL of the client’s key.
This property may be None when a client is constructed with
from_jwk()
.- Returns:
The base vault URL of the client’s key.
- Return type:
str or None
- class azure.keyvault.keys.crypto.DecryptResult(key_id: str | None, algorithm: EncryptionAlgorithm, plaintext: bytes)[source]¶
The result of a decrypt operation.
- Parameters:
key_id (str) – The encryption key’s Key Vault identifier
algorithm (EncryptionAlgorithm) – The encryption algorithm used
plaintext (bytes) – The decrypted bytes
- class azure.keyvault.keys.crypto.EncryptResult(key_id: str | None, algorithm: EncryptionAlgorithm, ciphertext: bytes, **kwargs: Any)[source]¶
The result of an encrypt operation.
- Parameters:
key_id (str) – The encryption key’s Key Vault identifier
algorithm (EncryptionAlgorithm) – The encryption algorithm used
ciphertext (bytes) – The encrypted bytes
- Keyword Arguments:
iv (bytes) – Initialization vector for symmetric algorithms
authentication_tag (bytes) – The tag to authenticate when performing decryption with an authenticated algorithm
additional_authenticated_data (bytes) – Additional data to authenticate but not encrypt/decrypt when using an authenticated algorithm
- class azure.keyvault.keys.crypto.EncryptionAlgorithm(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Encryption algorithms
- capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()¶
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int ¶
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool ¶
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str ¶
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str ¶
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()¶
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)¶
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool ¶
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)¶
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()¶
Return a copy of the string converted to uppercase.
- zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- a128_cbc = 'A128CBC'¶
- a128_cbcpad = 'A128CBCPAD'¶
- a128_gcm = 'A128GCM'¶
- a192_cbc = 'A192CBC'¶
- a192_cbcpad = 'A192CBCPAD'¶
- a192_gcm = 'A192GCM'¶
- a256_cbc = 'A256CBC'¶
- a256_cbcpad = 'A256CBCPAD'¶
- a256_gcm = 'A256GCM'¶
- rsa1_5 = 'RSA1_5'¶
- rsa_oaep = 'RSA-OAEP'¶
- rsa_oaep_256 = 'RSA-OAEP-256'¶
- class azure.keyvault.keys.crypto.KeyVaultRSAPrivateKey(client: CryptographyClient, key_material: JsonWebKey | None)[source]¶
An RSAPrivateKey implementation based on a key managed by Key Vault.
This class should not be instantiated directly. Instead, use the
create_rsa_private_key()
method to create a key based on the client’s key. Only synchronous clients and operations are supported at this time.- decrypt(ciphertext: bytes, padding: AsymmetricPadding) bytes [source]¶
Decrypts the provided ciphertext.
- Parameters:
ciphertext (bytes) – Encrypted bytes to decrypt.
padding (AsymmetricPadding) – The padding to use. Supported paddings are OAEP and PKCS1v15. For OAEP padding, supported hash algorithms are SHA1 and SHA256. The only supported mask generation function is MGF1. See https://learn.microsoft.com/azure/key-vault/keys/about-keys-details for details.
- Returns:
The decrypted plaintext, as bytes.
- Return type:
- private_bytes(encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption) bytes [source]¶
Allows serialization of the key to bytes.
This function uses the cryptography library’s implementation. Encoding (PEM or DER) and format (TraditionalOpenSSL, OpenSSH, or PKCS8) and encryption algorithm (such as BestAvailableEncryption or NoEncryption) are chosen to define the exact serialization.
- Parameters:
encoding (Encoding) – A value from the Encoding enum.
format (PrivateFormat) – A value from the PrivateFormat enum.
encryption_algorithm (KeySerializationEncryption) – An instance of an object conforming to the KeySerializationEncryption interface.
- Returns:
The serialized key.
- Return type:
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- private_numbers() RSAPrivateNumbers [source]¶
Returns an RSAPrivateNumbers representing the key’s private numbers.
- Returns:
The private numbers of the key.
- Return type:
RSAPrivateNumbers
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- public_key() KeyVaultRSAPublicKey [source]¶
The RSAPublicKey associated with this private key, as a KeyVaultRSAPublicKey.
The public key implementation will use the same underlying cryptography client as this private key.
- Returns:
The KeyVaultRSAPublicKey associated with the key.
- Return type:
- sign(data: bytes, padding: AsymmetricPadding, algorithm: Prehashed | HashAlgorithm) bytes [source]¶
Signs the data.
- Parameters:
data (bytes) – The data to sign, as bytes.
padding (AsymmetricPadding) – The padding to use. Supported paddings are PKCS1v15 and PSS. For PSS, the only supported mask generation function is MGF1. See https://learn.microsoft.com/azure/key-vault/keys/about-keys-details for details.
algorithm (Prehashed or cryptography.hazmat.primitives.hashes.HashAlgorithm) – The algorithm to sign with. Only HashAlgorithm`s are supported – specifically, `SHA256, SHA384, and SHA512.
- Returns:
The signature, as bytes.
- Return type:
- signer(padding: AsymmetricPadding, algorithm: HashAlgorithm) NoReturn [source]¶
Not implemented. This method was deprecated in cryptography 2.0 and removed in 37.0.0.
- property key_size: int¶
The bit length of the public modulus.
- Returns:
The key’s size.
- Return type:
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- class azure.keyvault.keys.crypto.KeyVaultRSAPublicKey(client: CryptographyClient, key_material: JsonWebKey | None = None)[source]¶
An RSAPublicKey implementation based on a key managed by Key Vault.
This class should not be instantiated directly. Instead, use the
create_rsa_public_key()
method to create a key based on the client’s key. Only synchronous clients and operations are supported at this time.- encrypt(plaintext: bytes, padding: AsymmetricPadding) bytes [source]¶
Encrypts the given plaintext.
- Parameters:
plaintext (bytes) – Plaintext to encrypt.
padding (AsymmetricPadding) – The padding to use. Supported paddings are OAEP and PKCS1v15. For OAEP padding, supported hash algorithms are SHA1 and SHA256. The only supported mask generation function is MGF1. See https://learn.microsoft.com/azure/key-vault/keys/about-keys-details for details.
- Returns:
The encrypted ciphertext, as bytes.
- Return type:
- public_bytes(encoding: Encoding, format: PublicFormat) bytes [source]¶
Allows serialization of the key to bytes.
This function uses the cryptography library’s implementation. Encoding (PEM or DER) and format (SubjectPublicKeyInfo or PKCS1) are chosen to define the exact serialization.
- Parameters:
encoding (Encoding) – A value from the Encoding enum.
format (PublicFormat) – A value from the PublicFormat enum.
- Returns:
The serialized key.
- Return type:
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- public_numbers() RSAPublicNumbers [source]¶
Returns an RSAPublicNumbers representing the key’s public numbers.
- Returns:
The public numbers of the key.
- Return type:
RSAPublicNumbers
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- recover_data_from_signature(signature: bytes, padding: AsymmetricPadding, algorithm: HashAlgorithm | None) bytes [source]¶
Recovers the signed data from the signature. Only supported with cryptography version 3.3 and above.
This function uses the cryptography library’s implementation. The data typically contains the digest of the original message string. The padding and algorithm parameters must match the ones used when the signature was created for the recovery to succeed. The algorithm parameter can also be set to None to recover all the data present in the signature, without regard to its format or the hash algorithm used for its creation.
For PKCS1v15 padding, this method returns the data after removing the padding layer. For standard signatures the data contains the full DigestInfo structure. For non-standard signatures, any data can be returned, including zero-length data.
Normally you should use the verify() function to validate the signature. But for some non-standard signature formats you may need to explicitly recover and validate the signed data. The following are some examples:
Some old Thawte and Verisign timestamp certificates without DigestInfo.
Signed MD5/SHA1 hashes in TLS 1.1 or earlier (RFC 4346, section 4.7).
IKE version 1 signatures without DigestInfo (RFC 2409, section 5.1).
- Parameters:
signature (bytes) – The signature.
padding (AsymmetricPadding) – An instance of AsymmetricPadding. Recovery is only supported with some of the padding types.
algorithm (HashAlgorithm) – An instance of HashAlgorithm. Can be None to return all the data present in the signature.
- Returns:
The signed data.
- Return type:
- Raises:
NotImplementedError – if the local version of cryptography doesn’t support this method.
InvalidSignature – if the signature is invalid.
UnsupportedAlgorithm – if the signature data recovery is not supported with the provided padding type.
ValueError – if the client is unable to obtain the key material from Key Vault.
- verifier(signature: bytes, padding: AsymmetricPadding, algorithm: HashAlgorithm) NoReturn [source]¶
Not implemented. This method was deprecated in cryptography 2.0 and removed in 37.0.0.
- verify(signature: bytes, data: bytes, padding: AsymmetricPadding, algorithm: Prehashed | HashAlgorithm) None [source]¶
Verifies the signature of the data.
- Parameters:
signature (bytes) – The signature to sign, as bytes.
data (bytes) – The message string that was signed., as bytes.
padding (AsymmetricPadding) – The padding to use. Supported paddings are PKCS1v15 and PSS. For PSS, the only supported mask generation function is MGF1. See https://learn.microsoft.com/azure/key-vault/keys/about-keys-details for details.
algorithm (Prehashed or cryptography.hazmat.primitives.hashes.HashAlgorithm) – The algorithm to sign with. Only HashAlgorithm`s are supported – specifically, `SHA256, SHA384, and SHA512.
- Raises:
InvalidSignature – If the signature does not validate.
- property key_size: int¶
The bit length of the public modulus.
- Returns:
The key’s size.
- Return type:
- Raises:
ValueError – if the client is unable to obtain the key material from Key Vault.
- class azure.keyvault.keys.crypto.KeyWrapAlgorithm(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Key wrapping algorithms
- capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()¶
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int ¶
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool ¶
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str ¶
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str ¶
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()¶
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)¶
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool ¶
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)¶
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()¶
Return a copy of the string converted to uppercase.
- zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- aes_128 = 'A128KW'¶
- aes_192 = 'A192KW'¶
- aes_256 = 'A256KW'¶
- rsa1_5 = 'RSA1_5'¶
- rsa_oaep = 'RSA-OAEP'¶
- rsa_oaep_256 = 'RSA-OAEP-256'¶
- class azure.keyvault.keys.crypto.SignResult(key_id: str | None, algorithm: SignatureAlgorithm, signature: bytes)[source]¶
The result of a sign operation.
- Parameters:
key_id (str) – The signing key’s Key Vault identifier
algorithm (SignatureAlgorithm) – The signature algorithm used
signature (bytes) –
- class azure.keyvault.keys.crypto.SignatureAlgorithm(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Signature algorithms, described in https://tools.ietf.org/html/rfc7518
- capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()¶
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int ¶
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool ¶
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str ¶
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str ¶
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()¶
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)¶
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool ¶
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)¶
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()¶
Return a copy of the string converted to uppercase.
- zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- es256 = 'ES256'¶
ECDSA using P-256 and SHA-256
- es256_k = 'ES256K'¶
ECDSA using P-256K and SHA-256
- es384 = 'ES384'¶
ECDSA using P-384 and SHA-384
- es512 = 'ES512'¶
ECDSA using P-521 and SHA-512
- ps256 = 'PS256'¶
RSASSA-PSS using SHA-256 and MGF1 with SHA-256
- ps384 = 'PS384'¶
RSASSA-PSS using SHA-384 and MGF1 with SHA-384
- ps512 = 'PS512'¶
RSASSA-PSS using SHA-512 and MGF1 with SHA-512
- rs256 = 'RS256'¶
RSASSA-PKCS1-v1_5 using SHA-256
- rs384 = 'RS384'¶
RSASSA-PKCS1-v1_5 using SHA-384
- rs512 = 'RS512'¶
RSASSA-PKCS1-v1_5 using SHA-512
- class azure.keyvault.keys.crypto.UnwrapResult(key_id: str | None, algorithm: KeyWrapAlgorithm, key: bytes)[source]¶
The result of an unwrap key operation.
- Parameters:
key_id (str) – Key encryption key’s Key Vault identifier
algorithm (KeyWrapAlgorithm) – The key wrap algorithm used
key (bytes) – The unwrapped key
- class azure.keyvault.keys.crypto.VerifyResult(key_id: str | None, is_valid: bool, algorithm: SignatureAlgorithm)[source]¶
The result of a verify operation.
- Parameters:
key_id (str) – The signing key’s Key Vault identifier
is_valid (bool) – Whether the signature is valid
algorithm (SignatureAlgorithm) – The signature algorithm used
- class azure.keyvault.keys.crypto.WrapResult(key_id: str | None, algorithm: KeyWrapAlgorithm, encrypted_key: bytes)[source]¶
The result of a wrap key operation.
- Parameters:
key_id (str) – The wrapping key’s Key Vault identifier
algorithm (KeyWrapAlgorithm) – The key wrap algorithm used
encrypted_key (bytes) – The encrypted key bytes
Subpackages¶
- azure.keyvault.keys.crypto.aio package
CryptographyClient
CryptographyClient.close()
CryptographyClient.decrypt()
CryptographyClient.encrypt()
CryptographyClient.from_jwk()
CryptographyClient.send_request()
CryptographyClient.sign()
CryptographyClient.unwrap_key()
CryptographyClient.verify()
CryptographyClient.wrap_key()
CryptographyClient.key_id
CryptographyClient.vault_url