Help Center/ Data Encryption Workshop/ Best Practices/ Key Management Service/ Using the Encryption SDK to Encrypt and Decrypt Local Files
Updated on 2024-08-30 GMT+08:00

Using the Encryption SDK to Encrypt and Decrypt Local Files

You can use certain algorithms to encrypt your files, protecting them from being breached or tampered with.

Encryption SDK is a client password library that can encrypt and decrypt data and file streams. You can easily encrypt and decrypt massive amounts of data simply by calling APIs. It allows you to focus on developing the core functions of your applications without being distracted by the data encryption and decryption processes.

For more information, visit. For details, see Details.

Scenario

If large files and images are sent to KMS through HTTPS for encryption, a large number of network resources will be consumed and the encryption will be slow. This section describes how to quickly encrypt a large amount of data.

Solution

Encryption SDK performs envelope encryption on file streams segment by segment.

Data is encrypted within the SDK by using the DEK generated by KMS. Segmented encryption of files in the memory ensures the security and correctness of file encryption, because it does not require file transfer over the network.

The SDK loads a file to memory and processes it segment by segment. The next segment will not be read before the encryption or decryption of the current segment completes.

Process

Procedure

  1. Obtain the AK and the SK.

    • ACCESS_KEY: Access key of the Huawei account. For details, see How Do I Obtain an Access Key (AK/SK)?
    • SECRET_ACCESS_KEY: Secret access key of the Huawei account. For details, see How Do I Obtain an Access Key (AK/SK)?
    • There will be security risks if the AK/SK used for authentication is directly written into code. Encrypt the AK/SK in the configuration file or environment variables for storage.
    • In this example, the AK/SK stored in the environment variables are used for identity authentication. Configure the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment first.

  2. Obtain region information.

    1. Log in to the management console.
    2. Hover over the username in the upper right corner and choose My Credentials from the drop-down list.
    3. Obtain the Project ID and Project Name.
      Figure 1 Obtaining the project ID and project name
    4. Click . Choose Security & Compliance > Data Encryption Workshop.
    5. Obtain the ID of the CMK (KEYID) to be used in the current region.
      Figure 2 Obtaining the CMK ID
    6. Obtain the endpoint (ENDPOINT) required by the current region.

      An endpoint is the request address for calling an API. Endpoints vary depending on services and regions. For the endpoints of all services, see Regions and Endpoints.

      Figure 3 Obtaining an endpoint

  3. Encrypt and decrypt a file.

    public class KmsEncryptFileExample {
    
        private static final String ACCESS_KEY = System.getenv("HUAWEICLOUD_SDK_AK");
        private static final String SECRET_ACCESS_KEY = System.getenv("HUAWEICLOUD_SDK_SK");
        private static final String PROJECT_ID = "<projectId>";
        private static final String REGION = "<region>";
        private static final String KEYID = "<keyId>";
        public static final String ENDPOINT = "<endpoint>";
    
        public static void main(String[] args) throws IOException {
            // Source file path
            String encryptFileInPutPath = args[0];
            // Path of the encrypted ciphertext file
            String encryptFileOutPutPath = args[1];
            // Path of the decrypted file
            String decryptFileOutPutPath = args[2];
            // Encryption context
            Map<String, String> encryptContextMap = new HashMap<>();
            encryptContextMap.put("encryption", "context");
            encryptContextMap.put("simple", "test");
            encryptContextMap.put("caching", "encrypt");
            // Construct the encryption configuration
            HuaweiConfig config = HuaweiConfig.builder().buildSk(SECRET_ACCESS_KEY)
                    .buildAk(ACCESS_KEY)
                    .buildKmsConfig(Collections.singletonList(new KMSConfig(REGION, KEYID, PROJECT_ID, ENDPOINT)))
                    .buildCryptoAlgorithm(CryptoAlgorithm.AES_256_GCM_NOPADDING)
                    .build();
            HuaweiCrypto huaweiCrypto = new HuaweiCrypto(config);
            // Set the key ring.
            huaweiCrypto.withKeyring(new KmsKeyringFactory().getKeyring(KeyringTypeEnum.KMS_MULTI_REGION.getType()));
            // Encrypt the file.
            encryptFile(encryptContextMap, huaweiCrypto, encryptFileInPutPath, encryptFileOutPutPath);
            // Decrypt the file.
            decryptFile(huaweiCrypto, encryptFileOutPutPath, decryptFileOutPutPath);
        }
    
        private static void encryptFile(Map<String, String> encryptContextMap, HuaweiCrypto huaweiCrypto, 
                                        String encryptFileInPutPath, String encryptFileOutPutPath) throws IOException {
            // fileInputStream: input stream corresponding to the encrypted file
            FileInputStream fileInputStream = new FileInputStream(encryptFileInPutPath);
            // fileOutputStream: output stream corresponding to the source file
            FileOutputStream fileOutputStream = new FileOutputStream(encryptFileOutPutPath);
            // Encryption
            huaweiCrypto.encrypt(fileInputStream, fileOutputStream, encryptContextMap);
            fileInputStream.close();
            fileOutputStream.close();
        }
    
        private static void decryptFile(HuaweiCrypto huaweiCrypto, String decryptFileInPutPath, String decryptFileOutPutPath) throws IOException {
            // in: input stream corresponding to the source file
            FileInputStream fileInputStream = new FileInputStream(decryptFileInPutPath);
            // out: output stream corresponding to the encrypted file
            FileOutputStream fileOutputStream = new FileOutputStream(decryptFileOutPutPath);
            // Decryption
            huaweiCrypto.decrypt(fileInputStream, fileOutputStream);
            fileInputStream.close();
            fileOutputStream.close();
        }
    }