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
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

Encriptación o descifrado de una gran cantidad de datos

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

Escenario

Si desea encriptar o descifrar grandes volúmenes de datos, como imágenes, videos y archivos de bases de datos, puede utilizar la encriptación de sobres, que permite encriptar o descifrar archivos sin tener que transferir una gran cantidad de datos por la red.

Procesos de encriptación o descifrado

  • Encriptación de datos de gran tamaño
    Figura 1 Cifrado de un archivo local

    El proceso es el siguiente:

    1. Crear una CMK en KMS.
    2. Invocar a la API create-datakey de KMS para crear una DEK. Se generará una DEK en texto plano y una DEK en texto encriptado. La DEK de texto encriptado se genera cuando se utiliza una CMK para encriptar la DEK de texto plano.
    3. Utilice la DEK de texto plano para cifrar un archivo de texto plano, generando un archivo de texto cifrado.
    4. Almacene la DEK de texto cifrado y el archivo de texto cifrado juntos en un dispositivo de almacenamiento permanente o en un servicio de almacenamiento.
  • Descifrado de datos de gran tamaño
    Figura 2 Descifrar un archivo local

    El proceso es el siguiente:
    1. Lea la DEK de texto cifrado y el archivo de texto cifrado desde el dispositivo de almacenamiento permanente o servicio de almacenamiento.
    2. Invoque a la API de decrypt-datakey de KMS y use la CMK correspondiente (el utilizado para cifrar la DEK) para descifrar la DEK de texto cifrado. Luego obtiene la DEK de texto plano.

      Si se elimina la CMK, el descifrado fallará. Mantenga sus CMK correctamente.

    3. Utilice la DEK de texto plano para descifrar el archivo de texto cifrado.

API relacionadas con la encriptación de sobre

Puede utilizar las siguientes API para cifrar y descifrar datos.

API

Descripción

Creación de una DEK

Crear una DEK.

Encriptación de una DEK

Cifrar una DEK con la clave principal especificada.

Descifrado de una DEK

Descifrar una DEK con la clave principal especificada.

