Key Management Service examples
  • PDF

Key Management Service examples

  • PDF

Available in Classic and VPC

This guide describes examples of implementing envelope encryption using Key Management Service.
Caution

The code introduced in these Key Management Service examples is a hypothetical scenario created to help you understand Key Management Service. Since it doesn't reflect jobs such as exception handling and it won't respond perfectly to the actual scenario, be careful not to apply it to the actual situation.

Envelope encryption of confidential information

This section introduces a scenario and example for envelope encryption of confidential information.

Scenario

Server developer A of a web service company using NAVER Cloud Platform received the following requirement that the DB authentication information for accessing the DB server from the web server needs to be encrypted.

  • The DB authentication information must be encrypted and protected.
  • All encryption keys must be properly created, operated, and protected at the standard recommendation level.

To fulfill the requirement, developer A decided to encrypt the DB authentication information with the data encryption key (DEK), as well as encrypt the DEK with another key for storage. To use the master key (KEK), which is a higher key that encrypts the data key, developer A requested the key access permission of Key Management Service. Since the DEK needs to be encrypted and decrypted, developer A was granted with the Encryptor/Decryptor role for Key Management Service, and then verified the key tag. Developer A re-verified the access key and secret key that they already knew through Sub Account by accessing Sub Account of the NAVER Cloud Platform console. Afterward, developer A configured them as environment variables with the names NCP_ACCESS_KEY and NCP_SECRET_KEY respectively. Developer A also checked the API key dedicated for Key Management Service from API Keys of API Gateway to directly call the Key Management Service API, but noticed that it didn't exist, so they asked the account manager to create an API key dedicated to Key Management Service. After receiving confirmation from the account manager that it is fine to use the universal API key for the Key Management Service API, they configured the universal API key as an environment variable named NCP_API_KEY in their development environment system. Developer A, who also wanted to follow the encryption key creation recommendation standard for the DEK, noticed that a high-entropy key could be created through Key Management Service's createCustomKey API without having to go through the complex key creation process. Since the encryption of the DB authentication information will use AES-CBC, the initial vector (IV) value, which is additional information used for encryption/decryption, also needs to be managed. Therefore, developer A decided to manage the DB authentication information, data key, and additional encryption information as data in the form of an envelope as shown below.

{
  "ciphertext": "Encrypted DB authentication information",
  "wrappedKey": "Encrypted data encryption key",
  "iv": "Additional information to be used for encryption <Example> IV value"
}

Example code

The following is an example of creating envelope encryption written in Java based on the Envelope encryption of credentials scenario.

public class EncryptCredential {

  // URI
  private static String KMS_API_BASE_URI = "https://kms.apigw.ntruss.com";

  // END POINT
  private static String KMS_API_DECRYPT = "/keys/v1/%s/decrypt"; // Decryptor permission required (uses KMS API stage v1)
  //private static String KMS_API_DECRYPT = "/keys/v2/%s/decrypt"; // Decryptor permission required (uses KMS API stage v2)
  private static String KMS_API_CUSTOM_KEY = "/keys/v1/%s/createCustomKey"; // Encryptor permission required (uses KMS API stage v1)
  //private static String KMS_API_CUSTOM_KEY = "/keys/v2/%s/createCustomKey"; // Encryptor permission required (uses KMS API stage v2)

  // Sample KEY TAG
  private static String KEY_TAG = "4165867476e68eca06e84c993708c23d22ca2cb6a51ac15750bd7e991ccadc39";

  private static String ncpAccessKey;
  private static String ncpSecretKey;
  private static String ncpApiKey;

  public static void main(String[] args) throws Exception {
    // Use by registering the API credential information as environmental variable
    ncpAccessKey = System.getenv("NCP_ACCESS_KEY");
    ncpSecretKey = System.getenv("NCP_SECRET_KEY");
    ncpApiKey = System.getenv("NCP_API_KEY");

    envelopCredential();
  }

  public static void envelopCredential() throws Exception {
    // Requests creation of a new high-entropy data key
    String wrappedDataKey = getCustomKey();
    // Confidential data to be ultimately protected
    String example_credential_json = "{\"AUTH\":\"THIS_IS_A_DB_CREDENTIAL\"}}";

    // Encrypted data envelope to be stored by the user (Refer to Envelope encryption)
    String envelope = encrypt(example_credential_json, wrappedDataKey);
    // The encrypted data envelope is saved in a file in this example code.
    File envelopeFile = new File("credentialEnvelope.json");
    OutputStream os = new BufferedOutputStream(new FileOutputStream(envelopeFile));

    try {
      os.write(envelope.getBytes());
    } finally {
      os.close();
    }
  }

