GoogleKMS Class

Properties   Methods   Events   Configuration Settings   Errors  

The GoogleKMS class provides an easy-to-use interface for the Google Cloud Key Management Service.

Class Name

CloudKeys_GoogleKMS

Procedural Interface

 cloudkeys_googlekms_open();
 cloudkeys_googlekms_close($res);
 cloudkeys_googlekms_register_callback($res, $id, $function);
 cloudkeys_googlekms_get_last_error($res);
 cloudkeys_googlekms_get_last_error_code($res);
 cloudkeys_googlekms_set($res, $id, $index, $value);
 cloudkeys_googlekms_get($res, $id, $index);
 cloudkeys_googlekms_do_addlabel($res, $name, $value);
 cloudkeys_googlekms_do_addqueryparam($res, $name, $value);
 cloudkeys_googlekms_do_canceldestruction($res, $keyname, $versionid);
 cloudkeys_googlekms_do_config($res, $configurationstring);
 cloudkeys_googlekms_do_createkey($res, $keyname, $purpose, $algorithm, $usehsm);
 cloudkeys_googlekms_do_createkeyring($res);
 cloudkeys_googlekms_do_createversion($res, $keyname);
 cloudkeys_googlekms_do_decrypt($res, $keyname, $versionid);
 cloudkeys_googlekms_do_destroyversion($res, $keyname, $versionid);
 cloudkeys_googlekms_do_doevents($res);
 cloudkeys_googlekms_do_encrypt($res, $keyname, $versionid);
 cloudkeys_googlekms_do_getkeyinfo($res, $keyname);
 cloudkeys_googlekms_do_getkeyringinfo($res);
 cloudkeys_googlekms_do_getpublickey($res, $keyname, $versionid);
 cloudkeys_googlekms_do_getversioninfo($res, $keyname, $versionid);
 cloudkeys_googlekms_do_listkeyrings($res);
 cloudkeys_googlekms_do_listkeys($res);
 cloudkeys_googlekms_do_listversions($res, $keyname);
 cloudkeys_googlekms_do_reset($res);
 cloudkeys_googlekms_do_sendcustomrequest($res, $httpmethod, $keyname, $versionid, $action);
 cloudkeys_googlekms_do_setprimaryversion($res, $keyname, $versionid);
 cloudkeys_googlekms_do_setversionenabled($res, $keyname, $versionid, $enabled);
 cloudkeys_googlekms_do_sign($res, $keyname, $versionid, $algorithm, $isdigest);
 cloudkeys_googlekms_do_updatekey($res, $keyname, $templatealgorithm, $updatelabels);
 cloudkeys_googlekms_do_verify($res, $keyname, $versionid, $isdigest);

Remarks

The GoogleKMS class makes it easy to work with the Google Cloud Key Management Service (KMS) in a secure manner using TLS. Google KMS allows you to create and manage key rings that contain symmetric and asymmetric keys. Each key has one or more versions which can be used for cryptographic operations.

To begin, register for a Google Cloud account. Set the GoogleProjectId property to your full Google Cloud project Id, and set the Location property to the Google Cloud location you'd like to make requests against (by default, the us multi-regional location is used). Note that each location's resources are completely separate from the others'.

This class supports authentication via OAuth 2.0. First, perform OAuth authentication using the OAuth class or a separate process. Once complete you should have an authorization string which looks like:

Bearer ya29.AHES6ZSZEJzATdZYjeihDn5W-VrXSsxEZu5p0pclxGdKKQ
Assign this value to the Authorization property before attempting any operations. Consult the documentation for the service for more information about supported scope values and more details on OAuth authentication.

Using the Class

First, select which key ring the class should interact with using the KeyRing property. If the selected key ring does not yet exist, use the CreateKeyRing method to create it. Note that key rings cannot be deleted later, and therefore key ring names can never be reused within a given Location (unless you create a new Google Cloud project).

Once a key ring has been selected (and created, if necessary), keys can be created in it using the CreateKey method. A key consists of one or more key versions (which themselves can be thought of as distinct resources), each of which has its own cryptographic material. Symmetric keys have a primary version which is used when encrypting data. Asymmetric keys do not have a primary version; a specific version must always be targeted.

When a key is created, a single key version is automatically created for it as well (and for symmetric keys, this becomes the primary version). Additional key versions can be created using the CreateVersion method. Each key version receives a sequentially-assigned version Id, and the first version's Id is always 1. As will become apparent, most operations are performed with key versions, not keys.

googlekms.KeyRing = "MyKeyRing";
googlekms.CreateKeyRing();

