Partilhar via


Script PowerShell para permitir encriptação de dados transparentes usando a sua própria chave

Aplica-se a:Azure SQL Managed Instance

Este exemplo de script PowerShell configura a encriptação de dados transparentes (TDE) no Azure SQL Managed Instance, usando uma chave gerida pelo cliente do Azure Key Vault. Isto é frequentemente referido como cenário de trazer a sua própria chave (BYOK) para TDE. Para saber mais, consulte Azure SQL Transparent Data Encryption com chave gerida pelo cliente.

Pré-requisitos

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

Observação

Este artigo usa o módulo Azure Az PowerShell, que é o módulo PowerShell recomendado para interagir com o Azure. Para começar a usar o módulo Az PowerShell, consulte Instalar o Azure PowerShell. Para saber como migrar para o módulo Az PowerShell, veja Migrate Azure PowerShell from AzureRM to 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. Você pode usar 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. Selecionar Try It não copia automaticamente o código para o Cloud Shell. Captura de tela que mostra um exemplo de Try It for Azure Cloud Shell.
Vá para https://shell.azure.com, ou selecione o botão Iniciar o Cloud Shell para abrir o Cloud Shell no navegador. Captura de tela que mostra como iniciar o Cloud Shell em uma nova janela.
Selecione o botão Cloud Shell na barra de menus no canto superior direito do portal do Azure. Captura de tela que mostra o botão Cloud Shell no portal do Azure

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 precisar de atualizar, consulte Instalar o módulo Azure PowerShell, ou execute o script de exemplo abaixo para instalar o módulo para o utilizador 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.

Exemplos de scripts

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