James S.
James S.

Reputation: 150

Import EC Key into Key Vault

The Azure web portal only allows importing RSA keys into Key Vault. You can generate an EC key but not import one. Is there a way to programmatically import an EC key?

EDIT

My solution:

$p8Raw = Get-Content -Path .\KEY.p8 | ? {$_ -ne '-----BEGIN PRIVATE KEY-----' -and $_ -ne '-----END PRIVATE KEY-----'}
$p8Bytes = [System.Convert]::FromBase64String($p8Raw -join '')

$cng = [System.Security.Cryptography.ECDsaCng]::Create()
$len = $null
$cng.ImportPkcs8PrivateKey($p8Bytes, [ref] $len)
$params = $cng.ExportParameters($true)

$ToBase64Url = { Param($Content) [System.Convert]::ToBase64String($Content).Replace('+', '-').Replace('/', '_').Replace('=', '') }

$pubX = & $ToBase64Url -Content $params.Q.X
$pubY = & $ToBase64Url -Content $params.Q.Y
$prvD = & $ToBase64Url -Content $params.D
$jwk = @{ crv = 'P-256'; d = $prvD; kty = 'EC'; x = $pubX; y = $pubY }
$RequestPayload = @{ key = $jwk } | ConvertTo-Json

$token = Get-MsalToken -Scope 'https://vault.azure.net/user_impersonation' -ClientId $ClientId -TenantId $TenantId -Interactive

Invoke-WebRequest -Uri "${VaultUri}keys/${KeyName}?api-version=7.3" -Authentication Bearer -Token ($token.AccessToken | ConvertTo-SecureString -AsPlainText -Force) -Method Put -Body $RequestPayload -ContentType 'application/json'

Upvotes: 0

Views: 1041

Answers (2)

Craig McGregor
Craig McGregor

Reputation: 51

I would have gone with the supported Powershell cmdlets or Azure CLI.

  • Import-AzKeyvaultKey from powershell.
  • az keyvault key import from Azure CLI.

https://learn.microsoft.com/en-us/powershell/module/az.keyvault/add-azkeyvaultkey?view=azps-8.0.0

https://learn.microsoft.com/en-us/cli/azure/keyvault/key?view=azure-cli-latest#az-keyvault-key-import

Upvotes: 0

Esta Nagy
Esta Nagy

Reputation: 319

This REST endpoint should be able to do it based on this line:

The import key operation may be used to import any key type into an Azure Key Vault.

I think the easiest would be to use any of the official SDKs (Java,.Net, Python, etc.) but if you are willing to put together the right HTTP request, that should work too.

Upvotes: 1

Related Questions