- Visão geral de serviço
-
Guia de usuário
- Serviço de gerenciamento de chaves
- Serviço de gerenciamento de segredo em nuvem
- Serviço de par de chaves
- HSM dedicado
- Registros de auditoria
- Controle de permissão
-
Referência de API
- Antes de começar
- Chamada das APIs
- Visão geral de API
-
APIs
- APIs de gerenciamento de chaves
- APIs de gerenciamento de pares de chaves
- APIs de gerenciamento de segredo
- APIs históricas
- Exemplos de aplicação
- Políticas de permissões e ações suportadas
- Apêndice
- Histórico de mudanças
-
Melhores práticas
-
Serviço de gerenciamento de chaves
- Uso do KMS para criptografar dados off-line
- Uso do KMS para criptografar e descriptografar dados para serviços em nuvem
- Uso do SDK de criptografia para criptografar e descriptografar arquivos locais
- Criptografia e descriptografia de dados por meio de DR entre regiões
- Uso do KMS para proteger a integridade dos arquivos
- Serviço de gerenciamento de segredo em nuvem
- Geral
- Histórico de alterações
-
Serviço de gerenciamento de chaves
- Primeiros passos
-
Perguntas frequentes
- Serviço de gerenciamento de chaves
- Serviço de gerenciamento de segredo em nuvem
- Serviço de par de chaves
- HSM dedicado
- Registros de auditoria
- Controle de permissão
-
Perguntas frequentes
-
Relacionado ao KMS
- O que é o serviço de gerenciamento de chaves?
- O que é uma Chave principal do cliente?
- O que é uma chave padrão?
- Quais são as diferenças entre uma chave personalizada e uma chave padrão?
- O que é uma chave de criptografia de dados?
- Por que não consigo excluir uma CMK imediatamente?
- Quais serviços de nuvem podem usar o KMS para criptografia?
- Como os serviços da Huawei Cloud usam o KMS para criptografar dados?
- Quais são os benefícios da criptografia de envelope?
- Existe um limite para o número de chaves personalizadas que posso criar no KMS?
- Posso exportar uma CMK do KMS?
- Posso descriptografar meus dados se eu excluir permanentemente minha chave personalizada?
- Como usar a ferramenta on-line para criptografar ou descriptografar pequenos volumes de dados?
- Posso atualizar CMKs criadas por materiais de chave gerados por KMS?
- Quando devo usar uma CMK criada com materiais de chaves importados?
- O que devo fazer quando excluir acidentalmente materiais de chaves?
- Como as chaves padrão são geradas?
- O que devo fazer se não tiver as permissões para realizar operações no KMS?
- Por que não posso encapsular chaves assimétricas usando -id-aes256-wrap-pad no OpenSSL?
- Algoritmos de chave suportados pelo KMS
- O que devo fazer se o KMS não for solicitado e o código de erro 401 for exibido?
- Qual é a relação entre o texto cifrado e o texto não criptografado retornado pela API de dados de criptografia?
- Como o KMS protege minhas chaves?
- Como usar uma chave assimétrica para verificar o resultado da assinatura de um par de chaves públicas?
- Uma chave importada suporta rotação?
- Relacionado a credenciais
-
Relacionado ao KPS
- Como criar um par de chaves?
- O que são um par de chaves privadas e um par de chaves de contas?
- Como lidar com uma falha de importação de um par de chaves criado usando o PuTTYgen?
- O que devo fazer quando não consigo importar um par de chaves usando o Internet Explorer 9?
- Como fazer logon em um ECS de Linux com uma chave privada?
- Como usar uma chave privada para obter a senha para fazer logon em um ECS do Windows?
- Como lidar com a falha na vinculação de um par de chaves?
- Como lidar com a falha na substituição de um par de chaves?
- Como lidar com a falha na redefinição de um par de chaves?
- Como lidar com a falha na desvinculação de um par de chaves?
- Preciso reiniciar os servidores depois de substituir seu par de chaves?
- Como ativar o modo de logon com senha para um ECS?
- Como lidar com a falha no logon no ECS após desvincular o par de chaves?
- O que devo fazer se minha chave privada for perdida?
- Como converter o formato de um arquivo de chave privada?
- Posso alterar o par de chaves de um servidor?
- Um par de chaves pode ser compartilhado por vários usuários?
- Como obter o arquivo de chave pública ou privada de um par de chaves?
- O que posso fazer se um erro for relatado quando uma chave de conta for criada ou atualizada pela primeira vez?
- A cota de par de chaves de conta será ocupada depois que um par de chaves privadas for atualizado para um par de chaves de conta?
-
Relacionado ao HSM dedicado
- O que é o HSM dedicado?
- Como o HSM dedicado garante a segurança para a geração de chaves?
- O pessoal da sala de equipamentos tem a função de superadministrador para roubar informações usando um UKey privilegiado?
- Quais HSMs são usados para HSM dedicado?
- Quais APIs o HSM dedicado suporta?
- Como ativar o acesso público a uma instância do HSM dedicado?
- Preços
- Geral
-
Relacionado ao KMS
- No momento, o conteúdo não está disponível no seu idioma selecionado. Consulte a versão em inglês.
- What's New
- Function Overview
- Billing
- SDK Reference
- Videos
-
More Documents
- User Guide (ME-Abu Dhabi Region)
- User Guide (Paris and Amsterdam Regions)
-
User Guide (Kuala Lumpur Region)
- Service Overview
-
User Guide
- Key Management Service
- Cloud Secret Management Service
- Auditing Logs
- Permission Control
-
FAQs
-
KMS Related
- What Is Key Management Service?
- What Is a Customer Master Key?
- What Is a Default Key?
- What Are the Differences Between a Custom Key and a Default Key?
- What Is a Data Encryption Key?
- Why Cannot I Delete a CMK Immediately?
- Which Cloud Services Can Use KMS for Encryption?
- How Do Cloud Services Use KMS to Encrypt Data?
- What Are the Benefits of Envelope Encryption?
- Is There a Limit on the Number of Custom Keys That I Can Create on KMS?
- Can I Export a CMK from KMS?
- Can I Decrypt My Data if I Permanently Delete My Custom Key?
- How Do I Use the Online Tool to Encrypt or Decrypt Small Volumes of Data?
- Can I Update CMKs Created by KMS-Generated Key Materials?
- When Should I Use a CMK Created with Imported Key Materials?
- What Types of Keys Can I Import?
- What Should I Do When I Accidentally Delete Key Materials?
- How Are Default Keys Generated?
- What Should I Do If I Do Not Have the Permissions to Perform Operations on KMS?
- Why Can't I Wrap Asymmetric Keys by Using -id-aes256-wrap-pad in OpenSSL?
- Key Algorithms Supported by KMS
- What Should I Do If KMS Failed to Be Requested and Error Code 401 Is Displayed?
- What Is the Relationship Between the Ciphertext and Plaintext Returned by the encrypt-data API?
- How Does KMS Protect My Keys?
- Credential Related
-
KMS Related
- Change History
-
API Reference (ME-Abu Dhabi Region)
- Before You Start
- Calling APIs
- API Overview
-
APIs
- Creating a CMK
- Enabling a CMK
- Disabling a CMK
- Scheduling the Deletion of a CMK
- Canceling the Scheduled Deletion of a CMK
- Querying the List of CMKs
- Querying the Information About a CMK
- Creating a Random Number
- Creating a DEK
- Creating a Plaintext-Free DEK
- Encrypting a DEK
- Decrypting a DEK
- Querying the Number of Instances
- Querying the Quota of a User
- Changing the Alias of a CMK
- Changing the Description of a CMK
- Encrypting Data
- Decrypting Data
- Obtaining CMK Import Parameters
- Importing CMK Material
- Deleting CMK Material
- Querying CMK Instances
- Querying CMK Tags
- Querying Project Tags
- Adding or Deleting CMK Tags in Batches
- Adding a CMK Tag
- Deleting a CMK Tag
- Permissions Policies and Supported Actions
- Appendix
- Change History
-
API Reference (Paris and Amsterdam Regions)
- Before You Start
- Calling APIs
- API Overview
-
APIs
- Creating a CMK
- Enabling a CMK
- Disabling a CMK
- Scheduling the Deletion of a CMK
- Canceling the Scheduled Deletion of a CMK
- Querying the List of CMKs
- Querying the Information About a CMK
- Creating a Random Number
- Creating a DEK
- Creating a Plaintext-Free DEK
- Encrypting a DEK
- Decrypting a DEK
- Querying the Number of Instances
- Querying the Quota of a User
- Changing the Alias of a CMK
- Changing the Description of a CMK
- Creating a Grant
- Revoking a Grant
- Retiring a Grant
- Querying Grants on a CMK
- Querying Grants That Can Be Retired
- Encrypting Data
- Decrypting Data
- Obtaining CMK Import Parameters
- Importing CMK Material
- Deleting CMK Material
- Enabling Rotation for a CMK
- Changing the Rotation Interval for a CMK
- Disabling Rotation for a CMK
- Querying the Rotation Status of a CMK
- Appendix
- Change History
-
API Reference (Kuala Lumpur Region)
- Before You Start
- Calling APIs
- API Overview
-
APIs
- Creating a CMK
- Enabling a CMK
- Disabling a CMK
- Scheduling the Deletion of a CMK
- Canceling the Scheduled Deletion of a CMK
- Querying the List of CMKs
- Querying the Information About a CMK
- Creating a Random Number
- Creating a DEK
- Creating a Plaintext-Free DEK
- Encrypting a DEK
- Decrypting a DEK
- Querying the Number of Instances
- Querying the Quota of a User
- Changing the Alias of a CMK
- Changing the Description of a CMK
- Creating a Grant
- Revoking a Grant
- Retiring a Grant
- Querying Grants on a CMK
- Querying Grants That Can Be Retired
- Encrypting Data
- Decrypting Data
- Obtaining CMK Import Parameters
- Importing CMK Material
- Deleting CMK Material
- Enabling Rotation for a CMK
- Changing the Rotation Interval for a CMK
- Disabling Rotation for a CMK
- Querying the Rotation Status of a CMK
- Appendix
- Change History
Mostrar todos
Copiado.
Uso do KMS para proteger a integridade dos arquivos
Cenário
Quando uma grande quantidade de arquivos (como imagens, apólices de seguro eletrônicas e arquivos importantes) precisar ser transmitida ou armazenada com segurança, você poderá usar o KMS para assinar o resumo do arquivo. Quando os arquivos são usados novamente, você pode recalcular o resumo para verificação de assinatura. Certifique-se de que os arquivos não sejam adulterados durante a transmissão ou armazenamento.
Solução
Crie uma CMK no KMS.
Calcule o resumo do arquivo e chame a API de assinatura do KMS para assinar o resumo. O resultado da assinatura do resumo é obtido. Transmita ou armazene o resultado da assinatura do resumo, o ID da chave e o arquivo juntos. A figura a seguir mostra o processo de assinatura.

Antes de usar um arquivo, você precisa verificar a integridade do arquivo para garantir que o arquivo não seja adulterado.
Recalcule o resumo do arquivo e chame a API de verificação do KMS com o valor da assinatura para verificar a assinatura do resumo. O resultado da verificação da assinatura é obtido. Se a assinatura for verificada, o arquivo não foi adulterado. A figura a seguir mostra o processo de verificação de assinatura.

Procedimento
- 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.
- Obtenha informações da região.
- Use o KMS para assinar o arquivo e verificar a assinatura.
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()); } } }