Bu sayfa henüz yerel dilinizde mevcut değildir. Daha fazla dil seçeneği eklemek için yoğun bir şekilde çalışıyoruz. Desteğiniz için teşekkür ederiz.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

Using KMS to Protect File Integrity

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

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());
            }
        }
     
    }

Sitemizi ve deneyiminizi iyileştirmek için çerezleri kullanırız. Sitemizde tarama yapmaya devam ederek çerez politikamızı kabul etmiş olursunuz. Daha fazla bilgi edinin

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback