Updated on 2024-08-30 GMT+08:00

Using KMS to Protect File Integrity

Scenario

When a large amount of files (such as images, electronic insurance policies, and important files) need to be transmitted or stored securely, you can use KMS to sign the file digest. When the files are used again, you can recalculate the digest for signature verification. Ensure that files are not tampered with during transmission or storage.

Solution

Create a CMK on KMS.

Calculate the file digest and call the sign API of KMS to sign the digest. The signature result of the digest is obtained. Transmit or store the digest signature result, key ID, and the file together. The following figure shows the signature process.

Figure 1 Signature process

Before using a file, you need to check the integrity of the file to ensure that the file is not tampered with.

Recalculate the file digest and call the verify API of KMS with the signature value to verify the signature for the digest. The signature verification result is obtained. If the signature is verified, the file has not been tampered with. The following figure shows the signature verification process.

Figure 2 Signature verification 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.

  3. Use KMS to sign the file and verify the signature.

    public class FileStreamSignVerifyExample {
     
        /**
         * Basic authentication information:
         * - ACCESS_KEY: access key of the Huawei Cloud account
         * - SECRET_ACCESS_KEY: secret access key of the Huawei Cloud account, which is sensitive information. Store this in ciphertext.
         * - IAM_ENDPOINT: endpoint for accessing IAM. For details, see Regions and Endpoints.
         * - KMS_REGION_ID: regions supported by KMS. For details, see Regions and Endpoints.
         * - KMS_ENDPOINT: endpoint for accessing KMS. For details, see Regions and Endpoints.
         */
        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 IAM_ENDPOINT = "https://<IamEndpoint>";
        private static final String KMS_REGION_ID = "<RegionId>";
        private static final String KMS_ENDPOINT = "https://<KmsEndpoint>";
     
        public static void main(String[] args) {
            // CMK ID. Select a key whose usage contains SIGN_VERIFY.
            final String keyId = args[0];
     
            signAndVerifyFile(keyId);
        }
     
        /**
         * Use KMS to sign the file and verify the signature.
         *
         * @param keyId: CMK ID
         */
        static void signAndVerifyFile(String keyId) {
            // 1. Prepare the authentication information for accessing HUAWEI CLOUD.
            final BasicCredentials auth = new BasicCredentials()
                    .withIamEndpoint(IAM_ENDPOINT).withAk(ACCESS_KEY).withSk(SECRET_ACCESS_KEY);
     
            // 2. Initialize the SDK and transfer the authentication information and the address for the KMS to access the client.
            final KmsClient kmsClient = KmsClient.newBuilder()
                    .withRegion(new Region(KMS_REGION_ID, KMS_ENDPOINT)).withCredential(auth).build();
     
            // 3. Prepare the file to be signed.
            // inFile File to be signed
            final File inFile = new File("FirstSignFile.iso");
            final String fileSha256Sum = getFileSha256Sum(inFile);
     
            // 4. Calculate the digest and select a proper signature algorithm based on the key type.
            final SignRequest signRequest = new SignRequest().withBody(
                    new SignRequestBody().withKeyId(keyId).withSigningAlgorithm(SignRequestBody.SigningAlgorithmEnum.RSASSA_PSS_SHA_256)
                            .withMessageType(SignRequestBody.MessageTypeEnum.DIGEST).withMessage(fileSha256Sum));
     
            final SignResponse signResponse = kmsClient.sign(signRequest);
     
            // 5. Verify the digest.
            final ValidateSignatureRequest validateSignatureRequest = new ValidateSignatureRequest().withBody(
                    new VerifyRequestBody().withKeyId(keyId).withMessage(fileSha256Sum).withSignature(signResponse.getSignature())
                            .withSigningAlgorithm(VerifyRequestBody.SigningAlgorithmEnum.RSASSA_PSS_SHA_256)
                            .withMessageType(VerifyRequestBody.MessageTypeEnum.DIGEST));
            final ValidateSignatureResponse validateSignatureResponse = kmsClient.validateSignature(validateSignatureRequest);
     
            // 6. Compare the digest result.
            assert validateSignatureResponse.getSignatureValid().equalsIgnoreCase("true");
     
        }
     
        /**
         * Calculate the SHA256 digest of the file.
         *
         * @param file
         * @return SHA256 digest in Base64 format
         */
        static String getFileSha256Sum(File file) {
            int length;
            MessageDigest sha256;
            byte[] buffer = new byte[1024];
            try {
                sha256 = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage());
            }
            try (FileInputStream inputStream = new FileInputStream(file)) {
                while ((length = inputStream.read(buffer)) != -1) {
                    sha256.update(buffer, 0, length);
                }
                return Base64.getEncoder().encodeToString(sha256.digest());
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
     
    }