Paolo Ramos
Paolo Ramos

Reputation: 113

Import key programmatically to Azure Key Vault

Im able to import keys to Key Vault via PowerShell. Now I want to make a web interface to import the keys. I tried using KeyVaultClient.ImportKeyAsync() function but Im stuck with the keyBundle parameter. I understand that keyBundle is returned from the KeyVault. I have no idea how to convert the PFX file to keyBundle. Is there any extension method similar to the Add-AzureKeyVaultKey cmdlet, where I pass the file path and password? Or a method to convert PFX to keyBundle?

Upvotes: 0

Views: 787

Answers (1)

user6656930
user6656930

Reputation:

It's not quite as easy as a single method, but this should do the trick in .Net 4.6.1. It will only work for PFX that contain RSA keys, but that's essentially the only thing supported by both PFX and KeyVault. Here's the code:

X509Certificate2 cert = new X509Certificate2(
    pfxBytes,
    password,
    X509KeyStorageFlags.Exportable);

using (RSA rsa = cert.GetRSAPrivateKey())
{
    var parameters = rsa.ExportParameters(true);

    KeyBundle bundle = new KeyBundle
    {
        Key = new JsonWebKey
        {
            Kty = JsonWebKeyType.Rsa,
            // Private stuff
            D = parameters.D,
            DP = parameters.DP,
            DQ = parameters.DQ,
            P = parameters.P,
            Q = parameters.Q,
            QI = parameters.InverseQ,
            // Public stuff
            N = parameters.Modulus,
            E = parameters.Exponent,
        },
    };
}

If you are using an older version of .Net, you'd have to use RSA rsa = (RSA) cert.PrivateKey instead of cert.GetRSAPrivateKey(), but the code above is recommended because it handles IDisposable and non-RSA keys more clearly.

Upvotes: 4

Related Questions