Azure KeyVault 如何加载 X509Certificate?

Azure KeyVault how to load X509Certificate?

我将证书上传到 Azure KeyVault 并使用在 Active Directory 中注册的应用程序获得了对它的 "all" 访问权限。一切正常。现在我需要将获得的密钥加载到 X509Certificate 中,以便能够将其用作调用第 3 方遗留 SOAP Web 服务的客户端证书。据我所知,我只能使用 X509Certificate 来调用该网络服务。

上传为Key还是Secret都没关系?我都试过了。

var clientId = "...."
var clientSecret = "...."

..
var token = authenticationContext.GetAccessToken(resource, adCredential);
var keyClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(token));
KeyBundle key = keyClient.GetKeyAsync("https://mycertifcates.vault.azure.net/keys/MyCertificate/123456789");

到目前为止一切顺利,结果我得到了一个 KeyBundle,似乎我可以将它转换为 Base64String,但无论我尝试什么,我最终都会遇到异常:(

1st attempt I tried:

            var publicKey = Convert.ToBase64String(key.Key.N);
            var cert = X509Certificate.FromBase64String(publicKey);

System.Security.Cryptography.CryptographicException {"Cannot find the requested object.\r\n"}

啊啊啊

2nd attempt, loading it into an RSACryptoServiceProvider, but what to do with that? Results into the same exception and I'm not even able to get the private key if I want to

        var rsaCryptoProvider = new RSACryptoServiceProvider();
        var rsaParameters = new RSAParameters()
        {
            Modulus = key.Key.N,
            Exponent = key.Key.E
        };
        rsaCryptoProvider.ImportParameters(rsaParameters);
        var cspBlob = rsaCryptoProvider.ExportCspBlob(false);

        // what to do with the cspBlob ?
        var publicKey = Convert.ToBase64String(cspBlob);

同样没有私钥,public密钥不同。当然这也不行。

3rd attempt

我使用管理门户将其作为机密证书 ContentType 上传。

            var secret = helper.GetSecret("https://myCertificate.vault.azure.net/secrets/MyCertificate/1234567890");

            var value = secret.Value;

            // Now I got the secret.. works flawless
            // But it crash with the same exception at .Import
            var exportedCertCollection = new X509Certificate2Collection();
            exportedCertCollection.Import(Convert.FromBase64String(value));
            var cert2 = exportedCertCollection.Cast<X509Certificate2>().Single(s => s.HasPrivateKey);

System.Security.Cryptography.CryptographicException {"Cannot find the requested object.\r\n"}

欢迎提出任何建议。

我需要包含私钥的 pfx,查看跟踪日志

ystem.Net 信息:0:[37880] SecureChannel#23107755 - 剩下 1 个客户端证书可供选择。 System.Net 信息:0:[37880] SecureChannel#23107755 - 试图在证书库中找到匹配的证书。 System.Net 信息:0:[37880] SecureChannel#23107755 - 查找证书的私钥:[Subject]

回答我自己的问题(我想我问得太快了)

原来这道题其实是重复的,只是一开始没看懂。事实上,Azure 管理门户是有限的。目前上传证书只能通过使用 powershell(或其他代码)来完成。

第三次尝试代码适用于 X509Certificate2

        var secret = helper.GetSecret("https://myCertificate.vault.azure.net/secrets/MyCertificate/1234567890");

        var exportedCertCollection = new X509Certificate2Collection();
        exportedCertCollection.Import(Convert.FromBase64String(secret.Value));
        var cert2 = exportedCertCollection.Cast<X509Certificate2>().Single(s => s.HasPrivateKey);