Introduction
IBM® Key Protect for IBM Cloud® helps you provision encrypted keys for apps across IBM Cloud. As you manage the lifecycle of your keys, you can benefit from knowing that your keys are secured by cloud-based FIPS 140-2 Level 3 hardware security modules (HSMs) that protect against the theft of information.
Key Protect provides a REST API that you can use with any programming language to store, retrieve, and generate encryption keys. For details about using Key Protect, see the IBM Cloud docs.
API endpoint
https://<region>.kms.cloud.ibm.com
Replace <region> with the prefix that represents the geographic area where
your Key Protect service instance resides.
For more information, see
Regions and locations.
The code examples on this tab use the client library that is provided for Go.
go get -u github.com/IBM/keyprotect-go-client
GitHub:
The code examples on this tab use the client library that is provided for NodeJS.
npm install @ibm-cloud/ibm-key-protect
GitHub:
The code examples on this tab use the client library that is provided for Python.
pip install -U keyprotect
GitHub:
The code examples on this tab use the client library that is provided for Java.
git clone https://github.com/IBM/keyprotect-java-client
cd keyprotect-java-client
mvn install
GitHub:
Authentication
To call each method, you'll need to be assigned a role that includes the required IAM actions. Each method lists the associated action. For more information about IAM actions and how they map to roles, see Managing access for Key Protect.
To work with the API, authenticate your app or service by including your IBM Cloud IAM access token and instance ID in API requests.
You can build your API request by pairing a
service endpoint
with your authentication credentials. For example, if you created a
Key Protect service instance for the
us-south region, use the following endpoint and API headers to browse keys in
your service:
curl -X GET \
https://us-south.kms.cloud.ibm.com/api/v2/keys \
-H "accept: application/vnd.ibm.collection+json" \
-H "authorization: Bearer <access_token>" \
-H "bluemix-instance: <instance_ID>"
Replace <access_token> with your Cloud IAM token, and <instance_ID> with the
IBM Cloud instance ID that identifies your
Key Protect service instance.
You can retrieve an access token by first creating an API key, and then exchanging your API key for a Cloud IAM token. For more information, see Retrieving an access token programmatically.
To find out more about setting up the Key Protect API, see Accessing the API.
IBM Cloud Identity and Access Management (IAM) is the primary method to
authenticate to the Key Protect API. The SDK
provides client config initialization method in which you will need to replace
<key_protect_url> with the appropriate service endpoint,
the <api_key> with the API key
associated with your application, and <instance_ID> with the IBM Cloud
instance ID that identifies your Key Protect
service instance.
The value kp.DefaultTokenURL for TokenURL defaults to the IAM production URL,
but you may need to alter the value to be associated with virtual private networks.
Use the client config options in the method to create a new
Key Protect client. The method handles the
authentication procedure with the provided API_KEY.
IBM Cloud Identity and Access Management (IAM) is the primary method to authenticate to the Key Protect API. The SDK provides a client config setup in which you will need to export environment variables to match the IBMCLOUD_API_KEY term with the API key associated with your service credentials, another term, IAM_AUTH_URL with the appropriate URL like 'https://iam.cloud.ibm.com/identity/token', another term, KP_SERVICE_URL with the endpoint, including the region, such as https://us-south.kms.cloud.ibm.com, and KP_INSTANCE_ID with the IBM Cloud instance ID that identifies your Key Protect service instance.
To retrieve your instance ID:
ibmcloud resource service-instance <instance_name> --output JSON
IBM Cloud Identity and Access Management (IAM) is the primary method to
authenticate to the Key Protect API. The SDK
provides a client config setup in which you will need to replace the
IBMCLOUD_API_KEY with the API key associated with your application, and
KP_INSTANCE_ID with the IBM Cloud instance ID that identifies your
Key Protect service instance.
IBM Cloud Identity and Access Management (IAM) is the primary method to
authenticate to the Key Protect API. The SDK
provides a client config setup in which you will need to replace the
IBMCLOUD_API_KEY with the API key associated with your application, and
KP_INSTANCE_ID with the IBM Cloud instance ID that identifies your
Key Protect service instance.
IBM Cloud Identity and Access Management (IAM) is the primary method to
authenticate to the Key Protect API.
The SDK provides a client config setup in which you will need to replace the
IAM_API_KEY with the API key associated with your application, IAM_AUTH_URL
with your Cloud IAM token,KEY_PROTECT_URL with a service endpoint, and
INSTANCE_ID with the IBM Cloud instance ID that identifies your
Key Protect service instance.
To retrieve your access token:
curl -X POST https://iam.cloud.ibm.com/identity/token -H "accept: application/json" -H "content-type: application/x-www-form-urlencoded" -d "grant_type=urn%3Aibm%3Aparams%3Aoauth%3Agrant-type%3Aapikey&apikey=<API_KEY>" > token.json
Replace <API_KEY> with your
service credentials.
Then use the full access_token value, prefixed by the _Bearer_token type, to
authenticate your API requests.
To retrieve your instance ID:
ibmcloud resource service-instance <instance_name> --output JSON
Replace <instance_name> with the unique alias that you assigned to your
Key Protect service instance. The GUID
value in the JSON output represents the instance ID for the service.
To authenticate to Key Protect API:
import (
"context"
"encoding/json"
"fmt"
kp "github.com/IBM/keyprotect-go-client"
)
func getConfigAPIKey() kp.ClientConfig {
return kp.ClientConfig{
BaseURL: <key_protect_url>,
APIKey: <api_key>,
TokenURL: kp.DefaultTokenURL,
InstanceID: <instance_ID>,
Verbose: kp.VerboseFailOnly,
}
}
func main() {
options := getConfigAPIKey()
api, err := kp.New(options, kp.DefaultTransport())
if err != nil {
fmt.Println("Error creating kp client")
return
}
}
To access the API through your service endpoint, you will need to use the following format.
API endpoint format:
https://<region>.kms.cloud.ibm.com
Replace <region> with the prefix that represents the geographic area where
your Key Protect service instance resides.
For more informaton, see
Regions and locations.
To retrieve your instance ID, run the following command using the CLI:
ibmcloud resource service-instance <instance_name> --output JSON
Replace <instance_name> with the unique alias that you assigned to your
Key Protect service instance. The GUID
value in the JSON output represents the <instance_ID> for the service.
To authenticate to Key Protect API:
const KeyProtectV2 = require('@ibm-cloud/ibm-key-protect/ibm-key-protect-api/v2');
const { IamAuthenticator } = require('@ibm-cloud/ibm-key-protect/auth');
// using external configuration of environment variables
const envConfigs = {
apiKey: process.env.IBMCLOUD_API_KEY,
iamAuthUrl: process.env.IAM_AUTH_URL,
serviceUrl: process.env.KP_SERVICE_URL,
bluemixInstance: process.env.KP_INSTANCE_ID,
};
// Create an IAM authenticator.
const authenticator = new IamAuthenticator({
apikey: envConfigs.apiKey,
url: envConfigs.iamAuthUrl,
});
// Construct the service client.
const keyProtectClient = new KeyProtectV2({
authenticator,
serviceUrl: envConfigs.serviceUrl,
});
For more information on the regional endpoint where your data can be accessed, see Regions and locations.
To authenticate to Key Protect API:
import os
import keyprotect
from keyprotect import bxauth
tm = bxauth.TokenManager(api_key=os.getenv("<IBMCLOUD_API_KEY>"))
kp = keyprotect.Client(
credentials=tm,
region="<region>",
service_instance_id=os.getenv("<KP_INSTANCE_ID>")
)
Replace <IBMCLOUD_API_KEY> with your
service credentials.
Replace <KP_INSTANCE_ID> with the UUID that identifies your
Key Protect instance.
To retrieve your instance ID:
ibmcloud resource service-instance <instance_name> --output JSON
Replace <region> with the prefix that represents the geographic area where
your Key Protect service instance resides.
For more information, see
Regions and locations.
To authenticate to Key Protect API:
import com.ibm.cloud.ibm_key_protect_api.v2.IbmKeyProtectApi;
import com.ibm.cloud.ibm_key_protect_api.v2.model.*;
import com.ibm.cloud.sdk.core.http.Response;
import com.ibm.cloud.sdk.core.security.*;
public class KPClient {
private static IbmKeyProtectApi testClient;
public static void main(String[] args) {
IamAuthenticator authenticator = new IamAuthenticator("<IAM_API_KEY>");
authenticator.setURL("<IAM_AUTH_URL>");
authenticator.validate();
testClient = new IbmKeyProtectApi("<INSTANCE_ID>", authenticator);
testClient.setServiceUrl("<KEY_PROTECT_URL>");
}
}
Replace <INSTANCE_ID> with the UUID that identifies your Key Protect instance.
Replace <IAM_API_KEY> with your service credentials.
Replace <IAM_AUTH_URL> with https://iam.cloud.ibm.com/identity/token.
Replace <KEY_PROTECT_URL> with the service endpoint for your instance that handles your requests.
To retrieve your instance ID, replace <instance_name> in the command as shown:
ibmcloud resource service-instance <instance_name> --output JSON
Your endpoint is specific to the geographic area where your Key Protect service instance resides. For more information, see Regions and locations.
Auditing
You can monitor API activity within your account. Whenever an API method is called, an event is generated that you can then track and audit. The specific event type is listed for each method that generates auditing events. For methods that don't list any events, no events are generated.
For more information about how to track Key Protect activity, see Auditing the events for Key Protect.
Error handling
The Key Protect service uses standard HTTP
response codes to indicate whether a method completed successfully. A 200
response always indicates success. A 400 type response is some sort of
failure, and a 500 type response usually indicates an internal system error.
| Status code | Description |
|---|---|
200 OK |
Everything worked as expected. |
201 OK |
Everything worked as expected; no content. |
400 Bad Request |
The request was unsuccessful; ensure no required parameters are missing. |
401 Unauthorized |
The parameters were valid but the request failed due insufficient permissions. |
404 Not Found |
The requested resource doesn't exist. |
410 Gone |
The requested resource was deleted and no longer exists. |
429 Too Many Requests |
Too many requests hit the API too quickly. |
500 Server Error |
Something went wrong on Key Protect's end. |
Metadata
When you create or store keys in Key Protect, you can attach key-value data to your resources for easy identification of your keys.
The name, description, and tag parameters are useful for storing
information on your resources. For example, you can store corresponding unique
identifiers from your app or system on a
Key Protect key.
To protect your privacy, do not store any personally identifiable information, such as your name or location, as metadata for your keys.
Pagination
Some API requests might return a large number of results. By specifying the
limit and offset parameters at query time, you can retrieve a subset of your
keys, starting with the offset value that you specify. For more information, see
Retrieving a subset of keys.
There are optional operations that can effect pagination and the resulting list of keys returned by the service. Some operations may still be in development, and will be listed as "Beta" while that is the case.
Search
When used, this operation performs a search, possibly limiting the number of keys returned. If you want to narrow the number of results returned by a search, try using one or a combination of the following values as a prefix for the term you wish to have searched:
not:when specified, inverts the logic the search uses (for example,not:foowill search for keys that have aliases or names that do not containfoo).escape:everything after this option is take as plaintext (example:escape:not:will search for keys that have an alias or name containing the substringnot:).exact:only looks for exact matches.alias:only looks for key aliases.name:only looks for key names.
The list of keys returned is sorted on id by default, if this parameter is not provided.
Sort
When used, this operation sorts the list of keys returned based on one or more key properties. The key properties that can be sorted at this time are:
idstateextractableimportedcreationDatelastUpdateDatelastRotateDatedeletionDateexpirationDate
The list of keys returned is sorted on id by default, if this parameter is not provided.
Rate Limiting
Rate limits for API requests are enforced on a per-service-instance basis. If the number of requests for a particular method and endpoint reaches the request limit within the specified time window, no further requests are accepted until the timer expires. After the timer expires, a new time window begins with the next accepted request.
An HTTP status code of 429 indicates that the rate limit has been exceeded.
Change log
Important changes, such as additions, updates, and breaking changes, are marked with a change notice in this reference.
New features will be initially released as "beta" implementations.
"Beta" means that the specification is subject to change, with limited support in different environments (from partial support to none at all, depending on the specifics), in order to test new features that are not yet stable for use in production environments.
As part of continued migration and improvement, the algorithmBitSize, algorithmMode,
algorithmType and algorithmMetadata fields are deprecated within the Key Protect API.
Key Protect announces several changes to both the structure and to particular names of certain events to better conform with IBM naming conventions.
The alias parameter in the event generated with a key alias added to a key at creation time is being moved from the response data section to the request data section.
Also, to better conform with IBM standards, the names of certain events are changing.
| Old event name | New event name |
|---|---|
| kms.secrets.eventack | kms.secrets-event.ack |
| kms.secrets.readmetadata | kms.secrets-metadata.read |
| kms.secrets.listkeyversions | kms.secrets-key-versions.list |
| kms.secrets.defaultalias | kms.secrets-alias.default |
| kms.secrets.createalias | kms.secrets-alias.create |
| kms.secrets.deletealias | kms.secrets-alias.delete |
| kms.importtoken.create | kms.import-token.create |
| kms.importtoken.default | kms.import-token.default |
| kms.importtoken.read | kms.import-token.read |
| kms.instancepolicies.write | kms.instance-policies.write |
| kms.instancepolicies.default | kms.instance-policies.default |
| kms.instancepolicies.read | kms.instance-policies.read |
| kms.instance.readallowedipport | kms.instance-allowed-ip-port.read |
| kms.instance.readipwhitelistport | kms.instance-ip-whitelist-port.read |
| kms.keyrings.create | kms.key-rings.create |
| kms.keyrings.delete | kms.key-rings.delete |
| kms.keyrings.list | kms.key-rings.list |
| kms.keyrings.default | kms.key-rings.default |
| kms.governance.configread | kms.governance-config.read |
Methods
Create a key
Creates a new key with specified key material.
Key Protect designates the resource as either a root key or a standard
key based on the extractable value that you specify. A successful
POST /keys operation adds the key to the service and returns the
details of the request in the response entity-body, if the Prefer header
is set to return=representation.
POST /api/v2/keys
Request
Custom Headers
The IBM Cloud instance ID that identifies your Key Protect service instance.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The v4 UUID used to correlate and track transactions.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$Alters server behavior for POST or DELETE operations. A header with
return=minimalcauses the service to return only the key identifier as metadata. A header containingreturn=representationreturns both the key material and metadata in the response entity-body. If the key has been designated as a root key, the system cannot return the key material. Note: During POST operations, Key Protect may not immediately return the key material due to key generation time. To retrieve the key material, you can perform a subsequentGET /keys/{id}request.Allowable values: [
return=representation,return=minimal]Possible values: 14 ≤ length ≤ 21
The ID of the key ring that the specified key belongs to. When the header is not specified, Key Protect will perform a key ring lookup. For a more optimized request, specify the key ring on every call. The key ring ID of keys that are created without an
X-Kms-Key-Ringheader is:default.Possible values: 2 ≤ length ≤ 100, Value must match regular expression
^[a-zA-Z0-9-]*$Default:
default
The base request for creating a new key.
{
"metadata": {
"collectionType": "application/vnd.ibm.kms.key+json",
"collectionTotal": 1
},
"resources": [
{
"type": "application/vnd.ibm.kms.key+json",
"name": "Root-key",
"description": "A Key Protect key",
"extractable": false
}
]
}A collection of resources.
Possible values: number of items = 1
curl -X POST https://<region>.kms.cloud.ibm.com/api/v2/keys -H 'authorization: Bearer <IAM_token>' -H 'bluemix-instance: <instance_ID>' -H 'content-type: application/vnd.ibm.kms.key+json' -d '{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 1 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "name": "Root-key", "description": "A Key Protect key", "extractable": false } ] }'
package main import ( "context" "encoding/json" "fmt" kp "github.com/IBM/keyprotect-go-client" ) func main() { // Initialize the Key Protect client as specified in Authentication // Method CreateKeyWithAliases supports creating key with aliases. To provide alias names pass array of strings to the method // otherwise pass nil. rootkey, err := api.CreateKeyWithAliases(context.Background(), <key_name>, <expiration_date>, <extractable>, <aliases>) if err != nil { fmt.Println("Error while creating key: ", err) return } b, _ := json.MarshalIndent(rootkey, "", " ") fmt.Println(string(b)) }
// Initialize the Key Protect client as specified in Authentication // Define the key parameters const body = { metadata: { collectionType: 'application/vnd.ibm.kms.key+json', collectionTotal: 1, }, resources: [ { type: 'application/vnd.ibm.kms.key+json', name: 'nodejsKey', extractable: false, }, ], }; const createParams = Object.assign({}, envConfigs); createParams.body = body; const response = keyProtectClient.createKey(createParams); const keyId = response.result.resources[0].id; console.log('Key created, id is: ' + keyId);
import os import keyprotect from keyprotect import bxauth # Initialize the Key Protect client as specified in Authentication key = kp.create(name="<key_name>") print("Created key '%s'" % key["id"])
// payload is null if not an imported key // payload should be base64 encoded string // notRootKey is false if this is a root key public static String createKey(String keyName, String keyDescription, String payload, boolean notRootKey) { InputStream inputstream = null; CreateKeyOptions createKeyOptionsModel = null; try { // build json format input stream JsonObjectBuilder resourceObjectBuilder = Json.createObjectBuilder() .add("name", keyName) .add("extractable", notRootKey) .add("description", keyDescription); // imported key if (payload != null) { resourceObjectBuilder.add("payload", payload); } JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder() .add("metadata", Json.createObjectBuilder() .add("collectionType", "application/vnd.ibm.kms.key+json") .add("collectionTotal", 1)) .add("resources", Json.createArrayBuilder() .add(resourceObjectBuilder)); JsonObject jsonObject = jsonObjectBuilder.build(); inputstream = new ByteArrayInputStream(jsonObject.toString().getBytes()); createKeyOptionsModel = new CreateKeyOptions.Builder() .bluemixInstance("<instance_id>") .createKeyOneOf(inputstream) .prefer("return=representation") .build(); } catch(ClassCastException e) { System.out.println("Error: " + e.toString()); return "failed to create key"; } Response<Key> response = testClient.createKey(createKeyOptionsModel).execute(); List<KeyWithPayload> key = response.getResult().getResources(); return key.toString(); }
Response
Properties associated with a key response.
A collection of resources.
Possible values: number of items = 1
Status Code
The key was successfully created.
The key is missing a required field.
Your credentials are invalid or do not have the necessary permissions to make this request. Verify that the given IBM Cloud access token and instance ID are correct. If the error persists, contact the account owner to check your permissions.
Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. Learn more.
There are three possible causes for HTTP 404 while trying to create a key, specifying a reason code (resouces[0].reasons[0].code) as follows:
KEY_RING_NOT_FOUND_ERR: The key cannot be created because the key ring does not exist. Note the default key ring name is "default."
INSTANCE_NOT_FOUND_ERR: The key cannot be created because the instance does not exist.
IMPORT_TOKEN_NOT_FOUND_ERR: The key cannot be created because the import token does not exist.
The import token that was used to encrypt this key has reached its
maxAllowedRetrievalsorexpirationDate, and it is no longer available for operations. To create a new import token, usePOST /import_token.In very rare cases, the import token may expire before its expiration time. Ensure that your client application is configured with a retry mechanism for catching and responding to
409conflict exceptions.KEY_ALIAS_QUOTA_ERR: The alias quota for this key has been reached.
KEY_ALIAS_NOT_UNIQUE_ERR: One or more aliases are already associated with a key in the instance.
KEY_CREATE_IMPORT_ACCESS_ERR: KeyCreateImportAccess instance policy is enabled. Key Protect only permits the creation or import of keys in your Key Protect instance that follow the key creation and import settings listed on the keyCreateImportAccess policy.
IMPORT_TOKEN_EXPIRED_ERR: The key cannot be created because the import token has expired.
Too many requests. Wait a few minutes and try again.
IBM Key Protect is currently unavailable. Your request could not be processed. Try again later. If the problem persists, note the
correlation-IDin the response header and contact IBM Cloud support.
{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 1 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "id": "fadedbee-0000-0000-0000-1234567890ab", "name": "Root-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 1, "extractable": false, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:fadedbee-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "lastUpdateDate": "2000-03-21T00:00:00Z", "keyVersion": { "id": "fadedbee-0000-0000-0000-1234567890ab", "creationDate": "2000-03-21T00:00:00Z" }, "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": false } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Bad Request: The key is missing a required field." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Unauthorized: The user does not have access to the specified resource." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. [Learn more](/docs/key-protect?topic=key-protect-integrate-services#grant-access)" } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Conflict: The import token that was used to encrypt this key has reached its 'maxAllowedRetrievals' or 'expirationDate', and it is no longer available for key operations. To create a new import token, use 'POST /import_token'." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Too Many Requests: Wait a few minutes and try again." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Internal Server Error: IBM Key Protect is currently unavailable. Your request could not be processed. Try again later." } ] }
List keys
Retrieves a list of keys that are stored in your Key Protect service instance.
Important: When a user of Key Protect on Satellite views lists of keys through the IBM Console, or programmatically via this API, keys with "fine grain" permissions won't appear due to the manner in which the service aggregates the collection. While the user can still use the key resource, only by using the CLI or API and passing the specific key ID can a user access the metadata and other details of the key.
Note: GET /keys will not return the key material in the response
body. You can retrieve the key material for a standard key with a
subsequent GET /keys/{id} request.
GET /api/v2/keys
Request
Custom Headers
The IBM Cloud instance ID that identifies your Key Protect service instance.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The v4 UUID used to correlate and track transactions.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The ID of the target key ring. If unspecified, all resources in the instance that the caller has access to will be returned. When the header is specified, only resources within the specified key ring, that the caller has access to, will be returned. The key ring ID of keys that are created without an
X-Kms-Key-Ringheader is:default.Possible values: 2 ≤ length ≤ 100, Value must match regular expression
^[a-zA-Z0-9-]*$
Query Parameters
The number of keys to retrieve. By default,
GET /keysreturns the first 200 keys. To retrieve a different set of keys, uselimitwithoffsetto page through your available resources. The maximum value forlimitis 5,000. Usage: If you have 20 keys in your instance, and you want to retrieve only the first 5 keys, use../keys?limit=5.Possible values: 1 ≤ value ≤ 5000
Default:
200The number of keys to skip. By specifying
offset, you retrieve a subset of keys that starts with theoffsetvalue. Useoffsetwithlimitto page through your available resources. Usage: If you have 100 keys in your instance, and you want to retrieve keys 26 through 50, use../keys?offset=25&limit=25.Possible values: value ≥ 0
Default:
0The state of the keys to be retrieved. States must be a list of integers from 0 to 5 delimited by commas with no whitespace or trailing commas. Valid states are based on NIST SP 800-57. States are integers and correspond to the Pre-activation = 0, Active = 1, Suspended = 2, Deactivated = 3, and Destroyed = 5 values. Usage: If you want to retrieve active and deleted keys, use
../keys?state=1,5.Allowable values: [
0,1,2,3,5]Possible values: 0 ≤ number of items ≤ 5, 0 ≤ value ≤ 5
Default:
[0,1,2,3]The type of keys to be retrieved. Filters keys based on the
extractableproperty. You can use this query parameter to search for keys whose material can leave the service. If set totrue, standard keys will be retrieved. If set tofalse, root keys will be retrieved. If omitted, both root and standard keys will be retrieved. Usage: If you want to retrieve standard keys, use../keys?extractable=true.When provided, performs a search, possibly limiting the number of keys returned. Examples:
foobar- find keys where the name or any of its aliases containfoobar, case insentive (i.e. matchesxfoobar,Foobar).fadedbee-0000-0000-0000-1234567890ab(a valid key id) - find keys where the id the key isfadedbee-0000-0000-0000-1234567890ab, or the name or any of its aliases containfadedbee-0000-0000-0000-1234567890ab, case insentive.
May prepend with options:
not:= when specified, inverts matching logic (example:not:foowill search for keys that have aliases or names that do not containfoo)escape:= everything after this option is take as plaintext (example:escape:not:will search for keys that have an alias or name containing the substringnot:)exact:= only looks for exact matches
May prepend with search scopes:
alias:= search in key aliases for search queryname:= search in key names for search query
Examples:
not:exact:foobar/exact:not:foobar- find keys where the name nor any of its aliases are not exactlyfoobar(i.e. matchesxfoobar,bar,foo)exact:escape:not:foobar- find keys where the name or any of its aliases are exactlynot:foobarnot:alias:foobar/alias:not:foobar- find keys where any of its aliases do not containfoobarname:exact:foobar/exact:name:foobar- find keys where the name is exactlyfoobar
Note:
By default, if no scopes are provided, search will be performed in both
nameandaliasscopes.Search is only possible on a intial searchable space of at most 5000 keys. If the initial seachable space is greater than 5000 keys, the API returns HTTP 400 with the property resouces[0].reasons[0].code equals to 'KEY_SEARCH_TOO_BROAD'. Use the following filters to reduce the initial searchable space:
state(query parameter)extractable(query parameter)X-Kms-Key-Ring(HTTP header)
If the total intial searchable space exceeds the 5000 keys limit and when providing a fully specified key id or when searching within the
aliasscope, a lookup will be performed and if a key is found, the key will be returned as the only resource and in the response metadata the propertyincompleteSearchwill betrue.When providing a fully specified key id or when searching within the
aliasscope, a key lookup is performed in addition to the search. This means search will try to lookup a single key that is uniquely identified by the key id or provided alias, this key will be included in the response as the first resource, before other matches.Search scopes are disjunctive, behaving in an OR manner. When using more than one search scope, a match in at least one of the scopes will result in the key being returned.
Possible values: 0 ≤ length ≤ 256, Value must match regular expression
^.{0,256}$When provided, sorts the list of keys returned based on one or more key properties. To sort on a property in descending order, prefix the term with "-". To sort on multiple key properties, use a comma to separate each properties. The first property in the comma-separated list will be evaluated before the next. The key properties that can be sorted at this time are:
idstateextractableimportedcreationDatelastUpdateDatelastRotateDatedeletionDateexpirationDate
The list of keys returned is sorted on id by default, if this parameter is not provided.
Allowable values: [
id,state,extractable,imported,creationDate,lastUpdateDate,lastRotateDate,deletionDate,expirationDate]Possible values: 2 ≤ length ≤ 14
Default:
idWhen provided, returns the list of keys that match the queried properties. Each key property to be filtered on is specified as the property name itself, followed by an “=“ symbol, and then the value to filter on, followed by a space if there are more properties to filter only. Note: Anything between
<and>in the examples or descriptions represent placeholder to specify the value Basic format:= = - The value to filter on may contain a value related to the property itself, or an operator followed by a value accepted by the operator - Only one operator and value, or one value is accepted per property at a time Format with operator/value pair: = : Up to three of the same property may be specified at a time. The key properties that can be filtered at this time are: creationDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
deletionDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
expirationDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
extractable- Boolean true or false without quotes, case-insensitive
lastRotateDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
lastUpdateDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
state- A list of comma-separated integers with no space in between: 0,1,2,3,5 Comparison operations (operators) that can be performed on date values are:
lte:<value>Less than or equal to -lt:<value>Less than -gte:<value>Greater than or equal to -gt:<value>Greater than A special keyword for date,none(case-insensitive), may be used to retreive keys that do not have that property. This is useful forlastRotateDate, where only keys that have never been rotated can be retreived. Examples:lastRotateDate="2022-02-15T00:00:00Z"Filter keys that were last rotated on February 15, 2022 -lastRotateDate=gte:"2022-02-15T00:00:00Z"Filter keys that were last rotated after or on February 15, 2022 -lastRotateDate=gte:"2022-02-15T00:00:00Z" lastRotateDate=lt:"2022-03-15T00:00:00Z"Filter keys that were last rotated after or on February 15, 2022 but before (not including) March 15, 2022 -lastRotateDate="2022-02-15T00:00:00Z" state=0,1,2,3,5 extractable=falseFilter root keys that were last rotated on February 15, 2022, with any state Note: When you filter bystateorextractablein this query parameter, you will not be able to use the deprecatedstateorextractableindependent query parameter. You will get a 400 response code if you specify a value for one of the two properties in both this filter query parameter and the deprecated independent query of the same name (the same applies vice versa).
Possible values: 0 ≤ length ≤ 512, Value must match regular expression
^.{0,512}$
curl -X GET https://<region>.kms.cloud.ibm.com/api/v2/keys -H 'accept: application/vnd.ibm.kms.key+json' -H 'authorization: Bearer <IAM_token>' -H 'bluemix-instance: <instance_ID>'
package main import ( "context" "encoding/json" "fmt" kp "github.com/IBM/keyprotect-go-client" ) func main() { // Initialize the Key Protect client as specified in Authentication keys, err := api.GetKeys(context.Background(), <limit>, <offset>) if err != nil { fmt.Println("Error while retrieving keys: ", err) return } b, _ := json.MarshalIndent(keys, "", " ") fmt.Println(string(b)) }package main import ( "context" "encoding/json" "fmt" kp "github.com/IBM/keyprotect-go-client" ) func main() { // Initialize the Key Protect client as specified in Authentication limit := uint32(5) offset := uint32(0) extractable := false keyStates := []kp.KeyState{kp.KeyState(kp.Active), kp.KeyState(kp.Suspended)} listKeysOptions := &kp.ListKeysOptions{ Limit : &limit, Offset : &offset, Extractable : &extractable, State : keyStates, } keys, err := client.ListKeys(ctx, listKeysOptions) if err != nil { fmt.Println(err) } fmt.Println(keys) }package main import ( "context" "encoding/json" "fmt" kp "github.com/IBM/keyprotect-go-client" ) func main() { // Initialize the Key Protect client as specified in Authentication srtStr, _ := kp.GetKeySortStr(kp.WithCreationDate(), WithImportedDesc()) listKeysOptions := &kp.ListKeysOptions{ Sort:srtStr, } keys, err := client.ListKeys(ctx, listKeysOptions) if err != nil { fmt.Println(err) } fmt.Println(keys) }
import os import keyprotect from keyprotect import bxauth # Initialize the Key Protect client as specified in Authentication keys = kp.keys() for key in kp.keys(): print("%s\t%s" % (key["id"], key["name"]))
// Initialize the Key Protect client as specified in Authentication const response = keyProtectClient.getKeys(envConfigs); console.log('Get keys result:'); for (let resource of response.result.resources){ console.log(resource); }
public static List<KeyRepresentation> getKeys() { GetKeysOptions getKeysOptionsModel = new GetKeysOptions.Builder() .bluemixInstance("<instance_id>") .build(); Response<ListKeys> response = testClient.getKeys(getKeysOptionsModel).execute(); List<KeyRepresentation> keys = response.getResult().getResources(); return keys; }
Response
The base schema for listing keys.
The metadata that describes the list keys response
A collection of resources.
Possible values: 0 ≤ number of items ≤ 5000
Status Code
The list of keys was successfully retrieved.
If reason code (resouces[0].reasons[0].code) is present and is equal to 'KEY_SEARCH_TOO_BROAD', the total searchable space is more than 5000 keys. Try using a filter to reduce the seachable space.
Your credentials are invalid or do not have the necessary permissions to make this request. Verify that the given IBM Cloud access token and instance ID are correct. If the error persists, contact the account owner to check your permissions.
Too many requests. Wait a few minutes and try again.
IBM Key Protect is currently unavailable. Your request could not be processed. Try again later. If the problem persists, note the
correlation-IDin the response header and contact IBM Cloud support.
{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 2 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "id": "fadedbee-0000-0000-0000-1234567890ab", "name": "Root-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 1, "extractable": true, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:fadedbee-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "lastUpdateDate": "2000-03-21T00:00:00Z", "lastRotateDate": "2000-03-21T00:00:00Z", "keyVersion": { "id": "fadedbee-0000-0000-0000-1234567890ab", "creationDate": "2000-03-21T00:00:00Z" }, "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": false }, { "type": "application/vnd.ibm.kms.key+json", "id": "addedace-0000-0000-0000-1234567890ab", "name": "Standard-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 1, "extractable": true, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:addedace-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "lastUpdateDate": "2000-03-21T00:00:00Z", "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": false }, { "type": "application/vnd.ibm.kms.key+json", "id": "beadcafe-0000-0000-0000-1234567890ab", "name": "Deleted-Standard-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 5, "extractable": true, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:beadcafe-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "lastUpdateDate": "2000-03-21T00:00:00Z", "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": true, "deletionDate": "2000-03-21T00:00:00Z", "restoreAllowed": true, "restoreExpirationDate": "2000-03-21T00:00:00Z", "purgeAllowed": false, "purgeAllowedFrom": "2000-03-21T00:00:00Z", "purgeScheduledOn": "2000-03-21T00:00:00Z" } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Unauthorized: The user does not have access to the specified resource." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Too Many Requests: Wait a few minutes and try again." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Internal Server Error: IBM Key Protect is currently unavailable. Your request could not be processed. Try again later." } ] }
Retrieve key total
Returns the same HTTP headers as a GET request without returning the entity-body. This operation returns the number of keys in your instance in a header called Key-Total.
HEAD /api/v2/keys
Request
Custom Headers
The IBM Cloud instance ID that identifies your Key Protect service instance.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The v4 UUID used to correlate and track transactions.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The ID of the target key ring. If unspecified, all resources in the instance that the caller has access to will be returned. When the header is specified, only resources within the specified key ring, that the caller has access to, will be returned. The key ring ID of keys that are created without an
X-Kms-Key-Ringheader is:default.Possible values: 2 ≤ length ≤ 100, Value must match regular expression
^[a-zA-Z0-9-]*$
Query Parameters
The state of the keys to be retrieved. States must be a list of integers from 0 to 5 delimited by commas with no whitespace or trailing commas. Valid states are based on NIST SP 800-57. States are integers and correspond to the Pre-activation = 0, Active = 1, Suspended = 2, Deactivated = 3, and Destroyed = 5 values. Usage: If you want to retrieve active and deleted keys, use
../keys?state=1,5.Allowable values: [
0,1,2,3,5]Possible values: 0 ≤ number of items ≤ 5, 0 ≤ value ≤ 5
Default:
[0,1,2,3]The type of keys to be retrieved. Filters keys based on the
extractableproperty. You can use this query parameter to search for keys whose material can leave the service. If set totrue, standard keys will be retrieved. If set tofalse, root keys will be retrieved. If omitted, both root and standard keys will be retrieved. Usage: If you want to retrieve standard keys, use../keys?extractable=true.When provided, returns the list of keys that match the queried properties. Each key property to be filtered on is specified as the property name itself, followed by an “=“ symbol, and then the value to filter on, followed by a space if there are more properties to filter only. Note: Anything between
<and>in the examples or descriptions represent placeholder to specify the value Basic format:= = - The value to filter on may contain a value related to the property itself, or an operator followed by a value accepted by the operator - Only one operator and value, or one value is accepted per property at a time Format with operator/value pair: = : Up to three of the same property may be specified at a time. The key properties that can be filtered at this time are: creationDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
deletionDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
expirationDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
extractable- Boolean true or false without quotes, case-insensitive
lastRotateDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
lastUpdateDate- Date in RFC 3339 format in double-quotes: “2000-03-21T00:00:00Z”
state- A list of comma-separated integers with no space in between: 0,1,2,3,5 Comparison operations (operators) that can be performed on date values are:
lte:<value>Less than or equal to -lt:<value>Less than -gte:<value>Greater than or equal to -gt:<value>Greater than A special keyword for date,none(case-insensitive), may be used to retreive keys that do not have that property. This is useful forlastRotateDate, where only keys that have never been rotated can be retreived. Examples:lastRotateDate="2022-02-15T00:00:00Z"Filter keys that were last rotated on February 15, 2022 -lastRotateDate=gte:"2022-02-15T00:00:00Z"Filter keys that were last rotated after or on February 15, 2022 -lastRotateDate=gte:"2022-02-15T00:00:00Z" lastRotateDate=lt:"2022-03-15T00:00:00Z"Filter keys that were last rotated after or on February 15, 2022 but before (not including) March 15, 2022 -lastRotateDate="2022-02-15T00:00:00Z" state=0,1,2,3,5 extractable=falseFilter root keys that were last rotated on February 15, 2022, with any state Note: When you filter bystateorextractablein this query parameter, you will not be able to use the deprecatedstateorextractableindependent query parameter. You will get a 400 response code if you specify a value for one of the two properties in both this filter query parameter and the deprecated independent query of the same name (the same applies vice versa).
Possible values: 0 ≤ length ≤ 512, Value must match regular expression
^.{0,512}$
curl -I HEAD https://<region>.kms.cloud.ibm.com/api/v2/keys -H 'accept: application/vnd.ibm.kms.key+json' -H 'authorization: Bearer <IAM_token>' -H 'bluemix-instance: <instance_ID>'
Response
Response Headers
The number of keys in your service instance.
Possible values: value ≥ 0
Status Code
The metadata was successfully retrieved.
Your credentials are invalid or do not have the necessary permissions to make this request. Verify that the given IBM Cloud access token and instance ID are correct. If the error persists, contact the account owner to check your permissions.
Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. Learn more.
Too many requests. Wait a few minutes and try again.
IBM Key Protect is currently unavailable. Your request could not be processed. Try again later. If the problem persists, note the
correlation-IDin the response header and contact IBM Cloud support.
Create a key with policy overrides
Creates a new key with specified key material and key policies. This API overrides the policy configurations set at instance level with policies provided in the payload.
Key Protect designates the resource as a root key or a standard key based on the extractable value that you specify.
A successful POST /keys_with_policy_overrides operation adds the key and key policies to the service and returns the
details of the request in the response entity-body, if the Prefer header
is set to return=representation.
POST /api/v2/keys_with_policy_overrides
Request
Custom Headers
The IBM Cloud instance ID that identifies your Key Protect service instance.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The v4 UUID used to correlate and track transactions.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$Alters server behavior for POST or DELETE operations. A header with
return=minimalcauses the service to return only the key identifier as metadata. A header containingreturn=representationreturns both the key material and metadata in the response entity-body. If the key has been designated as a root key, the system cannot return the key material. Note: During POST operations, Key Protect may not immediately return the key material due to key generation time. To retrieve the key material, you can perform a subsequentGET /keys/{id}request.Allowable values: [
return=representation,return=minimal]Possible values: 14 ≤ length ≤ 21
The ID of the key ring that the specified key belongs to. When the header is not specified, Key Protect will perform a key ring lookup. For a more optimized request, specify the key ring on every call. The key ring ID of keys that are created without an
X-Kms-Key-Ringheader is:default.Possible values: 2 ≤ length ≤ 100, Value must match regular expression
^[a-zA-Z0-9-]*$Default:
default
The base request for creating a new key with policies.
{
"metadata": {
"collectionType": "application/vnd.ibm.kms.key+json",
"collectionTotal": 1
},
"resources": [
{
"type": "application/vnd.ibm.kms.key+json",
"name": "Root-key",
"description": "A Key Protect key"
}
]
}A collection of resources.
Possible values: number of items = 1
curl -X POST https://<region>.kms.cloud.ibm.com/api/v2/keys_with_policy_overrides -H 'authorization: Bearer <IAM_token>' -H 'bluemix-instance: <instance_ID>' -H 'content-type: application/vnd.ibm.kms.key+json' -d '{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 1 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "name": "Root-key", "description": "A Key Protect key", "extractable": false, "dualAuthDelete": { "enabled": true }, "rotation":{ "enabled": true, "interval_month": 6 } } ] }'
Response
Properties associated with a key response.
A collection of resources.
Possible values: number of items = 1
Status Code
The key was successfully created.
The key is either missing a required field or it may contain an invalid or malformed input.
Your credentials are invalid or do not have the necessary permissions to make this request. Verify that the given IBM Cloud access token and instance ID are correct. If the error persists, contact the account owner to check your permissions.
Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. Learn more.
There are three possible causes for HTTP 404 while trying to create a key, specifying a reason code (resouces[0].reasons[0].code) as follows:
KEY_RING_NOT_FOUND_ERR: The key cannot be created because the key ring does not exist. Note the default key ring name is "default." INSTANCE_NOT_FOUND_ERR: The key cannot be created because the instance does not exist. IMPORT_TOKEN_NOT_FOUND_ERR: The key cannot be created because the import token does not exist.
The import token that was used to encrypt this key has reached its
maxAllowedRetrievalsorexpirationDate, and it is no longer available for operations. To create a new import token, usePOST /import_token. In very rare cases, the import token may expire before its expiration time. Ensure that your client application is configured with a retry mechanism for catching and responding to409conflict exceptions. KEY_ALIAS_QUOTA_ERR: The alias quota for this key has been reached. KEY_ALIAS_NOT_UNIQUE_ERR: One or more aliases are already associated with a key in the instance. KEY_CREATE_IMPORT_ACCESS_ERR: KeyCreateImportAccess instance policy is enabled. Key Protect only permits the creation or import of keys in your Key Protect instance that follow the key creation and import settings listed on the keyCreateImportAccess policy. IMPORT_TOKEN_EXPIRED_ERR: The key cannot be created because the import token has expired.Too many requests. Wait a few minutes and try again.
IBM Key Protect is currently unavailable. Your request could not be processed. Try again later. If the problem persists, note the
correlation-IDin the response header and contact IBM Cloud support.
{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 1 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "id": "fadedbee-0000-0000-0000-1234567890ab", "name": "Root-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 1, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:fadedbee-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "lastUpdateDate": "2000-03-21T00:00:00Z", "keyVersion": { "id": "fadedbee-0000-0000-0000-1234567890ab", "creationDate": "2000-03-21T00:00:00Z" }, "rotation": { "interval_month": 3 }, "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": false } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Bad Request: The key is missing a required field." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Unauthorized: The user does not have access to the specified resource." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. [Learn more](/docs/key-protect?topic=key-protect-integrate-services#grant-access)" } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Conflict: The import token that was used to encrypt this key has reached its 'maxAllowedRetrievals' or 'expirationDate', and it is no longer available for key operations. To create a new import token, use 'POST /import_token'." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Too Many Requests: Wait a few minutes and try again." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Internal Server Error: IBM Key Protect is currently unavailable. Your request could not be processed. Try again later." } ] }
Retrieve a key
Retrieves a key and its details by specifying the ID or alias of the key.
GET /api/v2/keys/{id}Request
Custom Headers
The IBM Cloud instance ID that identifies your Key Protect service instance.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The v4 UUID used to correlate and track transactions.
Possible values: length = 36, Value must match regular expression
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$The ID of the key ring that the specified key is a part of. When the header is not specified, Key Protect will perform a key ring lookup. For a more optimized request, specify the key ring on every call. The key ring ID of keys that are created without an
X-Kms-Key-Ringheader is:default.Possible values: 2 ≤ length ≤ 100, Value must match regular expression
^[a-zA-Z0-9-]*$
Path Parameters
The v4 UUID or alias that uniquely identifies the key.
Possible values: 2 ≤ length ≤ 90, Value must match regular expression
^[a-zA-Z0-9-_]{2,90}$
curl -X GET https://<region>.kms.cloud.ibm.com/api/v2/keys/<key_ID_or_alias> -H 'accept: application/vnd.ibm.kms.key+json' -H 'authorization: Bearer <IAM_token>' -H 'bluemix-instance: <instance_ID>'
package main import ( "context" "encoding/json" "fmt" kp "github.com/IBM/keyprotect-go-client" ) func main() { // Initialize the Key Protect client as specified in Authentication key, err := api.GetKey(context.Background(), <key_ID_or_alias>) if err != nil { fmt.Println("Error while retrieving the key: ", err) return } b, _ := json.MarshalIndent(key, "", " ") fmt.Println(string(b)) }
// Initialize the Key Protect client as specified in Authentication const getKeyParams = Object.assign({}, envConfigs); getKeyParams.id = "<key_id>"; const response = keyProtectClient.getKey(getKeyParams); console.log('Get key result: '); console.log(response.result.resources[0]);
import os import keyprotect from keyprotect import bxauth # Initialize the Key Protect client as specified in Authentication key = kp.get("<key_id>") print("%s\t%s" % (key["id"], key["name"]))
public static List<KeyWithPayload> getKey(String keyId) { GetKeyOptions getKeyOptionsModel = new GetKeyOptions.Builder() .bluemixInstance("<instance_id>") .id(keyId) .build(); Response<GetKey> response = testClient.getKey(getKeyOptionsModel).execute(); List<KeyWithPayload> key = response.getResult().getResources(); return key; }
Response
The base schema for retrieving keys.
The metadata that describes the resource array.
A collection of resources.
Possible values: number of items = 1
Status Code
The key was successfully retrieved. If the key was previously deleted,
keyVersion.creationDateis omitted from the request response.The key could not be retrieved due to a malformed, invalid, or missing ID.
Your credentials are invalid or do not have the necessary permissions to make this request. Verify that the given IBM Cloud access token and instance ID are correct. If the error persists, contact the account owner to check your permissions.
Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. Learn more.
The key could not be found. Verify that the key ID specified is valid.
Too many requests. Wait a few minutes and try again.
IBM Key Protect is currently unavailable. Your request could not be processed. Try again later. If the problem persists, note the
correlation-IDin the response header and contact IBM Cloud support.
{ "metadata": { "collectionType": "application/vnd.ibm.kms.key+json", "collectionTotal": 1 }, "resources": [ { "type": "application/vnd.ibm.kms.key+json", "id": "fadedbee-0000-0000-0000-1234567890ab", "name": "Standard-key", "aliases": [ "alias-for-this-key" ], "description": "A Key Protect key", "state": 1, "extractable": true, "keyRingID": "default", "crn": "crn:v1:bluemix:public:kms:<region>:<account-ID>:<instance-ID>:key:fadedbee-0000-0000-0000-1234567890ab", "imported": false, "creationDate": "2000-03-21T00:00:00Z", "createdBy": "IBMid-0000000000", "algorithmType": "Deprecated", "algorithmMetadata": { "bitLength": "256", "mode": "Deprecated" }, "algorithmBitSize": 256, "algorithmMode": "Deprecated", "keyVersion": { "id": "fadedbee-0000-0000-0000-1234567890ab", "creationDate": "2000-03-21T00:00:00Z" }, "dualAuthDelete": { "enabled": true, "keySetForDeletion": true, "authExpiration": "2000-03-21T00:00:00Z" }, "deleted": false, "payload": "x089YbmN9GSvpxEKe0LaqA==" } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Bad Request: The key could not be retrieved due to a malformed, invalid, or missing ID." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Unauthorized: The user does not have access to the specified resource." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Your service is not authorized to make this request. Ensure that an authorization exists between your service and Key Protect. [Learn more](/docs/key-protect?topic=key-protect-integrate-services#grant-access)" } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Not Found: The key could not be found. Verify that the key ID specified is valid." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Too Many Requests: Wait a few minutes and try again." } ] }{ "metadata": { "collectionType": "application/vnd.ibm.kms.error+json", "collectionTotal": 1 }, "resources": [ { "errorMsg": "Internal Server Error: IBM Key Protect is currently unavailable. Your request could not be processed. Try again later." } ] }
Invoke an action on a key
Note: This API has been deprecated and transitioned to
individual request paths. Existing actions using this API will continue
to be supported, but new actions will no longer be added to it. We
recommend, if possible, aligning your request URLs to the new API path.
The generic format of actions is now the following:
/api/v2/keys/<key_ID>/actions/<action> where key_ID is the key you
want to operate on/with and action is the same action that was passed
as a query parameter previously.
Invokes an action on a specified key. This method supports the following actions:
disable: Disable operations for a keyenable: Enable operations for a keyrestore: Restore a root keyrewrap: Use a root key to rewrap or reencrypt a data encryption keyrotate: Create a new version of a root keysetKeyForDeletion: Authorize deletion for a key with a dual authorization policyunsetKeyForDeletion: Remove an authorization for a key with a dual authorization policyunwrap: Use a root key to unwrap or decrypt a data encryption keywrap: Use a root key to wrap or encrypt a data encryption key
Note: If you unwrap a wrapped data encryption key (WDEK) that was not wrapped by the latest version of the key, the service also returns the a new WDEK, wrapped with the latest version of the key as the ciphertext field. The recommendation is to store and use that WDEK, although older WDEKs will continue to work.
POST /api/v2/keys/{id}