【问题标题】:Import key programmatically to Azure Key Vault以编程方式将密钥导入 Azure Key Vault
【发布时间】:2016-07-30 16:02:31
【问题描述】:

我能够通过 PowerShell 将密钥导入 Key Vault。现在我想制作一个 Web 界面来导入密钥。 我尝试使用 KeyVaultClient.ImportKeyAsync() 函数,但我坚持使用 keyBundle 参数。我了解 keyBundle 是从 KeyVault 返回的。我不知道如何将 PFX 文件转换为 keyBundle。 是否有任何类似于 Add-AzureKeyVaultKey cmdlet 的扩展方法,我在其中传递文件路径和密码?还是一种将 PFX 转换为 keyBundle 的方法?

【问题讨论】:

    标签: azure azure-keyvault


    【解决方案1】:

    它不像单一方法那么简单,但这应该可以在 .Net 4.6.1 中解决问题。它仅适用于包含 RSA 密钥的 PFX,但这基本上是 PFX 和 KeyVault 都支持的唯一内容。代码如下:

    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,
            },
        };
    }
    

    如果您使用的是旧版本的 .Net,则必须使用 RSA rsa = (RSA) cert.PrivateKey 而不是 cert.GetRSAPrivateKey(),但建议使用上面的代码,因为它可以更清楚地处理 IDisposable 和非 RSA 密钥。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多