  private static String encrypt(Object obj, String wrappedDataKey) throws Exception {
    Map<String, String> envelope = new HashMap<>();

    // Data key unwrapping
    String dataKey = unwrapKey(wrappedDataKey);

    // Encrypts the created high-entropy 256-bit data key in the AES-CBC method
    SecretKey secretKey = new SecretKeySpec(decodeFromBase64(dataKey),"AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
    byte[] ciphertext = cipher.doFinal(obj.toString().getBytes());

    envelope.put("wrappedKey", wrappedDataKey);
    envelope.put("ciphertext", encodeToBase64(ciphertext));
    envelope.put("iv", encodeToBase64(iv));

    return JSONValue.toJSONString(envelope);
  }

  private static String unwrapKey(String sealedKey) throws Exception {
    String endPoint = String.format(KMS_API_DECRYPT, KEY_TAG);

    JSONObject data = new JSONObject();
    data.put("ciphertext", sealedKey);
    JSONObject respJsonObject = apiCaller(endPoint, data.toJSONString());
    String plaintext = (respJsonObject.get("plaintext")).toString();
    return plaintext;
  }

  private static String getCustomKey() throws Exception {
    String endPoint = String.format(KMS_API_CUSTOM_KEY, KEY_TAG);

    JSONObject data = new JSONObject();
    data.put("requestPlainKey", false);
    JSONObject respJsonObject = apiCaller(endPoint, data.toJSONString());
    return respJsonObject.get("ciphertext").toString();
  }

  private static JSONObject apiCaller(String endPoint, String data) throws Exception {
    HttpClient client = HttpClients.createDefault();

    long timestamp = System.currentTimeMillis();
    String signature = makeSignature(endPoint, timestamp);
    URIBuilder uriBuilder = new URIBuilder(KMS_API_BASE_URI);
    uriBuilder.setPath(endPoint);

    HttpPost request = new HttpPost(uriBuilder.build().toString());
    request.addHeader("x-ncp-apigw-timestamp", timestamp + "");
    request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Required when using v1
    //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required when using v2
    request.addHeader("x-ncp-iam-access-key", ncpAccessKey);
    request.addHeader("x-ncp-apigw-signature-v1", signature);
    request.addHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(data));

    HttpResponse response = client.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONParser parser = new JSONParser();
    JSONObject repsObj = (JSONObject) parser.parse(responseBody);
    JSONObject dataObj = (JSONObject) repsObj.get("data");
    return dataObj;
  }

  private static String encodeToBase64(byte[] bytesToEncode) {
    return Base64.getEncoder().encodeToString(bytesToEncode);
  }

  private static byte[] decodeFromBase64(String stringToDecode) {
    return Base64.getDecoder().decode(stringToDecode);
  }

  // Creates an API call signature for API Gateway authentication (Refer to the API Gateway guide)
  private static String makeSignature(String uri , long timestamp) throws Exception {
    String message = new StringBuilder()
      .append("POST").append(" ").append(uri).append("\n")
      .append(timestamp).append("\n")
      .append(ncpApiKey).append("\n") // Required when using v1
      //.append(ncpApiKey).append("\n") // Not required when using v2
      .append(ncpAccessKey)
      .toString();

    SecretKeySpec signingKey = new SecretKeySpec(ncpSecretKey.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
    String encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
    return encodeBase64String;
  }

}

Creation result

The following is the creation result of the example code.

{
  "ciphertext":"wh6wryZ5MUrzlzd7EW9OYNek+3taxNVnxAcUPBRR6vtDH29tDrFxLyNukqUT3s7i",
  "iv":"HDlrArTVqwHQJRx9IhtqzQ==",
  "wrappedKey":"ncpkms:v1:e0AGESFjKj7xFtCxW1zfGFyZ3G\/4mc51mAMMu1n2hHNLsI4X9h5NKRKx0avz+1ky7\/+7aCd5SAjCOlnV"
}

Use of encrypted envelope

This section introduces a hypothetical scenario and example code to help you use the encrypted envelope.

Scenario

The envelope containing the DB authentication information encrypted through the Envelope encryption of confidential information scenario needs to be used in the actual server code. To test it, developer A writes code that decrypts the ciphertext in the envelope before accessing the DB and converts it to the DB authentication information.

Example code

The following is an example written in Java based on the Use of encrypted envelope scenario.

public class ClientApiSample {

