Cloud Keys 2020 Python Edition

Questions / Feedback?

AmazonKMS Class

Properties   Methods   Events   Configuration Settings   Errors  

The AmazonKMS class provides an easy-to-use interface for Amazon's Key Management Service.

Syntax

class cloudkeys.AmazonKMS

Remarks

The AmazonKMS class makes it easy to work with the Amazon Key Management Service (KMS) in a secure manner using TLS. Amazon KMS allows you to create, manage, and use customer master keys (CMKs) for cryptographic operations. You can also work with aliases, and generate data keys and data key pairs.

To begin, register for an AWS account and obtain an access_key and secret_key to use for authentication. Once one or more CMKs have been created, either via the AWS console (recommended) or this API, you'll be ready to start using the class to manage and use the CMKs.

Resource Terminology

As implied above, there are three kinds of resources associated with Amazon KMS. The primary resource type is the customer master key, or "CMK". CMKs can be symmetric or asymmetric, and can be used either for encryption and decryption, or signing and verification. CMKs themselves can never leave the Amazon cloud, they are used for server-side cryptographic operations only. This is a security feature, but it does mean that the amount of data that can be processed in a CMK-based cryptographic operation is relatively small.

To work around the small server-side cryptographic operation data limit, Amazon KMS also supports the generation of data keys (symmetric) and data key pairs (asymmetric), which can then be used outside of Amazon KMS in order to encrypt/decrypt and sign/verify larger amounts data. KMS itself only generates these keys, it does not track them or make use of them for cryptographic operations. However, it does encrypt the data key (or, for data key pairs, the private key) using a CMK when it is generated, which means that the key must be decrypted using a CMK each time it needs to be used. For more information, refer to Amazon's Envelope Encryption description, which details the many security benefits of this strategy.

The last resource is called an alias. Aliases provide friendly names for CMKs, which can otherwise only be identified by their Id or Amazon resource name (ARN). Since an alias is a standalone resource, it can be created and deleted without affecting the CMK it refers to. It can also be updated to refer to a different CMK at any time.

Note: CMKs and aliases are region-specific resources. That is, CMKs and aliases cannot be accessed or used outside of the region that they reside in.

Using the Class

CMKs can be created using the create_key method. A CMK's key spec (i.e., whether it is symmetric or asymmetric, and in the latter case, what kind of asymmetric) and usage (i.e., whether it is for encryption/decryption or signing/verification) must be set at the time of creation, and they cannot be changed later. A description of the CMK can also be provided when it is created, and can be changed at any time using the update_key_description method.

When a CMK will no longer be used, it can be scheduled for deletion using the schedule_key_deletion method. AWS requires that CMKs remain in a "pending deletion" state for at least seven days to help ensure that they are truly no longer needed. If at any time during the waiting period it is discovered that the CMK is still needed, the deletion can be canceled using the cancel_key_deletion method (CMKs cannot be used while they are pending deletion).

// The CreateKey method returns the Amazon resource name of the newly-created CMK.
string keyArn = kms.CreateKey("SYMMETRIC_DEFAULT", false, "Test key");

// ... Some time later ...

// Schedules the CMK for deletion in 15 days.
kms.ScheduleKeyDeletion(keyArn, 15);

Aliases can be created and deleted using the create_alias and delete_alias methods. Also, while aliases can be updated to refer to a different CMK at any time during their lifetime. Note that all alias names must begin with the prefix alias/ (but cannot begin with alias/aws/, which is a reserved prefix).

kms.CreateAlias("alias/MyTestKey", keyArn);
kms.UpdateAlias("alias/MyTestKey", otherKeyArn);
kms.DeleteAlias("alias/MyTestKey"); // Only deletes the alias; the CMK it refers to is unaffected.

