Partilhar via


Script do PowerShell para habilitar a criptografia de dados transparente usando sua própria chave

Aplica-se a:Instância Gerenciada SQL do Azure

Este exemplo de script do PowerShell configura a criptografia de dados transparente (TDE) na Instância Gerenciada SQL do Azure, usando uma chave gerenciada pelo cliente do Cofre de Chaves do Azure. Isso é muitas vezes referido como um cenário traga sua própria chave (BYOK) para TDE. Para saber mais, consulte Criptografia de dados transparente do SQL do Azure com chave gerenciada pelo cliente.

Pré-requisitos

Se não tiver uma subscrição do Azure, crie uma conta gratuita do Azure antes de começar.

Nota

Este artigo usa o módulo Azure Az PowerShell, que é o módulo PowerShell recomendado para interagir com o Azure. Para começar a utilizar o módulo Azure PowerShell, veja Instalar o Azure PowerShell. Para saber como migrar para o módulo do Az PowerShell, veja Migrar o Azure PowerShell do AzureRM para o Az.

Utilizar o Azure Cloud Shell

O Azure aloja o Azure Cloud Shell, um ambiente de shell interativo que pode utilizar através do seu browser. Pode utilizar o Bash ou o PowerShell com o Cloud Shell para trabalhar com os serviços do Azure. Você pode usar os comandos pré-instalados do Cloud Shell para executar o código neste artigo, sem precisar instalar nada em seu ambiente local.

Para iniciar o Azure Cloud Shell:

Opção Exemplo/Ligação
Selecione Experimentar no canto superior direito de um bloco de código. A seleção de Experimente não copia automaticamente o código para o Cloud Shell. Screenshot that shows an example of Try It for Azure Cloud Shell.
Aceda a https://shell.azure.com ou selecione o botão Iniciar Cloud Shell para abrir o Cloud Shell no browser. Screenshot that shows how to launch Cloud Shell in a new window.
Selecione o botão Cloud Shell na barra de menus, na parte direita do portal do Azure. Screenshot that shows the Cloud Shell button in the Azure portal

Para executar o código neste artigo no Azure Cloud Shell:

  1. Inicie o Cloud Shell.

  2. Selecione o botão Copiar num bloco de código para copiar o código.

  3. Cole o código na sessão do Cloud Shell selecionando Ctrl+Shift V no Windows e Linux ou selecionando Cmd+Shift++V no macOS.

  4. Selecione Introduzir para executar o código.

Usar o PowerShell localmente ou usar o Azure Cloud Shell requer o Azure PowerShell 2.3.2 ou uma versão posterior. Se você precisar atualizar, consulte Instalar o módulo do Azure PowerShell ou execute o script de exemplo abaixo para instalar o módulo para o usuário atual:

Install-Module -Name Az -AllowClobber -Scope CurrentUser

Se estiver a executar localmente o PowerShell, também terá de executar o Connect-AzAccount para criar uma ligação com o Azure.

Scripts de exemplo

# You will need an existing Managed Instance as a prerequisite for completing this script.
# See https://docs.microsoft.com/en-us/azure/sql-database/scripts/sql-database-create-configure-managed-instance-powershell

# Log in to your Azure account:
Connect-AzAccount

# If there are multiple subscriptions, choose the one where AKV is created: 
Set-AzContext -SubscriptionId "subscription ID"

# Install the Az.Sql PowerShell package if you are running this PowerShell locally (uncomment below):
# Install-Module -Name Az.Sql

# 1. Create Resource and setup Azure Key Vault (skip if already done)

# Create Resource group (name the resource and specify the location)
$location = "westus2" # specify the location
$resourcegroup = "MyRG" # specify a new RG name
New-AzResourceGroup -Name $resourcegroup -Location $location

# Create new Azure Key Vault with a globally unique VaultName and soft-delete option turned on:
$vaultname = "MyKeyVault" # specify a globally unique VaultName
New-AzKeyVault -VaultName $vaultname -ResourceGroupName $resourcegroup -Location $location

# Authorize Managed Instance to use the AKV (wrap/unwrap key and get public part of key, if public part exists): 
$objectid = (Set-AzSqlInstance -ResourceGroupName $resourcegroup -Name "MyManagedInstance" -AssignIdentity).Identity.PrincipalId
Set-AzKeyVaultAccessPolicy -BypassObjectIdValidation -VaultName $vaultname -ObjectId $objectid -PermissionsToKeys get,wrapKey,unwrapKey

# Allow access from trusted Azure services: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -Bypass AzureServices

# Allow access from your client IP address(es) to be able to complete remaining steps: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -IpAddressRange "xxx.xxx.xxx.xxx/xx"

# Turn the network rules ON by setting the default action to Deny: 
Update-AzKeyVaultNetworkRuleSet -VaultName $vaultname -DefaultAction Deny


# 2. Provide TDE Protector key (skip if already done)

# First, give yourself necessary permissions on the AKV, (specify your account instead of contoso.com):
Set-AzKeyVaultAccessPolicy -VaultName $vaultname -UserPrincipalName "myaccount@contoso.com" -PermissionsToKeys create,import,get,list

# The recommended way is to import an existing key from a .pfx file. Replace "<PFX private key password>" with the actual password below:
$keypath = "c:\some_path\mytdekey.pfx" # Supply your .pfx path and name
$securepfxpwd = ConvertTo-SecureString -String "<PFX private key password>" -AsPlainText -Force 
$key = Add-AzKeyVaultKey -VaultName $vaultname -Name "MyTDEKey" -KeyFilePath $keypath -KeyFilePassword $securepfxpwd

# ...or get an existing key from the vault:
# $key = Get-AzKeyVaultKey -VaultName $vaultname -Name "MyTDEKey"

# Alternatively, generate a new key directly in Azure Key Vault (recommended for test purposes only - uncomment below):
# $key = Add-AzureKeyVaultKey -VaultName $vaultname -Name MyTDEKey -Destination Software -Size 2048

# 3. Set up BYOK TDE on Managed Instance:

# Assign the key to the Managed Instance:
# $key = 'https://contoso.vault.azure.net/keys/contosokey/01234567890123456789012345678901'
Add-AzSqlInstanceKeyVaultKey -KeyId $key.id -InstanceName "MyManagedInstance" -ResourceGroupName $resourcegroup

# Set TDE operation mode to BYOK: 
Set-AzSqlInstanceTransparentDataEncryptionProtector -Type AzureKeyVault -InstanceName "MyManagedInstance" -ResourceGroup $resourcegroup -KeyId $key.id

Próximos passos

Para obter mais informações sobre o Azure PowerShell, consulte a documentação do Azure PowerShell.

Exemplos de script adicionais do PowerShell para Instância Gerenciada SQL podem ser encontrados em scripts PowerShell da Instância Gerenciada SQL do Azure.