// When a key is created, you specify its name, purpose, algorithm, and protection level.
// Refer to the CreateKey method's documentation for more information.
googlekms.CreateKey("MyKey", 1, "GOOGLE_SYMMETRIC_ENCRYPTION", false);

// When a new version is created, the algorithm and protection level are reused.
googlekms.CreateVersion("MyKey");

Like key rings, keys and key versions cannot be deleted. However, a key version can be disabled, or its cryptographic material can be destroyed, making it permanently unusable. To enable or disable a key version, use the SetVersionEnabled method; to destroy a key version's cryptographic material, use the DestroyVersion method. Note that the latter doesn't destroy the cryptographic material immediately; instead, it schedules it for destruction 24 hours from the time of the call. The CancelDestruction method can be called within this waiting period to cancel the destruction.

// Disable a key version to make it unusable until it is re-enabled.
googlekms.SetVersionEnabled("MyKey", "7", false);

// Destroy a key version's cryptographic material to make it permanently unusable.
googlekms.DestroyVersion("MyKey", "7");

// The destruction takes place after a 24 hour waiting period; it can be canceled during that period.
// If destruction is canceled, the key version is always placed into a disabled state.
googlekms.CancelDestruction("MyKey", "7");

To list key rings, keys, or key versions, use the ListKeyRings, ListKeys, or ListVersions method. If there are multiple pages of results when listing a resource, the appropriate marker property will be populated, and all pages of results can be accumulated by continuing to call the relevant listing method until the marker property is empty.

do {
  googlekms.ListKeyRings();
} while (!string.IsNullOrEmpty(googlekms.KeyRingMarker));
foreach (GoogleKeyRing keyring in googlekms.KeyRings) {
  Console.WriteLine(keyring.Name);
}

googlekms.KeyRing = "MyKeyRing";
do {
  googlekms.ListKeys();
} while (!string.IsNullOrEmpty(googlekms.KeyMarker));
foreach (GoogleKey key in googlekms.Keys) {
  Console.WriteLine(key.Name);
}

do {
  googlekms.ListKeyVersions("MyKey");
} while (!string.IsNullOrEmpty(googlekms.VersionMarker));
foreach (GoogleKeyVersion version in googlekms.Versions) {
  Console.WriteLine(version.Name + " " + version.VersionId);
}

Depending on a key's purpose, it can be used to perform different cryptographic operations. Keys whose purpose is encryption/decryption can be used in Encrypt and Decrypt operations. Keys whose purpose is sign/verify can be used in Sign and Verify operations. To perform a cryptographic operation, use InputData or InputFile to supply the input data that should be processed. All operations will output the result data to OutputData or OutputFile (except Verify; refer to its documentation for more information).

Note that Google does not support server-side asymmetric encryption or asymmetric verification. The class performs these operations locally as a convenience to account for this.

// Create an asymmetric key whose purpose is encryption/decryption.
googlekms.CreateKey("MyAsymmEncKey", 3, "RSA_DECRYPT_OAEP_3072_SHA256", false);

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

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

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.