  // URI
  private static String KMS_API_BASE_URI = "https://kms.apigw.ntruss.com";

  // END POINT
  private static String KMS_API_DECRYPT = "/keys/v1/%s/decrypt"; // Decryptor permission required (uses KMS API stage v1)
  //private static String KMS_API_DECRYPT = "/keys/v2/%s/decrypt"; // Decryptor permission required (uses KMS API stage v2)

  // KEY TAG
  private static String KEY_TAG = "1bc86ca1be3b062cf8503d0a7e6d3717fe3a1c0480e309b724b26bf961e1f3c6";

  private static String ncpAccessKey;
  private static String ncpSecretKey;
  private static String ncpApiKey;

  public static void main(String[] args) throws Exception {
    // Use by registering the API credential information as environmental variable
    ncpAccessKey = System.getenv("NCP_ACCESS_KEY");
    ncpSecretKey = System.getenv("NCP_SECRET_KEY");
    ncpApiKey = System.getenv("NCP_API_KEY");

    String dbCredential = getCredential();
  }

  public static String getCredential() throws Exception {
    // Encrypted data envelope to be stored by the user (Refer to Envelope encryption)
    File envelopeFile = new File("credentialEnvelope.json");
    InputStream is = new BufferedInputStream(new FileInputStream(envelopeFile));

    String envelope = new String(Files.readAllBytes(Paths.get("credentialEnvelope.json")));
    JSONParser parser = new JSONParser();
    JSONObject envelopeJson = (JSONObject) parser.parse(envelope);
    String wrappedDataKey = envelopeJson.get("wrappedKey").toString();
    String ciphertext = envelopeJson.get("ciphertext").toString();
    String iv = envelopeJson.get("iv").toString();

    return decrypt(ciphertext, wrappedDataKey, iv);
  }

  private static String decrypt(String ciphertext, String wrappedDataKey, String iv) throws Exception {

    String dataKey = unwrapKey(wrappedDataKey);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(decodeFromBase64(iv));
    SecretKey secretKey = new SecretKeySpec(decodeFromBase64(dataKey), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
    byte[] plaintext = cipher.doFinal(decodeFromBase64(ciphertext));

    return new String(plaintext);
  }

  private static String unwrapKey(String sealedKey) throws Exception {
    String endPoint = String.format(KMS_API_DECRYPT, KEY_TAG);

    JSONObject data = new JSONObject();
    data.put("ciphertext", sealedKey);
    JSONObject respJsonObject = apiCaller(endPoint, data.toJSONString());
    String plaintext = (respJsonObject.get("plaintext")).toString();
    return plaintext;
  }

  private static JSONObject apiCaller(String endPoint, String data) throws Exception {
    HttpClient client = HttpClients.createDefault();

    long timestamp = System.currentTimeMillis();
    String signature = makeSignature(endPoint, timestamp);
    URIBuilder uriBuilder = new URIBuilder(KMS_API_BASE_URI);
    uriBuilder.setPath(endPoint);

    HttpPost request = new HttpPost(uriBuilder.build().toString());
    request.addHeader("x-ncp-apigw-timestamp", timestamp + "");
    request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Required when using v1
    //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required when using v2
    request.addHeader("x-ncp-iam-access-key", ncpAccessKey);
    request.addHeader("x-ncp-apigw-signature-v1", signature);
    request.addHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(data));

    HttpResponse response = client.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONParser parser = new JSONParser();
    JSONObject repsObj = (JSONObject) parser.parse(responseBody);
    JSONObject dataObj = (JSONObject) repsObj.get("data");
    return dataObj;
  }

  private static byte[] decodeFromBase64(String stringToDecode) {
    return Base64.getDecoder().decode(stringToDecode);
  }

