c# - 以编程方式将 x509 证书上传到 azure 应用程序 list

标签 c# asp.net-mvc azure validation x509certificate

有没有办法以编程方式将 Visual Studios 中创建的 x509 证书上传到 Azure 应用程序 list 中?

我关注了this post创建 x509 证书:

public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
{
    const int keyStrength = 2048;

    //generate random numbers
    CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
    SecureRandom random = new SecureRandom(randomGenerator);
    ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);

    //the certificate generator
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

    //serial number
    BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random );
    certificateGenerator.SetSerialNumber(serialNumber);

    // Issuer and Subject Name
    X509Name subjectDN = new X509Name("CN="+ subjectName);
    X509Name issuerDN = new X509Name("CN="+issuerName);
    certificateGenerator.SetIssuerDN(issuerDN);
    certificateGenerator.SetSubjectDN(subjectDN);

    //valid For
    DateTime notBefore = DateTime.Now;
    DateTime notAfter = notBefore.AddYears(2);
    certificateGenerator.SetNotBefore(notBefore);
    certificateGenerator.SetNotAfter(notAfter);

    //Subject Public Key
    AsymmetricCipherKeyPair subjectKeyPair;
    var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
    var keyPairGenerator = new RsaKeyPairGenerator();
    keyPairGenerator.Init(keyGenerationParameters);
    subjectKeyPair = keyPairGenerator.GenerateKeyPair();

    certificateGenerator.SetPublicKey(subjectKeyPair.Public);

    //selfSign certificate
    Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
    var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters) subjectKeyPair.Private);

    //merge into X509Certificate2
    X509Certificate2 x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));
    x509.PrivateKey = dotNetPrivateKey;
    x509.FriendlyName = subjectName;

    return x509;
}


public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey)
{
    const int keyStrength = 2048;

    //generate Random Numbers
    CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
    SecureRandom random = new SecureRandom(randomGenerator);

    //The Certificate Generator
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

    //Serial Number
    BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
    certificateGenerator.SetSerialNumber(serialNumber);

    //Issuer and Subject Name
    X509Name subjectDN = new X509Name("CN="+subjectName);
    X509Name issuerDN = subjectDN;
    certificateGenerator.SetIssuerDN(issuerDN);
    certificateGenerator.SetSubjectDN(subjectDN);

    //valid For
    DateTime notBefore = DateTime.Now;
    DateTime notAfter = notBefore.AddYears(2);

    certificateGenerator.SetNotBefore(notBefore);
    certificateGenerator.SetNotAfter(notAfter);

    //subject Public Key
    AsymmetricCipherKeyPair subjectKeyPair;
    KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
    RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
    keyPairGenerator.Init(keyGenerationParameters);
    subjectKeyPair = keyPairGenerator.GenerateKeyPair();

    certificateGenerator.SetPublicKey(subjectKeyPair.Public);

    //generating the certificate
    AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
    ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

    //selfSign Certificate
    Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

    X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
    x509.FriendlyName = subjectName;
    CaPrivateKey = issuerKeyPair.Private;

    return x509;
}

public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
    var cspParams = new CspParameters()
    {
        KeyContainerName = Guid.NewGuid().ToString(),
        KeyNumber = (int)KeyNumber.Exchange,
        Flags = CspProviderFlags.UseMachineKeyStore
    };

    var rsaProvider = new RSACryptoServiceProvider(cspParams);
    var parameters = new RSAParameters()
    {
        Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
        P = privateKey.P.ToByteArrayUnsigned(),
        Q = privateKey.Q.ToByteArrayUnsigned(),
        DP = privateKey.DP.ToByteArrayUnsigned(),
        DQ = privateKey.DQ.ToByteArrayUnsigned(),
        InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
        D = privateKey.Exponent.ToByteArrayUnsigned(),
        Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
    };

    rsaProvider.ImportParameters(parameters);

    return rsaProvider;
}

并像这样添加X509Store:

public static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
{
    bool bRet = false;

    try
    {
        X509Store store = new X509Store(st, sl);
        store.Open(OpenFlags.ReadWrite);
        store.Add(cert);

        store.Close();
    }
    catch
    {

    }

    return bRet;
}