Cifrado de un archivo local

  1. Crear una CMK en la consola de gestión. Para obtener más detalles, consulte Creación de una CMK.
  2. Preparar la información básica de autenticación.
    • ACCESS_KEY: clave de acceso del ID de Huawei
    • SECRET_ACCESS_KEY: clave de acceso secreta del ID de Huawei
    • PROJECT_ID: ID de proyecto de un sitio de Huawei Cloud. Para obtener más detalles, véase Proyecto.
    • KMS_ENDPOINT: punto de conexión para acceder a la KMS. Consulte Puntos de conexión para obtener más detalles.
    • 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.
  3. Cifrar un archivo local.

    El código de ejemplo es el siguiente.

    • CMK es el ID de la clave creada en la consola de gestión de Huawei Cloud.
    • FirstPlainFile.jpg es el archivo de datos de texto plano.
    • El archivo de datos generado tras la encriptación es SecondEncryptFile.jpg.
      import com.huaweicloud.sdk.core.auth.BasicCredentials;
      import com.huaweicloud.sdk.kms.v1.KmsClient;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyRequest;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyRequestBody;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyResponse;
      import com.huaweicloud.sdk.kms.v1.model.DecryptDatakeyRequest;
      import com.huaweicloud.sdk.kms.v1.model.DecryptDatakeyRequestBody;
      
      import javax.crypto.Cipher;
      import javax.crypto.spec.GCMParameterSpec;
      import javax.crypto.spec.SecretKeySpec;
      import java.io.BufferedInputStream;
      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.nio.file.Files;
      import java.security.SecureRandom;
      
      /**
      * Use a DEK to encrypt and decrypt files.
      * To enable the assert syntax, add -ea to enable VM_OPTIONS.
       */
      public class FileStreamEncryptionExample {
      
          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 KMS_ENDPOINT = "<KmsEndpoint>";
      
      //Version of the KMS interface. Currently, the value is fixed to v1.0.
          private static final String KMS_INTERFACE_VERSION = "v1.0";
      
          /**
           * AES algorithm flags:
           * - AES_KEY_BIT_LENGTH: bit length of the AES256 key
            * - AES_KEY_BYTE_LENGTH: byte length of the AES256 key
           * - AES_ALG: AES256 algorithm. In this example, the Group mode is GCM and the padding mode is PKCS5Padding.
           * - AES_FLAG: AES algorithm flag
           * - GCM_TAG_LENGTH: GCM tag length
           * - GCM_IV_LENGTH: length of the GCM initial vector
           */
          private static final String AES_KEY_BIT_LENGTH = "256";
          private static final String AES_KEY_BYTE_LENGTH = "32";
          private static final String AES_ALG = "AES/GCM/PKCS5Padding";
          private static final String AES_FLAG = "AES";
          private static final int GCM_TAG_LENGTH = 16;
          private static final int GCM_IV_LENGTH = 12;
      
          public static void main(final String[] args) {
              // ID of the CMK you created on the HUAWEI CLOUD management console
              final String keyId = args[0];
      
              encryptFile(keyId);
          }
      
          /**
           * Using a DEK to encrypt and decrypt a file
           *
           * @param keyId: user CMK ID
           */
          static void encryptFile(String keyId) {
              // 1. Prepare the authentication information for accessing HUAWEI CLOUD.
              final BasicCredentials auth = new BasicCredentials().withAk(ACCESS_KEY).withSk(SECRET_ACCESS_KEY)
                      .withProjectId(PROJECT_ID);
      
              // 2. Initialize the SDK and transfer the authentication information and the address for the KMS to access the client.
              final KmsClient kmsClient = KmsClient.newBuilder().withCredential(auth).withEndpoint(KMS_ENDPOINT).build();
      
              // 3. Assemble the request message for creating a DEK.
              final CreateDatakeyRequest createDatakeyRequest = new CreateDatakeyRequest().withVersionId(KMS_INTERFACE_VERSION)
                      .withBody(new CreateDatakeyRequestBody().withKeyId(keyId).withDatakeyLength(AES_KEY_BIT_LENGTH));
      
              // 4. Create a DEK.
              final CreateDatakeyResponse createDatakeyResponse = kmsClient.createDatakey(createDatakeyRequest);
      
              // 5. Receive the created DEK information.
              // It is recommended that the ciphertext key and key ID be stored locally so that the plaintext key can be easily obtained for data decryption.
              // The plaintext key should be used immediately after being created. Before using it, convert the hexadecimal plaintext key to a byte array.
              final String cipherText = createDatakeyResponse.getCipherText();
              final byte[] plainKey = hexToBytes(createDatakeyResponse.getPlainText());
      
              // 6. Prepare the file to be encrypted.
              // inFile: file to be encrypted
              // outEncryptFile: file generated after encryption
              final File inFile = new File("FirstPlainFile.jpg");
              final File outEncryptFile = new File("SecondEncryptFile.jpg");
      
              // 7. If the AES algorithm is used for encryption, you can create an initial vector.
              final byte[] iv = new byte[GCM_IV_LENGTH];
              final SecureRandom secureRandom = new SecureRandom();
              secureRandom.nextBytes(iv);
      
              // 8. Encrypt the file and store the encrypted file.
              doFileFinal(Cipher.ENCRYPT_MODE, inFile, outEncryptFile, plainKey, iv);
      
          }
      
          /**
           * Encrypting and decrypting a file
           *
           * @param cipherMode: Encryption mode. It can be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE.
           * @param infile: file to be encrypted or decrypted
           * @param outFile: file generated after encryption and decryption
           * @param keyPlain: plaintext key
           * @param iv: initial vector
           */
          static void doFileFinal(int cipherMode, File infile, File outFile, byte[] keyPlain, byte[] iv) {
      
              try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(infile));
                   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile))) {
                  final byte[] bytIn = new byte[(int) infile.length()];
                  final int fileLength = bis.read(bytIn);
      
                  assert fileLength > 0;
      
                  final SecretKeySpec secretKeySpec = new SecretKeySpec(keyPlain, AES_FLAG);
                  final Cipher cipher = Cipher.getInstance(AES_ALG);
                  final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, iv);
                  cipher.init(cipherMode, secretKeySpec, gcmParameterSpec);
                  final byte[] bytOut = cipher.doFinal(bytIn);
                  bos.write(bytOut);
              } catch (Exception e) {
                  throw new RuntimeException(e.getMessage());
              }
          }
      
      }

