通过.NET库将Azure密钥保险库证书添加到Azure批处理帐户

时间:2018-09-07 16:16:00

标签: c# .net azure azure-keyvault azure-batch

我需要自动创建Azure Batch帐户。其中一部分是从现有的Azure密钥保管库向帐户添加证书。我想我已经拥有了所有需要的东西,但我无法将它们全部融合在一起。我有一个KeyVault.Models.CertificateBundle对象和一个Management.Batch.Models.BatchAccount对象,但是我不确定如何将其中一个融入另一个对象。

我的代码如下:

// Create Batch account
var storageAccount = new Models.AutoStorageBaseProperties(storageAccountId);
mgmtClient.BatchAccount.Create(resourceGroupName, accountName,
    new Models.BatchAccountCreateParameters()
    {
        Location = clusterZone,
        AutoStorage = storageAccount
    });

string certName;
Models.CertificateCreateOrUpdateParameters certParams;

// Add certificate
using (KeyVaultClient kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetKeyVaultToken)))
{
    var cert = kvClient.GetCertificateAsync(certId).GetAwaiter().GetResult();
    string thumbprint = Convert.ToBase64String(cert.X509Thumbprint);
    string cer = Convert.ToBase64String(cert.Cer);
    certParams = new Models.CertificateCreateOrUpdateParameters(Convert.ToBase64String(cert.Cer), cert.Id, thumbprint: thumbprint, format: Models.CertificateFormat.Cer, type: cert.ContentType);
    certName = $"SHA1-{thumbprint}"; // not sure about this one
}

// failing with a complaint about the cert name
mgmtClient.Certificate.Create(resourceGroupName, accountName, certName, certParams);

此代码给出的确切错误是:

'certificateName' does not match expected pattern '^[\\w]+-[\\w]+$'.

certName看起来像SHA1-XXXXXXXXXXXXXXXXXXXXXX+XXXX=。指纹中有一些非字母数字字符。我只是在猜测这是SHA1,但除此之外,这个名称对我来说似乎很合适。我不确定我缺少什么。

我也很乐意接受某人针对此特定问题的简便解决方案。

1 个答案:

答案 0 :(得分:1)

  

'certificateName'与预期的模式'^ [\ w] +-[\ w] + $'不匹配。

您可以调试代码并从Azure keyvault检查指纹。在您的代码中,您从代码中获得的指纹与认证指纹不同。我得到了带有以下代码的认证指纹。

@objc func scrollAutomatically(_ timer1: Timer) {

      if let coll  = CV_Slider {
            for cell in coll.visibleCells {
                let indexPath: IndexPath? = coll.indexPath(for: cell)
                if ((indexPath?.row)!  < self.arr_img_Slide.count - 1){
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: (indexPath?.row)! + 1, section: (indexPath?.section)!)

                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }
                else{
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: 0, section: (indexPath?.section)!)
                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }

            }
        }
    }

以下用于将证书添加到Azure批处理帐户的演示代码。

X509Certificate2 x509 = new X509Certificate2();
x509.Import(cert.Cer);
var thumbprint = x509.Thumbprint;

测试结果:

enter image description here