  // Creates an API call signature for API Gateway authentication (Refer to the API Gateway guide)
  private static String makeSignature(String uri , long timestamp) throws Exception {
    String message = new StringBuilder()
      .append("POST").append(" ").append(uri).append("\n")
      .append(timestamp).append("\n")
      .append(ncpApiKey).append("\n") // Required when using v1
      //.append(ncpApiKey).append("\n") // Not required when using v2
      .append(ncpAccessKey)
      .toString();

    SecretKeySpec signingKey = new SecretKeySpec(ncpSecretKey.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
    String encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
    return encodeBase64String;
  }

}

Manage data encryption key

This section introduces a hypothetical scenario and example code to help you understand data encryption key (DEK) management.

Scenario

Encrypting confidential information and DEK and storing them together is known to be the most secure way to protect data. However, that is not all. All encryption keys need periodic rotation (renewal) to prepare against known cryptographic vulnerabilities. The master key used as KEY_TAG in the example code introduced earlier is configured to be automatically rotated at regular intervals (up to 365 days). It can also be rotated manually by the Key Management Service admin (or key admin). Since the DEK that developer A used directly to encrypt the DB authentication information is encrypted with the master key, the encrypted DEK must be re-encrypted with the rotated new master key when the master key is rotated. Re-encryption can be easily performed through the reencrypt API of Key Management Service. The reencrypt API re-encrypts the existing ciphertext with the latest version of the key. Just as developer A was notified via email when the key usage permission was assigned, they will also be notified when the key is rotated. When the notification is received, the re-encryption needs to be performed as soon as possible. To do this, developer A wrote the following code to execute when they receive the key rotation notification. Now, the DEK is re-encrypted with the new rotated version and creates a new envelope. It is safe to delete the existing envelope after re-encryption. However, it is recommended to manually check the re-encrypted envelope before deleting the existing envelope, to avoid data loss. Therefore, in this example, we will proceed by creating a new envelope, checking it, and then deleting the existing envelope, rather than overwriting the existing envelope right away.

Example code

The following is an example written in Java based on the Manage DEK scenario.

public class ClientApiSample {

  // URI
  private static String KMS_API_BASE_URI = "https://kms.apigw.ntruss.com";

  // END POINT
  private static String KMS_API_REENCRYPT = "/keys/v1/%s/reencrypt"; // Uses KMS API stage v1
  // private static String KMS_API_REENCRYPT = "/keys/v2/%s/reencrypt"; // Uses KMS API stage v2

  // KEY TAG
  private static String KEY_TAG = "1bc86ca1be3b062cf8503d0a7e6d3717fe3a1c0480e309b724b26bf961e1f3c6";

  private static String ncpAccessKey;
  private static String ncpSecretKey;
  private static String ncpApiKey;

  public static void main(String[] args) throws Exception {
    ncpAccessKey = System.getenv("NCP_ACCESS_KEY");
    ncpSecretKey = System.getenv("NCP_SECRET_KEY");
    ncpApiKey = System.getenv("NCP_API_KEY");

    reenvelopCredential();
  }

  private static void reenvelopCredential() throws Exception {
    String envelope = new String(Files.readAllBytes(Paths.get("credentialEnvelope.json")));
    JSONParser parser = new JSONParser();
    JSONObject envelopeJson = (JSONObject) parser.parse(envelope);
    String wrappedDataKey = envelopeJson.get("wrappedKey").toString();
    String ciphertext = envelopeJson.get("ciphertext").toString();
    String iv = envelopeJson.get("iv").toString();

    // Re-encrypts the encrypted data key with the latest version
    String rewrappedDataKey = rewrapKey(wrappedDataKey);

    Map<String, String> newEnvelope = new HashMap<>();
    // Only changes the re-encrypted key without changing the ciphertext and IV
    newEnvelope.put("wrappedKey", rewrappedDataKey);
    newEnvelope.put("ciphertext", ciphertext);
    newEnvelope.put("iv", iv);

    String newEnvelopeJson = JSONValue.toJSONString(newEnvelope);

    // Creates a new envelope (the existing envelope needs to be deleted after confirmation)
    File newEnvelopeFile = new File("credentialEnvelope_new.json");
    OutputStream os = new BufferedOutputStream(new FileOutputStream(newEnvelopeFile));

    try {
      os.write(newEnvelopeJson.getBytes());
    } finally {
      os.close();
    }
  }

  private static String rewrapKey(String wrappedDataKey) throws Exception {
    String endPoint = String.format(KMS_API_REENCRYPT, KEY_TAG);

    JSONObject data = new JSONObject();
    data.put("ciphertext", wrappedDataKey);

    JSONObject respJsonObject = apiCaller(endPoint, data.toJSONString());
    String ciphertext = respJsonObject.get("newCiphertext").toString();
    return ciphertext;
  }

