/// <summary> /// Encrypte un message /// </summary> /// <param name="keyName">Nom de la clef d'encryptage</param> /// <param name="message">Message à encrypter</param> /// <returns></returns> public async Task <string> EncryptAsync(string keyName, string message) { byte[] byteMessage = Encoding.Default.GetBytes(message); KeyOperationResult result = await KeyVaultClient.EncryptAsync( GetKeyUrl(keyName), _encryptionAlgorithm, byteMessage) .ConfigureAwait(false); return(Convert.ToBase64String(result.Result)); }
public async Task PutKey_Succeeds() { var key = new Key("key2", "secret2"); var keyOperationResult = new KeyOperationResult(key.Value, OperationResult.Updated); _secretsManagerMock.Setup(p => p.AddOrUpdateFunctionSecretAsync(key.Name, key.Value, "TestFunction1", ScriptSecretsType.Function)).ReturnsAsync(keyOperationResult); ObjectResult result = (ObjectResult)await _testController.Put("TestFunction1", key.Name, key); var content = (JObject)result.Value; Assert.Equal("key2", content["name"]); Assert.Equal("secret2", content["value"]); }
public async Task PutKey_FunctionInError_Succeeds() { _testController.Request = new HttpRequestMessage(HttpMethod.Get, "https://local/admin/functions/keys/key2"); var key = new Key("key2", "secret2"); var keyOperationResult = new KeyOperationResult(key.Value, OperationResult.Updated); _secretsManagerMock.Setup(p => p.AddOrUpdateFunctionSecretAsync(key.Name, key.Value, "ErrorFunction", ScriptSecretsType.Function)).ReturnsAsync(keyOperationResult); var result = (OkNegotiatedContentResult <ApiModel>)(await _testController.Put("ErrorFunction", key.Name, key)); var content = (JObject)result.Content; Assert.Equal("key2", content["name"]); Assert.Equal("secret2", content["value"]); }
public static string Sign(byte[] inputBytes) { // signature SHA256 sha256 = SHA256Managed.Create(); KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback( (authority, resource, scope) => KeyVaultUtil.GetToken(authority, resource, scope))); KeyOperationResult resultSign = Task.Run(() => keyVaultClient.SignAsync(SignKey(), JsonWebKeySignatureAlgorithm.RS256, sha256.ComputeHash(inputBytes))) .ConfigureAwait(false).GetAwaiter().GetResult(); var signatureEncoded = System.Convert.ToBase64String(resultSign.Result); return(signatureEncoded); }
public async Task CreateSecret(VehiclePolicies policydata) { // Create the content for the Policy data to be stored as Secret Insdata akvdata = new Insdata { Id = policydata.Id, Inscompany = policydata.Inscompany, Policyno = policydata.Policyno, Userid = policydata.Userid, Vehicleno = policydata.Vehicleno }; //Create a JSON String of the Policy data to be stored as Secret string insurancepolicysecret = JsonConvert.SerializeObject(akvdata); byte[] datatoencrypt = System.Text.Encoding.UTF8.GetBytes(insurancepolicysecret); string keyUri = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName); string keyVaultUri = string.Format("https://{0}.vault.azure.net", _keyVaultName); //Encrypt the data before it is stored as a Secret KeyOperationResult result = await _keyVaultClient.EncryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, datatoencrypt); byte[] encdata = result.Result; string encrypteddata = Convert.ToBase64String(encdata); //Set the Policy Start and Expiry Data to be added as attributes to the secret SecretAttributes attribs = new SecretAttributes { Enabled = true, Expires = DateTime.UtcNow.AddYears(1), NotBefore = DateTime.UtcNow }; IDictionary <string, string> alltags = new Dictionary <string, string> { { "InsuranceCompany", policydata.Inscompany } }; string contentType = "DigitalInsurance"; // Create a Secret with the encrypted Policy data SecretBundle bundle = await _keyVaultClient.SetSecretAsync(keyVaultUri, policydata.Uidname, encrypteddata, alltags, contentType, attribs); string bundlestr = bundle.Value; policydata.Version = bundle.SecretIdentifier.Version; policydata.Lastmod = bundle.Attributes.Updated; policydata.Startdate = bundle.Attributes.NotBefore; policydata.Enddate = bundle.Attributes.Expires; }
public async Task <ActionResult> EncryptAsync(string dataToEncrypt) { AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); // Demonstrate how to get a key KeyBundle key = await keyVaultClient.GetKeyAsync(keyVaultOptions.VaultBaseUrl, keyVaultOptions.KeyName); // Here you can use the (public) key to do encryption which is faster // Or encrypt on the Azure side using the EncryptAsync operation // Note that you can call the EncryptAsync operation directly without calling the GetKeyAsync method above KeyOperationResult keyOperationResult = await keyVaultClient.EncryptAsync(keyVaultOptions.VaultBaseUrl, key.KeyIdentifier.Name, key.KeyIdentifier.Version, JsonWebKeyEncryptionAlgorithm.RSAOAEP, Encoding.UTF8.GetBytes(dataToEncrypt)); ViewData["Encrypted"] = Convert.ToBase64String(keyOperationResult.Result); return(View("Index")); }
public async Task <bool> ValidateAsync(VehiclePolicies vehPoliciesMaster) { bool isValid = false; string keyUri = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName); string keyVaultUri = string.Format("https://{0}.vault.azure.net", _keyVaultName); var bundle = await _keyVaultClient.GetSecretAsync(keyVaultUri, vehPoliciesMaster.Uidname); string decryptedstring = bundle.Value; byte[] encdata = Convert.FromBase64String(decryptedstring); KeyOperationResult result = await _keyVaultClient.DecryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encdata); byte[] decrypteddata = result.Result; string secretdata = System.Text.Encoding.UTF8.GetString(decrypteddata); SecretAttributes attributes = bundle.Attributes; if (attributes.Expires < System.DateTime.UtcNow || attributes.NotBefore > System.DateTime.UtcNow) { isValid = false; } VehiclePolicies _vehPoliciesMaster = JsonConvert.DeserializeObject <VehiclePolicies>(secretdata); if (vehPoliciesMaster.Id.Equals(_vehPoliciesMaster.Id) && vehPoliciesMaster.Policyno.Equals(_vehPoliciesMaster.Policyno) && vehPoliciesMaster.Userid.Equals(_vehPoliciesMaster.Userid) && vehPoliciesMaster.Vehicleno.Equals(_vehPoliciesMaster.Vehicleno) && vehPoliciesMaster.Inscompany.Equals(_vehPoliciesMaster.Inscompany) ) { isValid = true; } else { return(isValid); } return(isValid); }
public async Task UpdateSecret(VehiclePolicies policydata) { //Create the updated Policy data to be stored as a new version of the Secret Insdata akvdata = new Insdata { Id = policydata.Id, Inscompany = policydata.Inscompany, Policyno = policydata.Policyno, Userid = policydata.Userid, Vehicleno = policydata.Vehicleno }; //Create the JSON String of the updated Policy Object string insurancepolicysecret = JsonConvert.SerializeObject(akvdata); byte[] datatoencrypt = System.Text.Encoding.UTF8.GetBytes(insurancepolicysecret); string keyUri = string.Format("https://{0}.vault.azure.net/keys/{1}", _keyVaultName, _keyName); string keyVaultUri = string.Format("https://{0}.vault.azure.net", _keyVaultName); KeyOperationResult result = null; //Get the metadata from the existing Secret in Key Vault SecretBundle bundle = await _keyVaultClient.GetSecretAsync(keyVaultUri, policydata.Uidname); if (bundle == null) { throw new ApplicationException("Error locating Secret data to update"); //No need to execute the rest of the steps if the Secret cannot be retrieved } SecretAttributes _attribs = bundle.Attributes; string _contentType = bundle.ContentType; IDictionary <string, string> dic = bundle.Tags; //Create the attributes for the updated Secret SecretAttributes attribsNew = new SecretAttributes { Enabled = true, Expires = _attribs.Expires, NotBefore = DateTime.UtcNow }; IDictionary <string, string> alltags = dic; string contentType = _contentType; // Encrypt the updated Secret data result = await _keyVaultClient.EncryptAsync(keyUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, datatoencrypt); byte[] encdata = result.Result; string encrypteddata = Convert.ToBase64String(encdata); //Create a new version of the Secret by calling the SetSecret Method, and using the attributes from the previous version of the Secret bundle = await _keyVaultClient.SetSecretAsync(keyVaultUri, policydata.Uidname, encrypteddata, alltags, contentType, attribsNew); string bundlestr = bundle.Value; policydata.Version = bundle.SecretIdentifier.Version; policydata.Lastmod = bundle.Attributes.Updated; policydata.Startdate = bundle.Attributes.NotBefore; policydata.Enddate = bundle.Attributes.Expires; }
public async Task CreateRSARootAndRSAIssuerTestAsync() { using (var mock = Setup((v, q) => { var expected = "SELECT TOP 1 * FROM Certificates c " + "WHERE c.Type = 'Certificate' " + "AND c.CertificateName = 'footca' " + "ORDER BY c.Version DESC"; if (q == expected) { return(v .Where(o => o.Value["Type"] == "Certificate") .Where(o => o.Value["CertificateName"] == "footca") .OrderByDescending(o => o.Value["Version"])); } expected = "SELECT TOP 1 * FROM Certificates c " + "WHERE c.Type = 'Certificate' " + "AND c.CertificateName = 'rootca' " + "ORDER BY c.Version DESC"; if (q == expected) { return(v .Where(o => o.Value["Type"] == "Certificate") .Where(o => o.Value["CertificateName"] == "rootca") .OrderByDescending(o => o.Value["Version"])); } expected = "SELECT TOP 1 * FROM Certificates c " + "WHERE c.Type = 'Certificate' " + "AND c.CertificateId = '" + kTestVaultUri + "/certificates/rootca' " + "ORDER BY c.Version DESC"; if (q == expected) { return(v .Where(o => o.Value["Type"] == "Certificate") .Where(o => o.Value["CertificateName"] == "rootca") .OrderByDescending(o => o.Value["Version"])); } throw new AssertActualExpectedException(expected, q, "Query"); }, out var service, out var client)) { ICertificateStore store = mock.Create <CertificateDatabase>(); ICertificateRepository repo = mock.Create <CertificateDatabase>(); var now = DateTime.UtcNow; using (var rkey = SignatureType.RS256.CreateCsr("CN=thee", true, out var rootcsr)) using (var rootca = rootcsr.CreateSelfSigned(now, now + TimeSpan.FromDays(5))) using (var ikey = SignatureType.RS256.CreateCsr("CN=me", true, out var issuercsr)) using (var issuer = issuercsr.Create(rootca, now, now + TimeSpan.FromHours(3), Guid.NewGuid().ToByteArray())) { await repo.AddCertificateAsync("rootca", rootca.ToCertificate(new IssuerPolicies { SignatureType = SignatureType.RS256, IssuedLifetime = TimeSpan.FromHours(3) }, KeyVaultKeyHandle.Create(kTestVaultUri + "/keys/rkid", null)), kTestVaultUri + "/certificates/rootca"); client.Setup(o => o.GetCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "rootca"), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateBundle( kTestVaultUri + "/certificates/rootca", kTestVaultUri + "/keys/rkid", null, // not exportable null, null, rootca.ToPfx(rkey.ToKey()), null, null, null); return(Task.FromResult(new AzureOperationResponse <CertificateBundle> { Body = result })); }); client.Setup(o => o.CreateCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "footca"), It.IsNotNull <CertificatePolicy>(), It.IsNotNull <CertificateAttributes>(), It.IsAny <IDictionary <string, string> >(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateOperation { Status = "InProgress" }; return(Task.FromResult(new AzureOperationResponse <CertificateOperation> { Body = result })); }); client.Setup(o => o.GetCertificateOperationWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateOperation { Csr = issuercsr.CreateSigningRequest(), Status = "Completed" }; return(Task.FromResult(new AzureOperationResponse <CertificateOperation> { Body = result })); }); client.Setup(o => o.GetCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "footca"), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateBundle( kTestVaultUri + "/certificates/footca", kTestVaultUri + "/keys/fkid", null, // not exportable null, null, issuer.ToPfx(ikey.ToKey()), null, null, null); return(Task.FromResult(new AzureOperationResponse <CertificateBundle> { Body = result })); }); client.Setup(o => o.MergeCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "footca"), It.IsAny <IList <byte[]> >(), It.IsAny <CertificateAttributes>(), It.IsAny <IDictionary <string, string> >(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateBundle( kTestVaultUri + "/certificates/footca", kTestVaultUri + "/keys/fkid", null, // not exportable null, null, issuer.ToPfx(ikey.ToKey()), null, null, null); return(Task.FromResult(new AzureOperationResponse <CertificateBundle> { Body = result })); }); client.Setup(o => o.SignWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), // It.Is<string>(a => a == kTestVaultUri + "/keys/rkid"), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), // It.Is<string>(a => a == "RS256"), It.IsAny <byte[]>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new KeyOperationResult( kTestVaultUri + "/keys/rkid", new byte[32]); return(Task.FromResult(new AzureOperationResponse <KeyOperationResult> { Body = result })); }); // Run var footca = await service.NewIssuerCertificateAsync("rootca", "footca", X500DistinguishedNameEx.Create("CN=me"), DateTime.UtcNow, new CreateKeyParams { KeySize = 2048, Type = KeyType.RSA }, new IssuerPolicies { IssuedLifetime = TimeSpan.FromHours(1) }); var found = await store.FindLatestCertificateAsync("footca"); // Assert Assert.NotNull(footca); Assert.NotNull(found); Assert.NotNull(footca.IssuerPolicies); Assert.NotNull(footca.KeyHandle); Assert.Null(footca.Revoked); Assert.Equal(TimeSpan.FromHours(3), footca.NotAfterUtc - footca.NotBeforeUtc); Assert.Equal(TimeSpan.FromHours(1), footca.IssuerPolicies.IssuedLifetime); Assert.Equal(SignatureType.RS256, footca.IssuerPolicies.SignatureType); Assert.False(footca.IsSelfSigned()); Assert.True(footca.IsIssuer()); Assert.True(footca.SameAs(found)); Assert.Equal(rootca.Subject, footca.GetIssuerSubjectName()); Assert.True(rootca.SubjectName.SameAs(footca.Issuer)); using (var cert = footca.ToX509Certificate2()) { Assert.Equal(cert.GetSerialNumber(), footca.GetSerialNumberAsBytesLE()); Assert.Equal(cert.SerialNumber, footca.GetSerialNumberAsString()); Assert.Equal(cert.Thumbprint, footca.Thumbprint); } Assert.True(footca.IsValidChain(rootca.ToCertificate().YieldReturn())); } } }
private async Task KeysMigrationGuide() { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); KeyVaultClient client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions using (HttpClient httpClient = new HttpClient()) { //@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); /*@@*/ provider = new AzureServiceTokenProvider(); //@@KeyVaultClient client = new KeyVaultClient( /*@@*/ client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback), httpClient); } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey // Create RSA key. NewKeyParameters createRsaParameters = new NewKeyParameters { Kty = JsonWebKeyType.Rsa, KeySize = 4096 }; KeyBundle rsaKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "rsa-key-name", createRsaParameters); // Create Elliptic-Curve key. NewKeyParameters createEcParameters = new NewKeyParameters { Kty = JsonWebKeyType.EllipticCurve, CurveName = "P-256" }; KeyBundle ecKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "ec-key-name", createEcParameters); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys IPage <KeyItem> page = await client.GetKeysAsync("https://myvault.vault.azure.net"); foreach (KeyItem item in page) { KeyIdentifier keyId = item.Identifier; KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name); } while (page.NextPageLink != null) { page = await client.GetKeysNextAsync(page.NextPageLink); foreach (KeyItem item in page) { KeyIdentifier keyId = item.Identifier; KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name); } } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey // Delete the key. DeletedKeyBundle deletedKey = await client.DeleteKeyAsync("https://myvault.vault.azure.net", "key-name"); // Purge or recover the deleted key if soft delete is enabled. if (deletedKey.RecoveryId != null) { DeletedKeyIdentifier deletedKeyId = deletedKey.RecoveryIdentifier; // Deleting a key does not happen immediately. Wait a while and check if the deleted key exists. while (true) { try { await client.GetDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name); // Finally deleted. break; } catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { // Not yet deleted... } } // Purge the deleted key. await client.PurgeDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name); // You can also recover the deleted key using RecoverDeletedKeyAsync. } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt // Encrypt a message. The plaintext must be small enough for the chosen algorithm. byte[] plaintext = Encoding.UTF8.GetBytes("Small message to encrypt"); KeyOperationResult encrypted = await client.EncryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, plaintext); // Decrypt the message. KeyOperationResult decrypted = await client.DecryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encrypted.Result); string message = Encoding.UTF8.GetString(decrypted.Result); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap using (Aes aes = Aes.Create()) { // Use a symmetric key to encrypt large amounts of data, possibly streamed... // Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data. KeyOperationResult wrapped = await client.WrapKeyAsync( "https://myvault.vault.azure.net", "rsa-key-name", null, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, aes.Key); // Read the IV and the encrypted key from the payload, then unwrap the key. KeyOperationResult unwrapped = await client.UnwrapKeyAsync( "https://myvault.vault.azure.net", "rsa-key-name", null, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, wrapped.Result); aes.Key = unwrapped.Result; // Decrypt the payload with the symmetric key. } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap } }
static void Main(string[] args) { string baseVaultAddress = "https://amethystevault.vault.azure.net"; // Azure AD //KeyVaultClient keyVaultClient = new KeyVaultClient( // new KeyVaultClient.AuthenticationCallback(GetAccessToken)); // Certificat CertificateAccesTokenService cts = new CertificateAccesTokenService(); KeyVaultClient keyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(cts.GetAccessToken)); #region Secret Console.WriteLine("Liste des secrets du vault"); IPage <SecretItem> items = keyVaultClient .GetSecretsAsync(baseVaultAddress) .Result; foreach (SecretItem item in items) { string name = item.Identifier.Name; SecretBundle s = keyVaultClient .GetSecretAsync(baseVaultAddress, name) .Result; Console.WriteLine("{0}: {1}", name, s.Value); } Console.WriteLine(); Console.WriteLine("Lecture d'un secret"); SecretBundle secret = keyVaultClient .GetSecretAsync(baseVaultAddress + "/secrets/password") .Result; //SecretBundle secret = keyVaultClient // .GetSecretAsync(vaultAddress, "password", version) // .Result; Console.WriteLine(secret.Value); #endregion #region Key string keyName = "keyDemo"; string identifiant = baseVaultAddress + "/keys/" + keyName; // proxy KeyBundle key = keyVaultClient .GetKeyAsync(baseVaultAddress, keyName) .Result; // encode un message byte[] byteMessage = Encoding.Default.GetBytes("Salut le monde!"); KeyOperationResult result = keyVaultClient .EncryptAsync(identifiant, JsonWebKeyEncryptionAlgorithm.RSAOAEP, byteMessage) .Result; string encoded = Convert.ToBase64String(result.Result); Console.WriteLine("Message encodé: {0}", encoded); // décode le message byteMessage = Convert.FromBase64String(encoded); result = keyVaultClient .DecryptAsync(identifiant, JsonWebKeyEncryptionAlgorithm.RSAOAEP, byteMessage) .Result; string message = Encoding.Default.GetString(result.Result); Console.WriteLine("Après décodage: {0}", message); #endregion #region Certificate // proxy CertificateBundle cert = keyVaultClient .GetCertificateAsync(baseVaultAddress, "TestCertificate") .Result; Console.WriteLine(cert.X509Thumbprint.ToHexString()); // proxy SecretBundle cert2 = keyVaultClient .GetSecretAsync(baseVaultAddress + "/secrets/TestCertificate") .Result; byte[] privateKeyBytes = Convert.FromBase64String(cert2.Value); X509Certificate2 pfx = new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.MachineKeySet); Console.WriteLine(pfx.Thumbprint); #endregion }
public async Task NewRootCertificateTest() { using (var mock = AutoMock.GetLoose()) { // Setup var(service, client) = Setup(mock, (v, q) => { var expected = "SELECT TOP 1 * FROM Certificates c " + "WHERE c.Type = 'Certificate' " + "AND c.CertificateName = 'rootca' " + "ORDER BY c.Version DESC"; if (q == expected) { return(v .Where(o => ((dynamic)o.Value).Type == "Certificate") .Where(o => ((dynamic)o.Value).CertificateName == "rootca") .OrderByDescending(o => ((dynamic)o.Value).Version)); } throw new AssertActualExpectedException(expected, q, "Query"); }); ICertificateStore store = mock.Create <CertificateDatabase>(); var now = DateTime.UtcNow; using (var rkey = SignatureType.RS256.CreateCsr("CN=me", true, out var request)) using (var cert = request.CreateSelfSigned(now, now + TimeSpan.FromDays(5))) { client.Setup(o => o.CreateCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "rootca"), It.IsNotNull <CertificatePolicy>(), It.IsNotNull <CertificateAttributes>(), It.IsAny <IDictionary <string, string> >(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateOperation { Status = "InProgress" }; return(Task.FromResult(new AzureOperationResponse <CertificateOperation> { Body = result })); }); client.Setup(o => o.GetCertificateOperationWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "rootca"), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateOperation { Csr = request.CreateSigningRequest(), Status = "Completed" }; return(Task.FromResult(new AzureOperationResponse <CertificateOperation> { Body = result })); }); client.Setup(o => o.GetCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "rootca"), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateBundle( kTestVaultUri + "/certificates/rootca", kTestVaultUri + "/keys/kid", null, // not exportable null, null, cert.ToPfx(rkey.ToKey()), null, null, null); return(Task.FromResult(new AzureOperationResponse <CertificateBundle> { Body = result })); }); client.Setup(o => o.MergeCertificateWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), It.Is <string>(a => a == "rootca"), It.IsAny <IList <byte[]> >(), It.IsAny <CertificateAttributes>(), It.IsAny <IDictionary <string, string> >(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new CertificateBundle( kTestVaultUri + "/certificates/rootca", kTestVaultUri + "/keys/kid", null, // not exportable null, null, cert.ToPfx(rkey.ToKey()), null, null, null); return(Task.FromResult(new AzureOperationResponse <CertificateBundle> { Body = result })); }); client.Setup(o => o.SignWithHttpMessagesAsync( It.Is <string>(a => a == kTestVaultUri), // It.Is<string>(a => a == kTestVaultUri + "/keys/kid"), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), // It.Is<string>(a => a == "RS256"), It.IsAny <byte[]>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>())).Returns(() => { var result = new KeyOperationResult( kTestVaultUri + "/keys/kid", new byte[32]); return(Task.FromResult(new AzureOperationResponse <KeyOperationResult> { Body = result })); }); // Run var rootca = await service.NewRootCertificateAsync("rootca", X500DistinguishedNameEx.Create("CN=me"), DateTime.UtcNow, TimeSpan.FromDays(5), new CreateKeyParams { KeySize = 4096, Type = KeyType.RSA }, new IssuerPolicies { SignatureType = SignatureType.RS256, IssuedLifetime = TimeSpan.FromHours(1) }); var found = await store.FindLatestCertificateAsync("rootca"); var export = ((IKeyStore)service).ExportKeyAsync(found.KeyHandle); // Assert Assert.NotNull(rootca); Assert.NotNull(found); Assert.NotNull(rootca.IssuerPolicies); Assert.NotNull(rootca.KeyHandle); await Assert.ThrowsAsync <InvalidOperationException>(() => export); Assert.Null(rootca.Revoked); Assert.Equal(TimeSpan.FromDays(5), rootca.NotAfterUtc - rootca.NotBeforeUtc); Assert.Equal(TimeSpan.FromHours(1), rootca.IssuerPolicies.IssuedLifetime); Assert.Equal(SignatureType.RS256, rootca.IssuerPolicies.SignatureType); Assert.True(rootca.IsValidChain()); rootca.Verify(rootca); Assert.True(rootca.IsSelfSigned()); Assert.True(rootca.IsIssuer()); Assert.True(rootca.SameAs(found)); Assert.NotNull(rootca.GetIssuerSerialNumberAsString()); Assert.Equal(rootca.GetSubjectName(), rootca.GetIssuerSubjectName()); Assert.True(rootca.Subject.SameAs(rootca.Issuer)); using (var rcert = rootca.ToX509Certificate2()) { Assert.Equal(rcert.GetSerialNumber(), rootca.GetSerialNumberAsBytesLE()); Assert.Equal(rcert.SerialNumber, rootca.GetSerialNumberAsString()); Assert.Equal(rcert.Thumbprint, rootca.Thumbprint); } Assert.Equal(rootca.GetSerialNumberAsString(), rootca.GetIssuerSerialNumberAsString()); } } }