Descifrado de un archivo local

  1. Preparar la información básica de autenticación.
    • ACCESS_KEY: clave de acceso del ID de Huawei
    • SECRET_ACCESS_KEY: clave de acceso secreta del ID de Huawei
    • PROJECT_ID: ID de proyecto de un sitio de Huawei Cloud. Para obtener más detalles, véase Proyecto.
    • KMS_ENDPOINT: punto de conexión para acceder a la KMS. Consulte Puntos de conexión para obtener más detalles.
    • 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. Descifrar un archivo local.

    El código de ejemplo es el siguiente.

    • CMK es el ID de la clave creada en la consola de gestión de Huawei Cloud.
    • El archivo de datos generado tras la encriptación es SecondEncryptFile.jpg.
    • El archivo de datos generado tras la encriptación y desencriptación es ThirdDecryptFile.jpg.
      import com.huaweicloud.sdk.core.auth.BasicCredentials;
      import com.huaweicloud.sdk.kms.v1.KmsClient;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyRequest;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyRequestBody;
      import com.huaweicloud.sdk.kms.v1.model.CreateDatakeyResponse;
      import com.huaweicloud.sdk.kms.v1.model.DecryptDatakeyRequest;
      import com.huaweicloud.sdk.kms.v1.model.DecryptDatakeyRequestBody;
      
      import javax.crypto.Cipher;
      import javax.crypto.spec.GCMParameterSpec;
      import javax.crypto.spec.SecretKeySpec;
      import java.io.BufferedInputStream;
      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.nio.file.Files;
      import java.security.SecureRandom;
      
      /**
      * Use a DEK to encrypt and decrypt files.
      * To enable the assert syntax, add -ea to enable VM_OPTIONS.
       */
      public class FileStreamEncryptionExample {
      
          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 KMS_ENDPOINT = "<KmsEndpoint>";
      
      
      //Version of the KMS interface. Currently, the value is fixed to v1.0.
          private static final String KMS_INTERFACE_VERSION = "v1.0";
      
          /**
           * AES algorithm flags:
           * - AES_KEY_BIT_LENGTH: bit length of the AES256 key
            * - AES_KEY_BYTE_LENGTH: byte length of the AES256 key
           * - AES_ALG: AES256 algorithm. In this example, the Group mode is GCM and the padding mode is PKCS5Padding.
           * - AES_FLAG: AES algorithm flag
           * - GCM_TAG_LENGTH: GCM tag length
           * - GCM_IV_LENGTH: length of the GCM initial vector
           */
          private static final String AES_KEY_BIT_LENGTH = "256";
          private static final String AES_KEY_BYTE_LENGTH = "32";
          private static final String AES_ALG = "AES/GCM/PKCS5Padding";
          private static final String AES_FLAG = "AES";
          private static final int GCM_TAG_LENGTH = 16;
          private static final int GCM_IV_LENGTH = 12;
      
          public static void main(final String[] args) {
              // ID of the CMK you created on the HUAWEI CLOUD management console
              final String keyId = args[0];
              // // Returned ciphertext DEK after DEK creation
              final String cipherText = args[1];
      
              decryptFile(keyId, cipherText);
          }
      
          /**
           * Using a DEK to encrypt and decrypt a file
           *
           * @param keyId: user CMK ID
           * @param cipherText: ciphertext data key
           */
          static void decryptFile(String keyId, String cipherText) {
              // 1. Prepare the authentication information for accessing HUAWEI CLOUD.
              final BasicCredentials auth = new BasicCredentials().withAk(ACCESS_KEY).withSk(SECRET_ACCESS_KEY)
                      .withProjectId(PROJECT_ID);
      
              // 2. Initialize the SDK and transfer the authentication information and the address for the KMS to access the client.
              final KmsClient kmsClient = KmsClient.newBuilder().withCredential(auth).withEndpoint(KMS_ENDPOINT).build();
      
              // 3. Prepare the file to be encrypted.
              // inFile: file to be encrypted
              // outEncryptFile: file generated after encryption
              // outDecryptFile: file generated after encryption and decryption
              final File inFile = new File("FirstPlainFile.jpg");
              final File outEncryptFile = new File("SecondEncryptFile.jpg");
              final File outDecryptFile = new File("ThirdDecryptFile.jpg");
      
              // 4. Use the same initial vector for AES encryption and decryption.
              final byte[] iv = new byte[GCM_IV_LENGTH];
              // 5. Assemble the request message for decrypting the DEK. cipherText is the ciphertext DEK returned after DEK creation.
              final DecryptDatakeyRequest decryptDatakeyRequest = new DecryptDatakeyRequest()
                      .withVersionId(KMS_INTERFACE_VERSION).withBody(new DecryptDatakeyRequestBody()
                              .withKeyId(keyId).withCipherText(cipherText).withDatakeyCipherLength(AES_KEY_BYTE_LENGTH));
      
              // 6. Decrypt the DEK and convert the returned hexadecimal plaintext key into a byte array.
              final byte[] decryptDataKey = hexToBytes(kmsClient.decryptDatakey(decryptDatakeyRequest).getDataKey());
      
              // 7. Decrypt the file and store the decrypted file.
      // iv at the end of the statement is the initial vector created in the encryption example.
              doFileFinal(Cipher.DECRYPT_MODE, outEncryptFile, outDecryptFile, decryptDataKey, iv);
      
              // 8. Compare the original file with the decrypted file.
              assert getFileSha256Sum(inFile).equals(getFileSha256Sum(outDecryptFile));
      
          }
      
          /**
           * Encrypting and decrypting a file
           *
           * @param cipherMode: Encryption mode. It can be Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE.
           * @param infile: file to be encrypted or decrypted
           * @param outFile: file generated after encryption and decryption
           * @param keyPlain: plaintext key
           * @param iv: initial vector
           */
          static void doFileFinal(int cipherMode, File infile, File outFile, byte[] keyPlain, byte[] iv) {
      
              try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(infile));
                   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile))) {
                  final byte[] bytIn = new byte[(int) infile.length()];
                  final int fileLength = bis.read(bytIn);
      
                  assert fileLength > 0;
      
                  final SecretKeySpec secretKeySpec = new SecretKeySpec(keyPlain, AES_FLAG);
                  final Cipher cipher = Cipher.getInstance(AES_ALG);
                  final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * Byte.SIZE, iv);
                  cipher.init(cipherMode, secretKeySpec, gcmParameterSpec);
                  final byte[] bytOut = cipher.doFinal(bytIn);
                  bos.write(bytOut);
              } catch (Exception e) {
                  throw new RuntimeException(e.getMessage());
              }
          }
      
          /**
      * Converting a hexadecimal string to a byte array
           *
           * @param hexString: a hexadecimal string
           * @return: byte array
           */
          static byte[] hexToBytes(String hexString) {
              final int stringLength = hexString.length();
              assert stringLength > 0;
              final byte[] result = new byte[stringLength / 2];
              int j = 0;
              for (int i = 0; i < stringLength; i += 2) {
                  result[j++] = (byte) Integer.parseInt(hexString.substring(i, i + 2), 16);
              }
              return result;
          }
      
          /**
           * Calculate the SHA256 digest of the file.
           *     
           * @param file
           * @return SHA256 digest
           */    
           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 new BigInteger(1, sha256.digest()).toString(16);
              } catch (IOException e) {
                  throw new RuntimeException(e.getMessage());
              }
          }
      }

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