  private static JSONObject apiCaller(String endPoint, String data) throws Exception {
    HttpClient client = HttpClients.createDefault();

    long timestamp = System.currentTimeMillis();
    String signature = makeSignature(endPoint, timestamp);
    URIBuilder uriBuilder = new URIBuilder(KMS_API_BASE_URI);
    uriBuilder.setPath(endPoint);

    HttpPost request = new HttpPost(uriBuilder.build().toString());
    request.addHeader("x-ncp-apigw-timestamp", timestamp + "");
    request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Required when using v1
    //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required when using v2
    request.addHeader("x-ncp-iam-access-key", ncpAccessKey);
    request.addHeader("x-ncp-apigw-signature-v1", signature);
    request.addHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(data));

    HttpResponse response = client.execute(request);
    String responseBody = EntityUtils.toString(response.getEntity());
    JSONParser parser = new JSONParser();
    JSONObject repsObj = (JSONObject) parser.parse(responseBody);
    JSONObject dataObj = (JSONObject) repsObj.get("data");
    return dataObj;
  }

  private static String makeSignature(String uri , long timestamp) throws Exception {
    String message = new StringBuilder()
      .append("POST").append(" ").append(uri).append("\n")
      .append(timestamp).append("\n")
      .append(ncpApiKey).append("\n") // Required when using v1
      //.append(ncpApiKey).append("\n") // Not required when using v2
      .append(ncpAccessKey)
      .toString();

    SecretKeySpec signingKey = new SecretKeySpec(ncpSecretKey.getBytes("UTF-8"), "HmacSHA256");
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
    String encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
    return encodeBase64String;
  }
}

Creation result

The following is the creation result of the example code.

{
  "ciphertext":"wh6wryZ5MUrzlzd7EW9OYNek+3taxNVnxAcUPBRR6vtDH29tDrFxLyNukqUT3s7i",
  "iv":"HDlrArTVqwHQJRx9IhtqzQ==",
  "wrappedKey":"ncpkms:v2:lNZubJHJ4coJConKPBf4gYghFN0h\/rjHmOBtvVbTXmXynRcKhPxPNrjkCTgurBZ4a7Fb7+\/8dVKcC33R"
}

Use Java SDK

This section introduces an example of easily calling the Key Management Service API through API Gateway, using the Java SDK (Maven project) provided by the Key Management Service API.

Note

To download the Key Management Service Java Client SDK, refer to Prerequisites for using Key Management Service.

Connect

All requests are called through the ApiClient object. The ApiClient object is created by setting the authentication information. The following shows how to do it. Set authentication information: The Key Management Service API is called through API Gateway, and performs the authentication of the API Key registered in API Gateway and the authentication of Sub Account (IAM).

  • Authentication using properties file
    • It performs the authentication by creating the PropertiesFileCredentialsProvider object using a properties file configured with the authentication information.

      type=iam
      apiKey="API Key configured in API Gateway"
      accessKey="Access key of the sub account configured in Sub Account"
      secretKey="Secret key of the sub account configured in Sub Account"
      

      An authentication information file named credentials.properties is created in the above format. Apply proper protection and access control for credentials.properties to prevent it from getting leaked. When the credentials.properties file is ready, create an ApiClient object with a predefined builder.

    • The following is an example code written in Java.

      public void setUp() {
        apiClient = new ApiClient.ApiClientBuilder()
          .addMarshaller(JsonMarshaller.getInstance())
          .addMarshaller(XmlMarshaller.getInstance())
          .addMarshaller(FormMarshaller.getInstance())
          .setCredentials(new PropertiesFileCredentialsProvider("credentials.properties").getCredentials()) // Sets authentication information
          .setLogging(true)
          .build();
      
        api = new V1Api(apiClient);
      }
      
  • Authentication using Server Role
    • It is an authentication method available from Server in the VPC environment of NAVER Cloud Platform. When using the KMS API from VPC Server, you can use the Java SDK without entering additional authentication information through Server Role. For more information about policy and role settings, refer to Manage Sub Account policies and roles. Specify NCP_KMS_MANAGER for the policy, and VPC Server that uses the KMS Java SDK for the role-owning resource.
      Note

      Improvements are being made to enable the use of user created policies, set and use NCP_KMS_MANAGER until the configuration of user created policies is applied.

