Getting Started with Cloud Keys
Requirements: Cloud Keys
Cloud Keys provides easy-to-use components for creating and managing cloud-based key services including Amazon KMS, Azure Key Vault, Google KMS, and more. The toolkit consists of components for each individual service.
Contents
Amazon KMS
The AmazonKMS component 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 AccessKey and SecretKey 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 component 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.
Authentication
Authentication is performed using the AccessKey and SecretKey provided by Amazon.
kms = new Amazonkms();
kms.AccessKey = S3_ACCESS_KEY;
kms.SecretKey = S3_SECRET_KEY;
Creating a CMK
CMKs can be created using the CreateKey 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 UpdateKeyDescription method.
When a CMK will no longer be used, it can be scheduled for deletion using the ScheduleKeyDeletion 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 CancelKeyDeletion 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);
Managing Aliases
Aliases can be created and deleted using the CreateAlias and DeleteAlias 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.
Listing CMKs and Aliases
To list CMKs or aliases, use the ListKeys and ListAliases methods. For the former, the IncludeKeyDetails property can optionally be enabled to have the component 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);
}
Cryptographic Operations
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 ReEncrypt operations. CMKs with sign/verify usage can be used in Sign and Verify operations. To perform a cryptographic operation, use InputData, InputFile, or SetInputStream to supply the input data that should be processed. All operations will output the result data to OutputData, OutputFile, or SetOutputStream (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 GenerateDataKey and GenerateDataKeyPair 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.
Additional Functionality
The component also supports a variety of other functionality, including:
- Retrieval of an asymmetric CMK's public key with GetPublicKey.
- Enabling and disabling CMKs with SetKeyEnabled.
- Automatic rotation of CMKs with GetKeyRotationStatus and SetKeyRotationStatus.
- Encryption contexts for Encrypt, Decrypt, and ReEncrypt.
- And more!
Amazon Secrets
The AmazonSecrets component makes it easy to work with the Amazon Secrets Manager service in a secure manner using TLS. Amazon Secrets Manager allows you to securely store secrets (e.g., passwords, symmetric keys, etc.) in the cloud so that the aren't persisted locally. This component helps you to create, manage, and access those secrets.
To begin, register for an AWS account and obtain an AccessKey and SecretKey to use for authentication.
Resource Terminology
A secret in Amazon Secrets Manager is a container for one or more secret versions, which is where secret data is actually stored. Each secret version can have between zero and 20 staging labels attached to it at any given time.
A staging label is a simple string that can be used instead of a version Id to refer to a particular secret version when retrieving secret data. A staging label can only be attached to one version of a secret at any given time. The server ensures that there is always exactly one version of a secret with the special staging label AWSCURRENT, but otherwise you are free to apply any staging labels to any secret versions you choose.
Secret versions that do not have any staging labels attached to them are considered deprecated, and the server may delete them at any time without warning. Deprecated secret versions are not shown in a secret's version list unless explicitly asked for.
Authentication
Authentication is performed using the AccessKey and SecretKey provided by Amazon.
amazonsecrets = new Amazonsecrets();
amazonsecrets.AccessKey = S3_ACCESS_KEY;
amazonsecrets.SecretKey = S3_SECRET_KEY;
Managing Secrets
The CreateSecret method will create a new secret with an initial secret version that holds the specified secret data. To change a secret's data, create a new version of it using the CreateVersion method.
To retrieve a secret's data, call the GetSecret method, and specify the specific version (either by Id or using a staging label) whose data should be retrieved. If no particular version is specified, the version with the AWSCURRENT staging label is used.
Secrets that will no longer be used can be deleted using the DeleteSecret method, either immediately or after a waiting period. If a secret is scheduled for deletion later, then during said waiting period the deletion can be canceled using CancelDeletion.
// Creates a new secret with the textual data "Test123" named MySecret.
// The initial secret version will have only the "AWSCURRENT" staging label.
amazonsecrets.SecretString = "Test123";
amazonsecrets.CreateSecret("MySecret", "A description of my secret.");
// Creates a new secret version with the textual data "Cats456" and attaches
// the staging labels "AWSCURRENT" (which gets moved from the previous version)
// and "best-version" to it.
amazonsecrets.SecretString = "Cats456";
amazonsecrets.CreateVersion("MySecret", "AWSCURRENT,best-version");
// Downloads the latest secret version's data to a local file.
amazonsecrets.LocalFile = "C:\temp\secret.txt";
amazonsecrets.GetSecret("MySecret", "", "");
// Schedules the secret, and all its versions, for deletion after 10 days.
amazonsecrets.DeleteSecret("MySecret", 10);
// Cancels the scheduled deletion.
amazonsecrets.CancelDeletion("MySecret");
Listing Secrets
To list secrets, use the ListSecrets method. To list a secret's versions, use the ListVersions method.
// If there are many secrets to list, there may be multiple pages of results. This will
// cause all pages of results to be accumulated into the Secrets collection property.
do {
amazonsecrets.ListSecrets();
} while (!string.IsNullOrEmpty(amazonsecrets.SecretMarker));
// A similar thing applies to secret versions as well.
do {
amazonsecrets.ListVersions("MySecret");
} while (!string.IsNullOrEmpty(amazonsecrets.VersionMarker));
Additional Functionality
The component also supports a variety of other functionality, including:
- Adding, removing, and moving staging labels between secret versions using MoveStagingLabel.
- Retrieval of information for a single secret with GetSecretInfo.
- Random password generation using GenRandomPassword.
- And more!
Azure Keys
The AzureKeys component provides an easy-to-use interface for the key-related functionality of the Azure Key Vault service. Azure Key Vault allows you to works with a few different kinds of resources, one of which is asymmetric key pairs. This component helps you to create, manage, and use said key pairs (or just "keys", for short) for cryptographic operations. To work with "secrets" instead, refer to the AzureSecrets component.
To begin, register for an Azure account and create one or more Key Vaults via the Azure Portal. Set the Vault property to the name of the vault you wish to work with.
Authentication
This component supports authentication via OAuth 2.0. First, perform OAuth authentication using the OAuth component 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.
Managing Keys
Keys can be created using the CreateKey method. A key's name and type (i.e., whether it is RSA or EC, and its size or curve, respectively) must be set at the time of creation, and cannot be changed later. A list of cryptographic operations that the key is valid for must also be set, but can be changed at any time using the UpdateKey. If a key with the specified name already exists, a new version of it is created; this makes it easy to "rotate" a key.
When a key will no longer be used, it can be deleted using the DeleteKey method. However, the key will only be soft-deleted; by default, Azure will permanently delete it after the waiting period configured for the vault. During this waiting period, the soft-deleted key may be recovered using RecoverKey, or permanently deleted using PurgeKey (assuming the currently-authenticated user has the permissions to do so).
azurekeys.CreateKey("mykey", "RSA_2048", "encrypt,decrypt,sign,verify,wrapKey,unwrapKey");
// ... Some time later, when the key is no longer needed ...
azurekeys.DeleteKey("mykey");
// At this point, the key is only soft-deleted. It could be recovered...
azurekeys.RecoverKey("mykey");
// ...or permanently deleted.
azurekeys.PurgeKey("mykey");
Listing Keys and Key Details
To list keys, use the ListKeys method. This method is also used to list soft-deleted keys if the GetDeleted configuration setting has been enabled first. To list a key's versions, use the ListVersions method. (You cannot list a deleted key's versions.) In all cases, the IncludeKeyDetails property can optionally be enabled to have the component attempt to retrieve the full information for each key (Azure leaves out certain fields by default when listing).
// If there are many keys 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 {
azurekeys.ListKeys();
} while (!string.IsNullOrEmpty(azurekeys.KeyMarker));
// A similar thing applies to key versions as well.
do {
azurekeys.ListVersions("mykey");
} while (!string.IsNullOrEmpty(azurekeys.VersionMarker));
Cryptographic Operations
Depending on a key's "key ops" list, it can be used to perform different cryptographic operations. Keys with the encrypt and decrypt ops can be used in Encrypt and Decrypt operations. Keys with the sign and verify ops can be used in Sign and Verify. Finally, keys with the wrapKey and unwrapKey ops can be used in WrapKey and UnwrapKey operations (which are just like encryption and decryption, but which are intended to be used for wrapping a symmetric key, and which require different permissions to call successfully).
To perform a cryptographic operation, use InputData, InputFile, or SetInputStream to supply the input data that should be processed. All operations will output the result data to OutputData, OutputFile, or SetOutputStream (except Verify; refer to its documentation for more information).
azurekeys.CreateKey("mykey", "RSA_2048", "encrypt,decrypt");
azurekeys.InputData = "Test123";
azurekeys.OutputFile = "C:/temp/enc.dat";
azurekeys.Encrypt("mykey", "RSA-OAEP-256");
azurekeys.InputFile = "C:/temp/enc.dat";
azurekeys.OutputFile = ""; // So that the data will be output to the OutputData property.
azurekeys.Decrypt("mykey", "RSA-OAEP-256");
Additional Functionality
The component also supports a variety of other functionality, including:
- Retrieval of a single key's information (including public key) with GetKeyInfo.
- Enabling and disabling keys with SetKeyEnabled.
- Tagging support using AddTag and the Tags collection.
- Secure key backup and restoration using BackupKey and RestoreKey.
- And more!
Azure Secrets
The AzureSecrets component provides an easy-to-use interface for the secret-related functionality of the Azure Key Vault service. Azure Key Vault allows you to work with a few different kinds of resources, one of which is secrets (e.g., passwords, symmetric keys, etc.). This component helps you to create and manage said secrets. To work with asymmetric key pairs instead, refer to the AzureKeys component.
To begin, register for an Azure account and create one or more Key Vaults via the Azure Portal. Set the Vault property to the name of the vault you wish to work with.
Authentication
This component supports authentication via OAuth 2.0. First, perform OAuth authentication using the OAuth component 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.
Managing Secrets
Secrets can be created using the CreateSecret method. A secret's name must be set at the time of creation, and cannot be changed later. The secret's value and, optionally, content type must also be set, but can be changed at any time. To change a secret's value, create a new version of it using the CreateSecret method (which will always create a new version if a secret with the specified name already exists); to change a secret's content-type, use the UpdateSecret method.
To retrieve a secret and its information, use the GetSecret method.
When a secret will no long be used, it can be deleted using the DeleteSecret method. However, the secret will only be soft-deleted; by default, Azure will permanently delete it after the waiting period configured for the vault. During this waiting period, the soft-deleted secret may be recovered using RecoverSecret, or permanently deleted using PurgeSecret (assuming the currently-authenticated user has the permissions to do so).
// Create a secret.
azuresecrets.SecretData = "Test123";
azuresecrets.CreateSecret("mysecret", "text/plain");
// Download the secret value to a local file.
azuresecrets.LocalFile = "C:\temp\secret.txt";
azuresecrets.GetSecret("mysecret");
// Create a new version of the secret.
azuresecrets.SecretData = "Cats456";
azuresecrets.CreateSecret("mysecret", "text/plain");
// ... Some time later, when the secret is no longer needed ...
azuresecrets.DeleteSecret("mysecret");
// At this point, the secret is only soft-deleted. It could be recovered...
azuresecrets.RecoverSecret("mysecret");
// ...or permanently deleted.
azuresecrets.PurgeSecret("mysecret");
Listing Secrets
To list secrets, use the ListSecrets method. This method is also used to list soft-deleted secrets if the GetDeleted configuration setting has been enabled first. To list a secret's versions, use the ListVersions method. (You cannot list a deleted secret's versions.)
// If there are many secrets to list, there may be multiple pages of results. This will
// cause all pages of results to be accumulated into the Secrets collection property.
do {
azuresecrets.ListSecrets();
} while (!string.IsNullOrEmpty(azuresecrets.SecretMarker));
// A similar thing applies to secret versions as well.
do {
azuresecrets.ListVersions("mysecret");
} while (!string.IsNullOrEmpty(azuresecrets.VersionMarker));
Additional Functionality
The component also supports a variety of other functionality, including:
- Enabling and disabling secrets with SetSecretEnabled.
- Tagging support using AddTag and the Tags collection.
- Secure secret backup and restoration using BackupSecret and RestoreSecret.
- And more!
Google KMS
The GoogleKMS component 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'.
Authentication
This component supports authentication via OAuth 2.0. First, perform OAuth authentication using the OAuth component 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.
Managing Keys
First, select which key ring the component 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");
Listing Keys and Key Details
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);
}
Cryptographic Operations
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, InputFile, or SetInputStream to supply the input data that should be processed. All operations will output the result data to OutputData, OutputFile, or SetOutputStream (except Verify; refer to its documentation for more information).
Note that Google does not support server-side asymmetric encryption or asymmetric verification. The component 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");
Additional Functionality
The component also supports a variety of other functionality, including:
- Retrieval of a single resource's information with GetKeyRingInfo, GetKeyInfo, or GetVersionInfo.
- Getting an asymmetric key's public key using GetPublicKey.
- Label support using AddLabel and the Labels collection.
- Updating key information with UpdateKey and SetPrimaryVersion.
- And more!
Google Secrets
The GoogleSecrets component provides an easy-to-use interface for the Google Cloud Secret Manager service. Google Secret Manager allows you to securely store secrets (e.g., passwords, symmetric keys, etc.) in the cloud so that they aren't persisted locally. This component helps you to create, manage, and access these secrets.
To begin, register for a Google Cloud account. Set the GoogleProjectId property to your full Google Cloud project Id.
Authentication
This component supports authentication via OAuth 2.0. First, perform OAuth authentication using the OAuth component 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.
Managing Secrets
In Google Secret Manager, a secret is a container for one or more secret versions, which is where secret data is actually stored. The CreateSecret method will create a new secret and then add an initial secret version to it with the specified secret data. To change a secret's data, simply create a new version of it using the CreateVersion method. Each version of the secret receives a sequentially-assigned version Id, and the first version's Id is always 1.
To retrieve a secret's data, call the GetSecret method, and specify the specific version whose data should be retrieved (if no version is specified, the latest version's data is retrieved).
Secret versions that will no longer be used can have their data destroyed using the DestroyVersion method; the version itself will still exist, but its data will not. The DeleteSecret method can be used to completely delete a secret and all of its versions.
// Create a secret.
googlesecrets.SecretData = "Test123";
googlesecrets.CreateSecret("MySecret");
// Create a new version of the secret.
googlesecrets.SecretData = "Cats456";
googlesecrets.CreateVersion("MySecret");
// Download the latest secret version's data to a local file.
googlesecrets.LocalFile = "C:\temp\secret.txt";
googlesecrets.GetSecret("MySecret", "");
// Download a previous version's data to a local file.
googlesecrets.LocalFile = "C:\temp\oldsecret.txt";
googlesecrets.GetSecret("MySecret", "1");
// Destroy an old secret version's data.
googlesecrets.DestroyVersion("MySecret", "1");
// Completely delete a secret, and all of its versions.
googlesecrets.DeleteSecret("MySecret");
Listing Secrets
To list secrets, use the ListSecrets method. To list a secret's versions, use the ListVersions method.
// If there are many secrets to list, there may be multiple pages of results. This will
// cause all pages of results to be accumulated into the Secrets collection property.
do {
googlesecrets.ListSecrets();
} while (!string.IsNullOrEmpty(googlesecrets.SecretMarker));
// A similar thing applies to secret versions as well.
do {
googlesecrets.ListVersions("MySecret");
} while (!string.IsNullOrEmpty(googlesecrets.VersionMarker));
Additional Functionality
The component also supports a variety of other functionality, including:
- Enabling and disabling secret versions with SetVersionEnabled
- Retrieval of information for a single secret or secret version with GetSecretInfo and GetVersionInfo.
- Label support using AddLabel, UpdateSecretLabels, and the Labels collection.
- And more!
We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.