基本上,我想将在 Visual Studio 中创建的证书上传到 Azure 门户或 Microsoft 注册门户中的应用程序 list ,以获得更强的访问 token ,用于将事件写入 Outlook 日历。我已经用谷歌搜索了两天了,但仍然没有运气......是否有我缺少的文档?

我需要使用 x509 证书来代替在 Microsoft 注册门户中创建新应用程序时生成的 appSecret。

有人能指出我正确的方向吗?

最佳答案

Is there a way to programmatically upload an x509 certificate created in Visual Studios into Azure application manifest?

是的,我们可以使用 Microsoft.Azure.ActiveDirectory.GraphClient 更新 Azure 应用程序 mainfest .

我为此做了一个演示。以下是详细步骤,您可以引用:

如果我们想更新 mainfest keyCredential,我们需要委派权限

1.注册一个azure AD native 应用程序并授予[以登录用户身份访问目录]权限。

enter image description here

2.创建控制台应用程序,在Program.cs文件中添加以下代码

 private static async Task<string> GetAppTokenAsync(string graphResourceId, string tenantId, string clientId, string userId)
        {

            string aadInstance = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
            IPlatformParameters parameters = new PlatformParameters(PromptBehavior.SelectAccount);
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance, false);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(graphResourceId, clientId, new Uri("http://localhost"), parameters, new UserIdentifier(userId, UserIdentifierType.UniqueId));
            return authenticationResult.AccessToken;
        }

 var graphResourceId = "https://graph.windows.net";
 var tenantId = "tenantId";
 var clientId = "clientId";
 var userId= "313e5ee2-b28exx-xxxx"; Then login user
 var servicePointUri = new Uri(graphResourceId); 
 var serviceRoot = new Uri(servicePointUri, tenantId);
 var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetAppTokenAsync(graphResourceId, tenantId, clientId, userName));
 var cert = new X509Certificate();
 cert.Import(@"D:\Tom\Documents\tom.cer");// the path fo cert file
 var expirationDate  = DateTime.Parse(cert.GetExpirationDateString()).ToUniversalTime();
 var startDate = DateTime.Parse(cert.GetEffectiveDateString()).ToUniversalTime();
 var binCert =cert.GetRawCertData();
 var keyCredential = new KeyCredential
      {
                CustomKeyIdentifier = cert.GetCertHash(),
                EndDate = expirationDate,
                KeyId = Guid.NewGuid(),
                StartDate = startDate,
                Type = "AsymmetricX509Cert",
                Usage = "Verify",
                Value = binCert

        };

   var application = activeDirectoryClient.Applications["ApplicationObjectId"].ExecuteAsync().Result;
   application.KeyCredentials.Add(keyCredential);
   application.UpdateAsync().Wait();

Packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Azure.ActiveDirectory.GraphClient" version="2.1.1" targetFramework="net471" />
  <package id="Microsoft.Data.Edm" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.Data.OData" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.Data.Services.Client" version="5.6.4" targetFramework="net471" />
  <package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.19.8" targetFramework="net471" />
  <package id="System.Spatial" version="5.6.4" targetFramework="net471" />
</packages>

关于c# - 以编程方式将 x509 证书上传到 azure 应用程序 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153189/

相关文章:

c# - Azure Functions - Host.json 不适用于 Azure 应用程序设置

azure - Azure 上托管的 Web API 中的 TLS 相互身份验证

c# - DocumentDB 客户端生命周期

c# - Console.Read 不返回我的 int32

c# - 在一行中写入列表/数组

c# - FakeItEasy - 是否可以异步测试约束(即 MatchesAsync)?

c# - JSON数据html参数

java - 将 mandelbrot 绘制到位图中

asp.net-mvc - BeginRenderLink Sitecore Glass Mapper

jquery - 使用 Bootstrap 3 模式时接收错误 0x800a01b6 - JavaScript 运行时错误 : Object doesn't support property or method 'modal' ,