    • When the configuration is completed, create an ApiClient object with a predefined builder, using the ServerRoleCredentialsProvider object.
    • The following is an example code written in Java.
      public void setUp() {
        apiClient = new ApiClient.ApiClientBuilder()
          .addMarshaller(JsonMarshaller.getInstance())
          .addMarshaller(XmlMarshaller.getInstance())
          .addMarshaller(FormMarshaller.getInstance())
          .setCredentialsProvider(new ServerRoleCredentialsProvider()) // Server Role authentication
          .setLogging(true)
          .build();
      
        api = new V1Api(apiClient);
      }
      

Call API

This section introduces how to call the API to perform encryption/decryption and signature/verification using the key created from Key Management Service and call examples.

  • Encrypt

    • The call method is as follows. Refer to Encrypt
    • The call example is as follows.
      public void keyTagEncryptPostTest() throws ApiException, SdkException {
          String keyTag = "53fdfdc1d875625d9cffc317e9c729c1febc5849328eb15b7b75ba17eb17e70c";
          EncryptRequestBody body = new EncryptRequestBody();
          String plaintext = Base64.getEncoder().encodeToString("This is a test.".getBytes());
          body.setPlaintext(plaintext);
      
          try {
              api.keyTagEncryptPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      
  • Decrypt

    • The call method is as follows. Refer to Decrypt
    • The call example is as follows.
      public void keyTagDecryptPostTest() throws ApiException, SdkException {
          String keyTag = "53fdfdc1d875625d9cffc317e9c729c1febc5849328eb15b7b75ba17eb17e70c";
          DecryptRequestBody body = new DecryptRequestBody();
          String ciphertext = "ncpkms:v1:eEEYwgBf/HGmqUEbTV/rASoJjneBjII+dOTnFYVOlvTnyw/+SFjwvjHpUg==";
          body.setCiphertext(ciphertext);
      
          try {
              api.keyTagDecryptPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      
  • Create user custom key

    • The call method is as follows. Refer to Create user custom key
    • The call example is as follows.
      public void keyTagCreateCustomKeyPostTest() throws ApiException, SdkException {
          String keyTag = "53fdfdc1d875625d9cffc317e9c729c1febc5849328eb15b7b75ba17eb17e70c";
          CreateCustomKeyRequestBody body = new CreateCustomKeyRequestBody();
          body.setRequestPlainKey(true); // Required parameter
          body.setBits(512); // Optional parameter
      
          try {
              api.keyTagCreateCustomKeyPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      
  • Re-encrypt

    • The call method is as follows. Refer to Re-encrypt
    • The call example is as follows.
      public void keyTagReencryptPostTest() throws ApiException, SdkException {
          String keyTag = "53fdfdc1d875625d9cffc317e9c729c1febc5849328eb15b7b75ba17eb17e70c";
          ReencryptRequestBody body = new ReencryptRequestBody();
          String ciphertext = "ncpkms:v1:eEEYwgBf/HGmqUEbTV/rASoJjneBjII+dOTnFYVOlvTnyw/+SFjwvjHpUg==";
          body.setCiphertext(ciphertext);
      
          try {
              api.keyTagReencryptPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      
  • Sign

    • The call method is as follows. Refer to Sign
    • The call example is as follows.
      public void keyTagSignPostTest() throws ApiException, SdkException {
          String keyTag = "4f81e47fae0a28dd50b9e5e0c3a204e371afa6d35b78b81cf802b80a2aa780ab";
          SignRequestBody body = new SignRequestBody();
          String data = "Test message";
          body.setData(Base64.getEncoder().encodeToString(data.getBytes()));
      
          try {
              api.keyTagSignPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      
  • Verify

    • The call method is as follows. Refer to Verify
    • The call example is as follows.
      public void keyTagVerifyPostTest() throws ApiException, SdkException {
          String keyTag = "4f81e47fae0a28dd50b9e5e0c3a204e371afa6d35b78b81cf802b80a2aa780ab";
          VerifyRequestBody body = new VerifyRequestBody();
          String data = "Test message";
          body.setData(Base64.getEncoder().encodeToString(data.getBytes()));
          body.setSignature("ncpkms:v1:MEUCIQDkn9k3voN2ABewgCAortmV4HVDXSok9bS+DX+GDd1hzAIgcIndWRNmx5j9zjMoDk9NYF3M5kk+KvRyYBVXGREVx1E=");
      
          try {
              api.keyTagVerifyPost(keyTag, body);
              // Handler Successful response
          } catch (ApiException e) {
              // Handler Failed response
              e.printStackTrace();
          } catch (SdkException e) {
              // Handle exceptions that occurred before communication with the server
              e.printStackTrace();
          }
      }
      

Was this article helpful?