AdditionalDataAdditional data to send when performing symmetric encryption or decryption.
AuthorizationOAuth 2.0 Authorization Token.
FirewallAutoDetectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallTypeThis property determines the type of firewall to connect through.
FirewallHostThis property contains the name or IP address of firewall (optional).
FirewallPasswordThis property contains a password if authentication is to be used when connecting through the firewall.
FirewallPortThis property contains the TCP port for the firewall Host .
FirewallUserThis property contains a user name if authentication is to be used connecting through a firewall.
GoogleProjectIdThe Id of the Google Cloud project to make requests against.
IdleThe current status of the class.
InputDataThe data to process.
InputFileThe file whose data should be processed.
KeyMarkerA marker indicating what page of keys to return next.
KeyRingSelects a key ring for the class to interact with.
KeyRingMarkerA marker indicating what page of key rings to return next.
KeyRingCountThe number of records in the KeyRing arrays.
KeyRingCreationDateThe key ring's creation date.
KeyRingNameThe name of the key ring.
KeyCountThe number of records in the Key arrays.
KeyCreationDateThe key's creation date.
KeyNameThe name of the key.
KeyNextRotateDateThe key's next rotation date.
KeyPrimaryVersionThe Id of the key's primary version.
KeyPurposeThe key's purpose.
KeyRotationPeriodThe key's rotation period.
KeyTemplateAlgorithmThe algorithm to use when new versions of the key are created.
KeyTemplateProtectionLevelThe protection level to use when new versions of the key are created.
LabelCountThe number of records in the Label arrays.
LabelNameThe name of the label.
LabelValueThe value of the label.
LocalHostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
LocationThe Google Cloud location to make requests against.
OtherHeadersOther headers as determined by the user (optional).
OutputDataThe output data.
OutputFileThe file to which output data should be written.
OverwriteWhether the output file should be overwritten if necessary.
ParsedHeaderCountThe number of records in the ParsedHeader arrays.
ParsedHeaderFieldThis property contains the name of the HTTP header (same case as it is delivered).
ParsedHeaderValueThis property contains the header contents.
ProxyAuthSchemeThis property is used to tell the class which type of authorization to perform when connecting to the proxy.
ProxyAutoDetectThis property tells the class whether or not to automatically detect and use proxy system settings, if available.
ProxyPasswordThis property contains a password if authentication is to be used for the proxy.
ProxyPortThis property contains the TCP port for the proxy Server (default 80).
ProxyServerIf a proxy Server is given, then the HTTP request is sent to the proxy instead of the server otherwise specified.
ProxySSLThis property determines when to use SSL for the connection to the proxy.
ProxyUserThis property contains a user name, if authentication is to be used for the proxy.
PublicKeyThe public key of an asymmetric key pair.
PublicKeyAlgorithmThe algorithm of an asymmetric key pair.
QueryParamCountThe number of records in the QueryParam arrays.
QueryParamNameThe name of the query parameter.
QueryParamValueThe value of the query parameter.
SSLAcceptServerCertEncodedThe certificate (PEM/base64 encoded).
SSLCertEncodedThe certificate (PEM/base64 encoded).
SSLCertStoreThe name of the certificate store for the client certificate.
SSLCertStorePasswordIf 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.
SSLCertStoreTypeThe type of certificate store for this certificate.
SSLCertSubjectThe subject of the certificate used for client authentication.
SSLServerCertEncodedThe certificate (PEM/base64 encoded).
TimeoutA timeout for the class.
VersionMarkerA marker indicating what page of key versions to return next.
VersionCountThe number of records in the Version arrays.
VersionAlgorithmThe key version's algorithm.
VersionCreationDateThe key version's creation date.
VersionDestructionDateThe key version's destruction date.
VersionGenerationDateThe generation date of the key version's cryptographic material.
VersionNameThe name of the key.
VersionProtectionLevelThe key version's protection level.
VersionStateThe key version's state.
VersionVersionIdThe Id of the key version.

Method List


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

AddLabelAdds an item to the Labels properties.
AddQueryParamAdds a query parameter to the QueryParams properties.
CancelDestructionCancels the destruction of a key version's cryptographic material.
ConfigSets or retrieves a configuration setting.
CreateKeyCreates a new key.
CreateKeyRingCreates a new key ring.
CreateVersionCreates a new key version.
DecryptDecrypts data using a key.
DestroyVersionSchedules the specified key version's cryptographic material for destruction.
DoEventsProcesses events from the internal message queue.
EncryptEncrypts data using a key.
GetKeyInfoGets information about a key.
GetKeyRingInfoGets information about a key ring.
GetPublicKeyRetrieves the public key of an asymmetric key pair.
GetVersionInfoGets information about a key version.
ListKeyRingsLists the key rings in the currently-selected location.
ListKeysLists the keys in the currently-selected key ring.
ListVersionsLists the key versions for the specified key.
ResetResets the class to its initial state.
SendCustomRequestSends a custom request to the server.
SetPrimaryVersionSets the primary version of a symmetric key.
SetVersionEnabledEnables or disables a key version.
SignSigns a message using a key.
UpdateKeyUpdates a key.
VerifyVerifies a digital signature using a key.

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.

EndTransferFired when a document finishes transferring.
ErrorInformation about errors during data delivery.
HeaderFired every time a header line comes in.
KeyListFires once for each key when listing keys.
KeyRingListFires once for each key ring when listing key rings.
LabelListFires once for each label returned when a key's information is retrieved.
LogFires once for each log message.
SSLServerAuthenticationFired after the server presents its certificate to the client.
SSLStatusShows the progress of the secure connection.
StartTransferFired when a document starts transferring (after the headers).
TransferFired while a document transfers (delivers document).
VersionListFires once for each key version when listing key versions.

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.
ForceSymmetricEncryptionWhether the Encrypt method should always perform symmetric encryption.
MaxKeyRingsThe maximum number of results to return when listing key rings.
MaxKeysThe maximum number of results to return when listing keys.
MaxVersionsThe maximum number of results to return when listing key versions.
MessageDigestThe message digest computed by the class during the last sign or verify operation, if any.
NextRotateDateThe next rotation date to send when creating or updating a key.
RawRequestReturns the data that was sent to the server.
RawResponseReturns the data that was received from the server.
RotationPeriodThe rotation period to send when creating or updating a key.
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 PHP Edition - Version 20.0 [Build 8157]