Este conteúdo foi traduzido por máquina para sua conveniência e a Huawei Cloud não pode garantir que o conteúdo foi traduzido com precisão. Para exibir o conteúdo original, use o link no canto superior direito para mudar para a página em inglês.
Computação
Elastic Cloud Server
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Redes
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
Gerenciamento e governança
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
Cloud Operations Center
Resource Governance Center
Migração
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
Análises
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Outros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Segurança e conformidade
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
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Serviços de mídia
Media Processing Center
Video On Demand
Live
SparkRTC
Armazenamento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Cloud Server Backup Service
Storage Disaster Recovery Service
Scalable File Service
Volume 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
Bancos de dados
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
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Aplicações de negócios
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Data Lake Factory
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Distribuição de conteúdo e computação de borda
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluções
SAP Cloud
High Performance Computing
Serviços para desenvolvedore
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
MacroVerse aPaaS
KooPhone
KooDrive
Nesta página
Central de ajuda/ Data Encryption Workshop/ Melhores práticas/ Serviço de gerenciamento de chaves/ Uso do SDK de criptografia para criptografar e descriptografar arquivos locais

Uso do SDK de criptografia para criptografar e descriptografar arquivos locais

Atualizado em 2024-09-14 GMT+08:00

Você pode usar certos algoritmos para criptografar seus arquivos, protegendo-os contra violação ou adulteração.

O SDK de criptografia é uma biblioteca de senhas de cliente que pode criptografar e descriptografar fluxos de dados e arquivos. Você pode facilmente criptografar e descriptografar grandes quantidades de dados simplesmente chamando APIs. Ele permite que você se concentre no desenvolvimento das principais funções de suas aplicações sem se distrair com os processos de criptografia e descriptografia de dados.

Para mais informações, visite. Para obter detalhes, consulte Detalhes.

Cenário

Se arquivos e imagens grandes forem enviados ao KMS por meio de HTTPS para criptografia, um grande número de recursos de rede será consumido e a criptografia será lenta. Esta seção descreve como criptografar rapidamente uma grande quantidade de dados.

Solução

O SDK de criptografia executa a criptografia de envelope em fluxos de arquivos, segmento por segmento.

Os dados são criptografados no SDK usando a DEK gerada pelo KMS. A criptografia segmentada de arquivos na memória garante a segurança e a correção da criptografia de arquivos, porque não requer transferência de arquivos pela rede.

O SDK carrega um arquivo na memória e o processa segmento por segmento. O próximo segmento não será lido antes que a criptografia ou descriptografia do segmento atual seja concluída.

Processo

Procedimento

  1. Obtenha o AK e a SK.

    • ACCESS_KEY: chave de acesso da conta da Huawei. Para obter detalhes, consulte Como obter uma chave de acesso (AK/SK)?
    • SECRET_ACCESS_KEY: chave de acesso de segredo da conta da Huawei. Para obter detalhes, consulte Como obter uma chave de acesso (AK/SK)?
    • Haverá riscos de segurança se a AK/SK usada para autenticação for gravada diretamente no código. Criptografe a AK/SK no arquivo de configuração ou nas variáveis de ambiente para armazenamento.
    • Neste exemplo, a AK/SK armazenada nas variáveis de ambiente é usada para autenticação de identidade. Configure as variáveis de ambiente HUAWEICLOUD_SDK_AK e HUAWEICLOUD_SDK_SK primeiro no ambiente local.

  2. Obtenha informações da região.

    1. Faça logon no console de gerenciamento.
    2. Passe o mouse sobre o nome de usuário no canto superior direito e escolha My Credentials na lista suspensa.
    3. Obtenha o Project ID e o Project Name.
      Figura 1 Obtenção do ID e do nome do projeto
    4. Clique em . Escolha Security & Compliance > Data Encryption Workshop.
    5. Obtenha o ID da CMK (KEYID) a ser usado na região atual.
      Figura 2 Obtenção do ID da CMK
    6. Obtenha o ponto de extremidade (ENDPOINT) exigido pela região atual.

      Um ponto de extremidade é o request address para chamar uma API. Os pontos de extremidade variam de acordo com os serviços e as regiões. Para obter os pontos de extremidade de todos os serviços, consulte Regiões e pontos de extremidade.

      Figura 3 Obtenção de um ponto de extremidade

  3. Criptografe e descriptografe um arquivo.

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

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Conteúdo selecionado

Envie o conteúdo selecionado com o feedback