Estos contenidos se han traducido de forma automática para su comodidad, pero Huawei Cloud no garantiza la exactitud de estos. Para consultar los contenidos originales, acceda a la versión en inglés.
Cómputo
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
Gestión y gobernanza
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
Migración
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álisis
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Otros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Seguridad y cumplimiento
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Servicios multimedia
Media Processing Center
Video On Demand
Live
SparkRTC
Almacenamiento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Contenedores
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Bases de datos
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
Aplicaciones empresariales
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
Distribución de contenido y cómputo de borde
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluciones
SAP Cloud
High Performance Computing
Servicios para desarrolladores
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
aPaaS MacroVerse
KooPhone
KooDrive
En esta página
Centro de ayuda/ Data Encryption Workshop/ Prácticas recomendadas/ Key Management Service/ Uso del SDK de encriptación para cifrar y descifrar datos locales

Uso del SDK de encriptación para cifrar y descifrar datos locales

Actualización más reciente 2024-09-13 GMT+08:00

Puede utilizar determinados algoritmos para encriptar sus archivos, protegiéndolos de posibles violaciones o manipulaciones.

El SDK de encriptación es una biblioteca de contraseñas de cliente que puede cifrar y descifrar datos y flujos de archivos. Puede cifrar y descifrar grandes cantidades de datos simplemente invocando a las API. Le permite concentrarse en el desarrollo de las funciones principales de sus aplicaciones sin distraerse con los procesos de encriptación y descifrado de datos.

NOTA:

Para obtener más detalles, consulte Detalles.

Escenario

Si se envían archivos e imágenes de gran tamaño a KMS por HTTPS para su encriptación, se consumirá un gran número de recursos de red y la encriptación será lenta. En esta sección se describe cómo cifrar rápidamente una gran cantidad de datos.

Solución

El SDK de encriptación realiza la encriptación en sobres en flujos de archivos segmento por segmento.

Los datos se cifran dentro del SDK utilizando la DEK generada por KMS. La encriptación segmentada de archivos en la memoria garantiza la seguridad y la corrección de la encriptación de archivos, ya que no requiere la transferencia de archivos por la red.

El SDK carga un archivo en la memoria y lo procesa segmento por segmento. El siguiente segmento no se leerá antes de que finalice la encriptación o el descifrado del segmento actual.

Proceso

Procedimiento

  1. Obtenga las AK y SK.

    • ACCESS_KEY: Clave de acceso de la cuenta de Huawei. Para obtener más detalles, consulte ¿Cómo obtengo una clave de acceso (AK/SK)?
    • SECRET_ACCESS_KEY: Clave de acceso secreta de la cuenta de Huawei. Para obtener más detalles, consulte ¿Cómo obtengo una clave de acceso (AK/SK)?
    • Habrá riesgos de seguridad si la AK/SK utilizada para la autenticación se escribe directamente en el código. Cifre la AK/SK en el archivo de configuración o en las variables de entorno para su almacenamiento.
    • En este ejemplo, las AK/SK almacenadas en las variables de entorno se utilizan para la autenticación de identidad. Primero configure las variables de entorno HUAWEICLOUD_SDK_AK y HUAWEICLOUD_SDK_SK en el entorno local.

  2. Obtenga información de la región.

    1. Inicie sesión en la consola de gestión.
    2. Pase el ratón por encima del nombre de usuario en la esquina superior derecha y seleccione My Credentials en la lista desplegable.
    3. Obtenga los Project ID y Project Name.
      Figura 1 Obtención del ID y el nombre del proyecto
    4. Haga clic en . Elija Security & Compliance > Data Encryption Workshop.
    5. Obtenga el ID de la CMK (KEYID) que se utilizará en la región actual.
      Figura 2 Obtención del ID de CMK
    6. Obtenga el punto de conexión (ENDPOINT) requerido por la región actual.

      Un punto de conexión es la request address para llamar a una API. Los puntos de conexión varían según los servicios y las regiones. Para ver los puntos de conexión de todos los servicios, consulte Regiones y puntos de conexción.

      Figura 3 Obtención de un punto de conexión

  3. Encriptar y descifrar un archivo.

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

Utilizamos cookies para mejorar nuestro sitio y tu experiencia. Al continuar navegando en nuestro sitio, tú aceptas nuestra política de cookies. Descubre más

Comentarios

Comentarios

Comentarios

0/500

Seleccionar contenido

Enviar el contenido seleccionado con los comentarios