Key Management Service examples
    • PDF

    Key Management Service examples

    • PDF

    Article Summary

    Available in Classic and VPC

    The following are examples that show how to implement Envelope Encryption using the Key Management Service.

    Caution

    The codes introduced in the Key Management Service examples are fictitious scenarios created to help you understand the Key Management Service. Be careful not to apply them to your actual situation as they lack tasks such as exception handling and cannot fully respond to real-world scenarios.

    Envelope encryption of confidential information

    It describes scenarios and examples for envelope encryption of confidential information.

    Scenario

    Server developer A at a web service company using NAVER Cloud Platform received the following requirements saying that DB authentication information for accessing the DB server from the web server must be encrypted.

    • DB authentication information must be encrypted and protected
    • All encryption keys must be properly created, operated, and protected at standard recommended levels

    To accomplish this, he decided to encrypt the DB authentication information with a data encryption key (DEK) and have the DEK encrypted with another key. To use the master key (KEK), which is a higher-level key that encrypts the data key, he applied for key access from the Key Management Service. Since the DEK needs to be encrypted and decrypted, he received Change/encrypt, Change/decrypt, and View/getKeyInfo, View/getKeyList permissions to the Key Management Service key, and then checked the key tag through the console.
    A checked the Access key and Secret key, which he already knew through Sub Account, again by accessing Sub Account in NAVER Cloud Platform console. He then set them to environment variables named NCP_ACCESS_KEY and NCP_SECRET_KEY respectively.
    To call the Key Management Service API directly, he checked API Keys in API Gateway for an API key dedicated to Key Management Service, but found that there was no such key, so he requested the account manager to create an API key dedicated to Key Management Service. After receiving confirmation from his account manager that the Key Management Service API is safe to use with a generic API key, he set the generic API key to an environment variable named NCP_API_KEY in his development environment.
    A, who also wanted to ensure that DEK followed the recommended standards for encryption key creation, realized that the Key Management Service's createCustomKey API could create high-entropy keys without having to perform the complex key creation process himself.
    Since the encryption of DB authentication information will be using AES-CBC, the Initial Vector (IV) value, which is additional information used for encryption/decryption, must also be managed. So A decided to manage DB authentication information, data keys, and additional encryption information in the form of envelopes like the following:

    {
      "ciphertext": "encrypted DB authentication information",
      "wrappedKey": "encrypted data encryption key",
      "iv": "additional information to use for encryption <example> IV value"
    }
    

    Example codes

    An example of creating envelope encryption in Java based on the scenario of envelope encryption of credentials is as follows:

    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"; // Change/decrypt permission required (Use KMS API stage v1)
      //private static String KMS_API_DECRYPT = "/keys/v2/%s/decrypt"; // Change/decrypt permission required (Use KMS API stage v2)
      private static String KMS_API_CUSTOM_KEY = "/keys/v1/%s/createCustomKey"; // Change/encrypt permission required (Use KMS API stage v1)
      //private static String KMS_API_CUSTOM_KEY = "/keys/v2/%s/createCustomKey"; // Change/encrypt permission required (Use KMS API stage v2)
    
      // KEY TAG for sample
      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 API credentials by registering them in system environment variables
        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 {
        // Request to generate a new high-entropy data key
        String wrappedDataKey = getCustomKey();
        // Confidential data that you ultimately want to protect
        String example_credential_json = "{\"AUTH\":\"THIS_IS_A_DB_CREDENTIAL\"}}";
    
        // Encrypted data envelopes for users to keep (see Envelop encryption)
        String envelope = encrypt(example_credential_json, wrappedDataKey);
        // This example code saves an encrypted data envelope to a file
        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);
    
        // Encrypt the generated high-enrtopy 256-bit data key with AES-CBC.
        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 if using v1
        //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required if 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);
      }
    
      // Create an API call signature for API Gateway authentication (see API Gateway user 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 if using v1
          //.append(ncpApiKey).append("\n") // Not required if 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 creation result of the example code is as follows:

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

    Using an encrypted envelope

    The following is a hypothetical scenario and example code to help you use an encrypted envelope.

    Scenario

    The envelope containing the DB credentials encrypted through the envelope encryption scenario of confidential information needs to be used in the actual server code. To test this, Developer A writes code to decrypt the envelope's passphrase and convert it to DB authentication information before connecting to the DB.

    Example codes

    The following example is written in Java according to the usage scenario of the encrypted envelope.

    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"; // Change/decrypt permission required (Use KMS API stage v1)
      //private static String KMS_API_DECRYPT = "/keys/v2/%s/decrypt"; // Change/decrypt permission required (Use 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 API credentials by registering them in system environment variables
        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 envelopes for users to keep (see Envelop 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 if using v1
        //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required if 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);
      }
    
      // Create an API call signature for API Gateway authentication (see API Gateway user 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 if using v1
          //.append(ncpApiKey).append("\n") // Not required if 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 keys

    The following is a hypothetical scenario and example code to help you understand data encryption key (DEK) management.

    Scenario

    Keeping confidential information and DEKs encrypted and bundled together is a known best practice for data protection. But it is not the only one. All encryption keys require periodic rotation (renewal) to guard against known cryptographic weaknesses.
    The master key used as the KEY_TAG in the example code introduced earlier is essentially set to automatically rotate at regular intervals (up to 365 days). In addition, it can also be manually rotated by the Key Management Service administrator (or key manager).
    Since the DEK that Developer A directly used to encrypt DB authentication information is encrypted with the master key, when the master key is rotated, the encrypted DEK must be re-encrypted with the newly rotated master key. Re-encryption is easily accomplished through the Key Management Service's reencrypt API. The reencrypt API re-encrypts the existing passphrase with the most recent version of the key.
    Just as A was notified via email when he was assigned key permissions, he will also be notified when the key is rotated. Once notified, he should perform re-encryption as soon as possible. To do this, A has written the following code to perform when notified of a key rotation. The DEK will now be re-encrypted with the new rotated version, creating a new envelope. After re-encryption, it is safe to delete the existing envelope. However, it is recommended to manually verify and delete the re-encrypted envelope to avoid losing data. So, instead of immediately overwriting the existing envelope, he wants to create a new envelope, check it, and then delete it.

    Example codes

    The following is an example written in Java based on the DEK management 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"; // Use KMS API stage v1
      // private static String KMS_API_REENCRYPT = "/keys/v2/%s/reencrypt"; // Use 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-encrypt the encrypted datakey to the latest version
        String rewrappedDataKey = rewrapKey(wrappedDataKey);
    
        Map<String, String> newEnvelope = new HashMap<>();
        // Passphrase and iv remain unchanged, only the re-encrypted key changes
        newEnvelope.put("wrappedKey", rewrappedDataKey);
        newEnvelope.put("ciphertext", ciphertext);
        newEnvelope.put("iv", iv);
    
        String newEnvelopeJson = JSONValue.toJSONString(newEnvelope);
    
        // Create new envelopes (requires removing existing ones 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 if using v1
        //request.addHeader("x-ncp-apigw-api-key", ncpApiKey); // Not required if 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 if using v1
          //.append(ncpApiKey).append("\n") // Not required if 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 creation result of the example code is as follows:

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

    Use Java SDK

    The following example shows how to use the Java SDK (Maven project) provided by the Key Management Service API to easily call the Key Management Service API through the API Gateway.

    Note

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

    Connection

    All requests are called through the ApiClient object. The ApiClient object is created by setting up authentication information. You can create it as follows.
    Set authentication information: the Key Management Service API is called through the API Gateway and performs API key authentication registered with the API Gateway and Sub Account (IAM) authentication.

    • Authentication using a property file
      • Authentication is performed by creating a PropertiesFileCredentialsProvider object using a property file with authentication information.

        type=iam
        apiKey="API Key set in API Gateway"
        accessKey="Access Key of the subaccount set in Sub Account"
        secretKey="Secret Key of the subaccount set in Sub Account"
        

        Create an authentication information file named credentials.properties in the form above. Ensure to protect credentials.properties from leakage with proper protection and access control. Once credentials.properties is ready, create an ApiClient object with a builder in the predefined form.

      • The example code written in Java is as follows:

        public void setUp() {
          apiClient = new ApiClient.ApiClientBuilder()
            .addMarshaller(JsonMarshaller.getInstance())
            .addMarshaller(XmlMarshaller.getInstance())
            .addMarshaller(FormMarshaller.getInstance())
            .setCredentials(new PropertiesFileCredentialsProvider("credentials.properties").getCredentials()) // Set authentication information
            .setLogging(true)
            .build();
        
          api = new V1Api(apiClient);
        }
        
    • Authentication through Server Role
      • This authentication method is available for servers in NAVER Cloud Platform's VPC environment. If you use the KMS API on a VPC server, you can use Java SDK without entering separate authentication information through Server Role. For more information on setting policies and roles, see Managing Sub Account policies and roles. The policy specifies NCP_KMS_MANAGER, and the role-owned resource specifies a VPC Server that uses the KMS Java SDK.

        Note

        We are currently working on improvements to use user-defined policies. So set and use NCP_KMS_MANAGER until the user-defined policy settings are applied.

      • Once the setting is complete, create an ApiClient object with a builder in the predefined form using the ServerRoleCredentialsProvider object.

      • The example code written in Java is as follows:

        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/validation using the key created from Key Management Service and call examples.

    • Encrypt

      • You can call it as follows.
        See Encrypt
      • The following is a call example.
        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

      • You can call it as follows.
        See Decrypt
      • The following is a call example.
        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

      • You can call it as follows.
        See Create user custom key
      • The following is a call example.
        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

      • You can call it as follows.
        See Re-encrypt
      • The following is a call example.
        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

      • You can call it as follows.
        See Sign
      • The following is a call example.
        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

      • You can call it as follows.
        See Verify
      • The following is a call example.
        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?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.