To list CMKs or aliases, use the list_keys and list_aliases methods. For the former, the include_key_details property can optionally be enabled to have the class attempt to retrieve the full information for each CMK (Amazon only returns the CMK's ARN and Id while listing).

// If there are many CMKs to list, there may be multiple pages of results. This will
// cause all pages of results to be accumulated into the Keys collection property.
do {
  kms.ListKeys();
} while (!string.IsNullOrEmpty(kms.KeyMarker));

foreach (AWSKey key in kms.Keys) {
  Console.WriteLine(key.ARN);
}

Depending on a CMK's usage, it can be used to perform different cryptographic operations. CMKs with encryption/decryption usage can be used in encrypt, decrypt, and re_encrypt operations. CMKs with sign/verify usage can be used in sign and verify operations. To perform a cryptographic operation, use input_data or input_file to supply the input data that should be processed. All operations will output the result data to output_data or output_file (except verify; refer to its documentation for more information).

// Create an asymmetric CMK with encrypt/decrypt usage.
string keyArn = kms.CreateKey("RSA_4096", false, "Encryption Key #237");

// Encrypt the string "Test123" and write the encrypted data to an output file.
kms.InputData = "Test123";
kms.OutputFile = "C:/temp/enc.dat";
kms.Encrypt(keyArn, "RSAES_OAEP_SHA_256");

// ...Later, decrypt the data again.
kms.InputFile = "C:/temp/enc.dat";
kms.OutputFile = ""; // So that the data will be output to the OutputData property.
kms.Decrypt(keyArn, "RSAES_OAEP_SHA_256");

It's important to note that the amount of data that can be processed in server-side cryptographic operations is very small. For signing operations, it is limited to 4096 bytes; for encryption operations, the limit varies based on the selected CMK's key spec and the selected encryption algorithm (see the encrypt method's documentation for more information).

To work around this issue, Amazon KMS supports the generation of data keys and data key pairs (described above) which can be used locally to encrypt/decrypt or sign/verify large amounts of data. To generate a data key or a data key pair, call the generate_data_key and generate_data_key_pair methods.

// Generates a data key, including a plaintext copy.
// The encrypted copy is encrypted by the specified CMK.
kms.GenerateDataKey("AES_256", keyArn, true);

// The resulting information is stored in the following properties:
// kms.KeyData.ARN: The ARN of the CMK used to encrypt the data key.
// kms.KeyData.EncryptedKey: The encrypted copy of the data key.
// kms.KeyData.KeySpec: The spec of the generated data key.
// kms.KeyData.PlaintextKey: The plaintext copy of the data key (if it was requested).

// Generates a data key pair, including plaintext copy.
// The encrypted copy of the private key is encrypted by the specified CMK.
kms.GenerateDataKeyPair("ECC_NIST_P384", keyArn, true);

// The resulting information is stored in the following properties:
// kms.KeyData.ARN: The ARN of the CMK used to encrypt the data key pair's private key.
// kms.KeyData.EncryptedKey: The encrypted copy of the private key.
// kms.KeyData.KeySpec: The spec of the generated data key pair.
// kms.KeyData.PlaintextKey: The plaintext copy of the private key (if it was requested).
// kms.KeyData.PublicKey: The data key pair's public key.

The class also supports a variety of other functionality, including:

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

access_keyThe access key to use for authentication.
alias_countThe number of records in the Alias arrays.
alias_arnThe Amazon resource name (ARN) of the alias.
alias_key_idThe Id of the CMK that the alias is associated with.
alias_nameThe name of the alias.
alias_markerA marker indicating what page of aliases to return next.
encryption_context_countThe number of records in the EncryptionContext arrays.
encryption_context_nameThe name of the context item.
encryption_context_valueThe value of the context item.
firewall_auto_detectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
firewall_typeThis property determines the type of firewall to connect through.
firewall_hostThis property contains the name or IP address of firewall (optional).
firewall_passwordThis property contains a password if authentication is to be used when connecting through the firewall.
firewall_portThis property contains the TCP port for the firewall Host .
firewall_userThis property contains a user name if authentication is to be used connecting through a firewall.
idleThe current status of the class.
include_key_detailsWhether to attempt to retrieve full details when listing CMKs.
input_dataThe data to process.
input_fileThe file whose data should be processed.
key_data_algorithmsThe algorithms supported by the public key.
key_data_arnThe Amazon resource name (ARN) of the associated CMK.
key_data_encrypted_keyThe encrypted key or private key data.
key_data_for_signingWhether the public key is for signing or encryption.
key_data_key_specThe key spec of the downloaded key data.
key_data_plaintext_keyThe plaintext key or private key data.
key_data_public_keyThe public key.
key_markerA marker indicating what page of CMKs to return next.
key_countThe number of records in the Key arrays.
key_account_idThe Id of the AWS account that owns the CMK.
key_algorithmsA comma-separated list of algorithms that the CMK supports.
key_arnThe Amazon resource name (ARN) of the CMK.
key_aws_managedWhether the CMK is AWS-managed.
key_cloud_hsm_cluster_idThe Id of the CloudHSM cluster the CMK's key material resides in, if applicable.
key_creation_dateThe creation date of the CMK.
key_custom_key_store_idThe Id of the custom key store that the CMK resides in, if applicable.
key_deletion_dateThe date at which the CMK will be deleted, if applicable.
key_descriptionThe CMK's description.
key_enabledWhether the CMK is enabled.
key_expiration_dateThe date at which the CMK's key material will expire, if applicable.
key_for_signingWhether the CMK is for signing or encryption.
key_idThe Id of the CMK.
key_key_specThe key spec of the CMK.
key_originThe origin of the CMK's key material.
key_stateThe CMK's state.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
other_headersOther headers as determined by the user (optional).
output_dataThe output data.
output_fileThe file to which output data should be written.
overwriteWhether the output file should be overwritten if necessary.
parsed_header_countThe number of records in the ParsedHeader arrays.
parsed_header_fieldThis property contains the name of the HTTP header (same case as it is delivered).
parsed_header_valueThis property contains the header contents.
proxy_auth_schemeThis property is used to tell the class which type of authorization to perform when connecting to the proxy.
proxy_auto_detectThis property tells the class whether or not to automatically detect and use proxy system settings, if available.
proxy_passwordThis property contains a password if authentication is to be used for the proxy.
proxy_portThis property contains the TCP port for the proxy Server (default 80).
proxy_serverIf a proxy Server is given, then the HTTP request is sent to the proxy instead of the server otherwise specified.
proxy_sslThis property determines when to use SSL for the connection to the proxy.
proxy_userThis property contains a user name, if authentication is to be used for the proxy.
query_param_countThe number of records in the QueryParam arrays.
query_param_nameThe name of the query parameter.
query_param_valueThe value of the query parameter.
regionThe region that the class will make requests against.
secret_keyThe secret key to use for authentication.
ssl_accept_server_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_storeThe name of the certificate store for the client certificate.
ssl_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
ssl_cert_store_typeThe type of certificate store for this certificate.
ssl_cert_subjectThe subject of the certificate used for client authentication.
ssl_server_cert_encodedThe certificate (PEM/base64 encoded).
timeoutA timeout for the class.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

add_encryption_context_itemAdds an item to the EncryptionContext properties.
add_query_paramAdds a query parameter to the QueryParams properties.
cancel_key_deletionCancels the deletion of the specified CMK.
clear_key_dataClears information stored in the KeyData properties.
configSets or retrieves a configuration setting.
create_aliasCreates a new alias.
create_keyCreates a new CMK.
decryptDecrypts data using a CMK.
delete_aliasDeletes an alias.
do_eventsProcesses events from the internal message queue.
encryptEncrypts data using a CMK.
generate_data_keyGenerates a data key that can be used outside of Amazon KMS.
generate_data_key_pairGenerates a data key pair that can be used outside of Amazon KMS.
generate_random_bytesGenerates a cryptographically-secure random byte string.
get_key_infoGets information about a CMK.
get_key_rotation_statusRetrieves the key rotation status for a CMK.
get_public_keyRetrieves the public key of an asymmetric CMK.
list_aliasesLists aliases in the current account and region.
list_keysLists CMKs in the current account and region.
re_encryptDecrypts data using one CMK and re-encrypts it using another CMK.
resetResets the class to its initial state.
schedule_key_deletionSchedules the deletion of a CMK.
send_custom_requestSends a custom request to the server.
set_key_enabledEnables or disables a CMK.
set_key_rotation_statusEnables or disables automatic key rotation for a CMK.
signSigns a message using a CMK.
update_aliasUpdates an alias to refer to a different CMK.
update_key_descriptionUpdates a CMK's description.
verifyVerifies a digital signature using a CMK.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_alias_listFires once for each alias when listing aliases.
on_end_transferFired when a document finishes transferring.
on_errorInformation about errors during data delivery.
on_headerFired every time a header line comes in.
on_key_listFires once for each CMK when listing CMKs.
on_logFires once for each log message.
on_ssl_server_authenticationFired after the server presents its certificate to the client.
on_ssl_statusShows the progress of the secure connection.
on_start_transferFired when a document starts transferring (after the headers).
on_transferFired while a document transfers (delivers document).

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AccumulatePagesWhether the class should accumulate subsequent pages of results when listing them.
AWSProfileThe name of the AWS CLI profile that the class should use to obtain authentication and region information.
AWSProfileDirThe location of the AWS CLI credentials and config files.
CreateKeyPolicyThe key policy JSON to send when creating a new CMK.
CustomKeyStoreIdThe Id of the custom key store that the CMK should be created in.
MaxAliasesThe maximum number of results to return when listing aliases.
MaxKeysThe maximum number of results to return when listing CMKs.
MessageDigestThe message digest computed by the class during the last sign or verify operation, if any.
NewEncryptionContextThe new encryption context to use when re-encrypting data.
RawRequestReturns the data that was sent to the server.
RawResponseReturns the data that was received from the server.
SessionTokenThe session token to send in the request when using temporary credentials.
UseEC2RoleCredentialsWhether to authenticate requests with credentials obtained from the IAM role attached to the EC2 instance.
UseFIPSEndpointWhether to use the FIPs endpoint to communicate with the server.
XChildCountThe number of child elements of the current element.
XChildName[i]The name of the child element.
XChildXText[i]The inner text of the child element.
XElementThe name of the current element.
XParentThe parent of the current element.
XPathProvides a way to point to a specific element in the returned XML or JSON response.
XSubTreeA snapshot of the current element in the document.
XTextThe text of the current element.
AcceptEncodingUsed to tell the server which types of content encodings the client supports.
AllowHTTPCompressionThis property enables HTTP compression for receiving data.
AllowHTTPFallbackWhether HTTP/2 connections are permitted to fallback to HTTP/1.1.
AppendWhether to append data to LocalFile.
AuthorizationThe Authorization string to be sent to the server.
BytesTransferredContains the number of bytes transferred in the response data.
ChunkSizeSpecifies the chunk size in bytes when using chunked encoding.
CompressHTTPRequestSet to true to compress the body of a PUT or POST request.
EncodeURLIf set to true the URL will be encoded by the class.
FollowRedirectsDetermines what happens when the server issues a redirect.
GetOn302RedirectIf set to true the class will perform a GET on the new location.
HTTP2HeadersWithoutIndexingHTTP2 headers that should not update the dynamic header table with incremental indexing.
HTTPVersionThe version of HTTP used by the class.
IfModifiedSinceA date determining the maximum age of the desired document.
KeepAliveDetermines whether the HTTP connection is closed after completion of the request.
KerberosSPNThe Service Principal Name for the Kerberos Domain Controller.
LogLevelThe level of detail that is logged.
MaxRedirectAttemptsLimits the number of redirects that are followed in a request.
NegotiatedHTTPVersionThe negotiated HTTP version.
OtherHeadersOther headers as determined by the user (optional).
ProxyAuthorizationThe authorization string to be sent to the proxy server.
ProxyAuthSchemeThe authorization scheme to be used for the proxy.
ProxyPasswordA password if authentication is to be used for the proxy.
ProxyPortPort for the proxy server (default 80).
ProxyServerName or IP address of a proxy server (optional).
ProxyUserA user name if authentication is to be used for the proxy.
SentHeadersThe full set of headers as sent by the client.
StatusLineThe first line of the last response from the server.
TransferredDataThe contents of the last response from the server.
TransferredDataLimitThe maximum number of incoming bytes to be stored by the class.
TransferredHeadersThe full set of headers as received from the server.
TransferredRequestThe full request as sent by the client.
UseChunkedEncodingEnables or Disables HTTP chunked encoding for transfers.
UseIDNsWhether to encode hostnames to internationalized domain names.
UsePlatformHTTPClientWhether or not to use the platform HTTP client.
UserAgentInformation about the user agent (browser).
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
OpenSSLCADirThe path to a directory containing CA certificates.
OpenSSLCAFileName of the file containing the list of CA's trusted by your application.
OpenSSLCipherListA string that controls the ciphers to be used by SSL.
OpenSSLPrngSeedDataThe data to seed the pseudo random number generator (PRNG).
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertFilePathsThe paths to CA certificate files on Unix/Linux.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedProtocolReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
Cloud Keys 2020 Python Edition - Version 20.0 [Build 8157]