Trying to access Azure Keyvault from .Net Framework project is hanging - c#

I'm currently working on a 256 bit AES encryption API project for my job. One of the aspects of these encryption APIs is they need to access our Azure Keyvault to retrieve a key (we have different keys for different projects).
For some reason the .Net Framework project hangs when trying to access the key vault after the first successful execution. It will hang on this line: var key = client.GetKeyAsync($"https://automationkeys.vault.azure.net/keys/{product}").GetAwaiter().GetResult();
I have the same encryption API made using .Net Core and I'm able to execute calls multiple times in a row without issue.
After doing some reading I have a feeling it has to do with async / await but I don't know enough about all that to see where the problem is.
Here is my full KeyVaultAccessor class:
public static class KeyVaultAccessor
{
public static string GetKey(string product)
{
var keyValue = string.Empty;
try
{
var client = GetKeyVaultClient(<my_app_id>, <keyvault_cert_thumbprint>);
var key = client.GetKeyAsync($"https://automationkeys.vault.azure.net/keys/{product}").GetAwaiter().GetResult();
keyValue = key?.KeyIdentifier.Version;
if (string.IsNullOrEmpty(keyValue))
{
Assert.Fail($"Key was null or empty for product: {product}");
}
}
catch (Exception e)
{
Assert.Fail($"Error occurred while attempting to retrieve key for product: {product}. {e.Message}");
}
return keyValue;
}
private static KeyVaultClient GetKeyVaultClient(string appId, string thumbprint)
{
var keyVault = new KeyVaultClient(async (authority, resource, scope) =>
{
var authenticationContext = new AuthenticationContext(authority, null);
X509Certificate2 certificate;
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certificateCollection.Count == 0)
{
throw new Exception("<certificate name> not installed in the store");
}
certificate = certificateCollection[0];
}
finally
{
store.Close();
}
var clientAssertionCertificate = new ClientAssertionCertificate(appId, certificate);
var result = await authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate);
return result.AccessToken;
});
return keyVault;
}
}

Not quite sure your root reason, but if you want to get a key in Azure keyVault by ClientCertificateCredential and local cert, try the code below which works perfectly for me:
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
namespace key_vault_console_app
{
class Program
{
static void Main(string[] args)
{
var keyVaultName = "";
var tenantID = "";
var appID = "";
var certThumbprint = "";
var kvUri = $"https://{keyVaultName}.vault.azure.net";
var certCred = new ClientCertificateCredential(tenantID, appID, GetLocalCert(certThumbprint));
var client = new KeyClient(new Uri(kvUri), certCred);
Console.Write(client.GetKey("<your key name>").Value.Key.Id);
}
public static X509Certificate2 GetLocalCert(string thumbprint)
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (certificateCollection.Count == 0)
{
throw new Exception("cert not installed in the store");
}
return certificateCollection[0];
}
finally
{
store.Close();
}
}
}
}
Result:

Related

Fail to send/receive Client Certificate from Console App to web api

I created a Web Api to accept a client certificate.
I am calling the web api from a console app using the following code.
var uri = new Uri("https://myservice.azurewebsites.net/api/values");
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
var certResults = new X509Store(StoreLocation.LocalMachine);
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
certStore.Open(OpenFlags.ReadOnly);
}
catch (Exception)
{
Console.WriteLine("Unable to access Certificate store");
}
var thumbprint = "<<self signed cert thumbprint>>";
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
certStore.Close();
HttpClient client = new HttpClient(handler);
if (certCollection.Count > 0)
{
handler.ClientCertificates.Add(certCollection[0]);
client.DefaultRequestHeaders.Add("Thumbprint", certCollection[0].Thumbprint);
}
var result = client.GetAsync(uri).GetAwaiter().GetResult();
Console.WriteLine($"status: {result.StatusCode}");
Console.WriteLine($"content: {result.Content.ReadAsStringAsync().GetAwaiter().GetResult()}");
Console.ReadLine();
}
On the server side, I added a middleware to get the certificate details.
{
//var certHeader = context.Request.Headers["X-ARR-ClientCert"];
var certificate = context.Connection.ClientCertificate;
if (certificate != null)
{
try
{
//var clientCertBytes = Convert.FromBase64String(certHeader);
//var certificate = new X509Certificate2(clientCertBytes);
bool isValidCert = IsValidClientCertificate(certificate);
if (isValidCert)
{
await _next.Invoke(context);
}
else
{
_logger.LogError("Certificate is not valid");
context.Response.StatusCode = 403;
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message, ex);
await context.Response.WriteAsync(ex.Message);
context.Response.StatusCode = 403;
}
}
else
{
_logger.LogError("X-ARR-ClientCert header is missing");
context.Response.StatusCode = 403;
}
}
I tried running it on the local machine and on Azure App Services.
I set the flag clientCertEnabled to true in resources.azure.com.
Web Api is SSL enabled.
But the certificate is always coming as null in both
var certHeader = context.Request.Headers["X-ARR-ClientCert"]; and
var certificate = context.Connection.ClientCertificate;.
What am I doing wrong here?
Thanks in advance.
Was reasearching some of this stuff myself and seeing your question, I wonder if you are having one of the issues described in the link Securing ASP.NET WebAPI using Client Certificates
Specifically:
4 Add MyPersonalCA.cer to Local Machine -> Truted Root Certificate Authorities. This is key, espcially while you are developing and want to try things. If you don’t do it, Request.ClientCertificate won’t be populated because the cert chain is untrusted.

How to implement apple token based push notifications (using p8 file) in C#?

For an app with some kind of chat based features I want to add push notification support for receiving new messages.
What I want to do is use the new token based authentication (.p8 file) from Apple, but I can't find much info about the server part.
I came across the following post:
How to use APNs Auth Key (.p8 file) in C#?
However the answer was not satisfying as there was not much detail about how to:
establish a connection with APNs
use the p8 file (except for some kind of encoding)
send data to the Apple Push Notification Service
You can't really do this on raw .NET Framework at the moment. The new JWT-based APNS server uses HTTP/2 only, which .NET Framework does not yet support.
.NET Core's version of System.Net.Http, however, does, provided you meet the following prerequisites:
On Windows, you must be running Windows 10 Anniversary Edition (v1607) or higher, or the equivalent build of Windows Server 2016 (I think).
On Linux, you must have a version of libcurl that supports HTTP/2.
On macOS, you have to compile libcurl with support for HTTP/2, then use the DYLD_INSERT_LIBRARIES environment variable in order to load your custom build of libcurl.
You should be able to use .NET Core's version of System.Net.Http in the .NET Framework if you really want.
I have no idea what happens on Mono, Xamarin or UWP.
There are then three things you have to do:
Parse the private key that you have been given. This is currently an ECDSA key, and you can load this into a System.Security.Cryptography.ECDsa object.
On Windows, you can use the CNG APIs. After parsing the base64-encoded DER part of the key file, you can then create a key with new ECDsaCng(CngKey.Import(data, CngKeyBlobFormat.Pkcs8PrivateBlob)).
On macOS or Linux there is no supported API and you have to parse the DER structure yourself, or use a third-party library.
Create a JSON Web Token / Bearer Token. If you use the System.IdentityModel.Tokens.Jwt package from NuGet, this is fairly simple. You will need the Key ID and Team ID from Apple.
public static string CreateToken(ECDsa key, string keyID, string teamID)
{
var securityKey = new ECDsaSecurityKey(key) { KeyId = keyID };
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256);
var descriptor = new SecurityTokenDescriptor
{
IssuedAt = DateTime.Now,
Issuer = teamID,
SigningCredentials = credentials
};
var handler = new JwtSecurityTokenHandler();
var encodedToken = handler.CreateEncodedJwt(descriptor);
return encodedToken;
}
Send an HTTP/2 request. This is as normal, but you need to do two extra things:
Set yourRequestMessage.Version to new Version(2, 0) in order to make the request using HTTP/2.
Set yourRequestMessage.Headers.Authorization to new AuthenticationHeaderValue("bearer", token) in order to provide the bearer authentication token / JWT with your request.
Then just put your JSON into the HTTP request and POST it to the correct URL.
Because Token (.p8) APNs only works in HTTP/2, thus most of the solutions only work in .net Core. Since my project is using .net Framework, some tweak is needed. If you're using .net Framework like me, please read on.
I search here and there and encountered several issues, which I managed to fix and pieced them together.
Below is the APNs class that actually works. I created a new class library for it, and placed the .P8 files within the AuthKeys folder of the class library. REMEMBER to right click on the .P8 files and set it to "Always Copy". Refer Get relative file path in a class library project that is being referenced by a web project.
After that, to get the location of the P8 files, please use AppDomain.CurrentDomain.RelativeSearchPath for web project or AppDomain.CurrentDomain.BaseDirectory for win application. Refer Why AppDomain.CurrentDomain.BaseDirectory not contains "bin" in asp.net app?
To get the token from the P8, you'll need to use the BouncyCastle class, please download it from Nuget.
using Jose;
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Security.Cryptography;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace PushLibrary
{
public class ApplePushNotificationPush
{
//private const string WEB_ADDRESS = "https://api.sandbox.push.apple.com:443/3/device/{0}";
private const string WEB_ADDRESS = "https://api.push.apple.com:443/3/device/{0}";
private string P8_PATH = AppDomain.CurrentDomain.RelativeSearchPath + #"\AuthKeys\APNs_AuthKey.p8";
public ApplePushNotificationPush()
{
}
public async Task<bool> SendNotification(string deviceToken, string title, string content, int badge = 0, List<Tuple<string, string>> parameters = null)
{
bool success = true;
try
{
string data = System.IO.File.ReadAllText(P8_PATH);
List<string> list = data.Split('\n').ToList();
parameters = parameters ?? new List<Tuple<string, string>>();
string prk = list.Where((s, i) => i != 0 && i != list.Count - 1).Aggregate((agg, s) => agg + s);
ECDsaCng key = new ECDsaCng(CngKey.Import(Convert.FromBase64String(prk), CngKeyBlobFormat.Pkcs8PrivateBlob));
string token = GetProviderToken();
string url = string.Format(WEB_ADDRESS, deviceToken);
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
httpRequestMessage.Headers.TryAddWithoutValidation("apns-push-type", "alert"); // or background
httpRequestMessage.Headers.TryAddWithoutValidation("apns-id", Guid.NewGuid().ToString("D"));
//Expiry
//
httpRequestMessage.Headers.TryAddWithoutValidation("apns-expiration", Convert.ToString(0));
//Send imediately
httpRequestMessage.Headers.TryAddWithoutValidation("apns-priority", Convert.ToString(10));
//App Bundle
httpRequestMessage.Headers.TryAddWithoutValidation("apns-topic", "com.xxx.yyy");
//Category
httpRequestMessage.Headers.TryAddWithoutValidation("apns-collapse-id", "test");
//
var body = JsonConvert.SerializeObject(new
{
aps = new
{
alert = new
{
title = title,
body = content,
time = DateTime.Now.ToString()
},
badge = 1,
sound = "default"
},
acme2 = new string[] { "bang", "whiz" }
});
httpRequestMessage.Version = new Version(2, 0);
using (var stringContent = new StringContent(body, Encoding.UTF8, "application/json"))
{
//Set Body
httpRequestMessage.Content = stringContent;
Http2Handler.Http2CustomHandler handler = new Http2Handler.Http2CustomHandler();
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls;
//handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
//Continue
using (HttpClient client = new HttpClient(handler))
{
HttpResponseMessage resp = await client.SendAsync(httpRequestMessage).ContinueWith(responseTask =>
{
return responseTask.Result;
});
if (resp != null)
{
string apnsResponseString = await resp.Content.ReadAsStringAsync();
handler.Dispose();
}
handler.Dispose();
}
}
}
catch (Exception ex)
{
success = false;
}
return success;
}
private string GetProviderToken()
{
double epochNow = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Dictionary<string, object> payload = new Dictionary<string, object>()
{
{ "iss", "YOUR APPLE TEAM ID" },
{ "iat", epochNow }
};
var extraHeaders = new Dictionary<string, object>()
{
{ "kid", "YOUR AUTH KEY ID" },
{ "alg", "ES256" }
};
CngKey privateKey = GetPrivateKey();
return JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, extraHeaders);
}
private CngKey GetPrivateKey()
{
using (var reader = File.OpenText(P8_PATH))
{
ECPrivateKeyParameters ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
return EccKey.New(x, y, d);
}
}
}
}
Secondly, if you noticed, I am using the custom WinHTTPHandler to make the code to support HTTP/2 based on How to make the .net HttpClient use http 2.0?. I am creating this using another class library, remember to download WinHTTPHandler from Nuget.
public class Http2CustomHandler : WinHttpHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
request.Version = new Version("2.0");
return base.SendAsync(request, cancellationToken);
}
}
After that, just call the "SendNotification" on the ApplePushNotificationPush class and you should get the message on your iPhone.
private string GetToken()
{
var dsa = GetECDsa();
return CreateJwt(dsa, "keyId", "teamId");
}
private ECDsa GetECDsa()
{
using (TextReader reader = System.IO.File.OpenText("AuthKey_xxxxxxx.p8"))
{
var ecPrivateKeyParameters =
(ECPrivateKeyParameters)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
var q = ecPrivateKeyParameters.Parameters.G.Multiply(ecPrivateKeyParameters.D).Normalize();
var qx = q.AffineXCoord.GetEncoded();
var qy = q.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
// Convert the BouncyCastle key to a Native Key.
var msEcp = new ECParameters {Curve = ECCurve.NamedCurves.nistP256, Q = {X = qx, Y = qy}, D = d};
return ECDsa.Create(msEcp);
}
}
private string CreateJwt(ECDsa key, string keyId, string teamId)
{
var securityKey = new ECDsaSecurityKey(key) { KeyId = keyId };
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256);
var descriptor = new SecurityTokenDescriptor
{
IssuedAt = DateTime.Now,
Issuer = teamId,
SigningCredentials = credentials,
};
var handler = new JwtSecurityTokenHandler();
var encodedToken = handler.CreateEncodedJwt(descriptor);
return encodedToken;
}
It have tried the above on ASP.NET CORE 2.1 and 2.2 to no avail. The response I always got was "The message received was unexpected or badly formatted" with HttpVersion20 enabled, which made me doubt whether http2 implementation is concrete.
Below is what worked on ASP.NET CORE 3.0;
var teamId = "YOURTEAMID";
var keyId = "YOURKEYID";
try
{
//
var data = await System.IO.File.ReadAllTextAsync(Path.Combine(_environment.ContentRootPath, "apns/"+config.P8FileName));
var list = data.Split('\n').ToList();
var prk = list.Where((s, i) => i != 0 && i != list.Count - 1).Aggregate((agg, s) => agg + s);
//
var key = new ECDsaCng(CngKey.Import(Convert.FromBase64String(prk), CngKeyBlobFormat.Pkcs8PrivateBlob));
//
var token = CreateToken(key, keyId, teamId);
//
var deviceToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var url = string.Format("https://api.sandbox.push.apple.com/3/device/{0}", deviceToken);
var request = new HttpRequestMessage(HttpMethod.Post, url);
//
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
//
request.Headers.TryAddWithoutValidation("apns-push-type", "alert"); // or background
request.Headers.TryAddWithoutValidation("apns-id", Guid.NewGuid().ToString("D"));
//Expiry
//
request.Headers.TryAddWithoutValidation("apns-expiration", Convert.ToString(0));
//Send imediately
request.Headers.TryAddWithoutValidation("apns-priority", Convert.ToString(10));
//App Bundle
request.Headers.TryAddWithoutValidation("apns-topic", "com.xx.yy");
//Category
request.Headers.TryAddWithoutValidation("apns-collapse-id", "test");
//
var body = JsonConvert.SerializeObject(new
{
aps = new
{
alert = new
{
title = "Test",
body = "Sample Test APNS",
time = DateTime.Now.ToString()
},
badge = 1,
sound = "default"
},
acme2 = new string[] { "bang", "whiz" }
})
//
request.Version = HttpVersion.Version20;
//
using (var stringContent = new StringContent(body, Encoding.UTF8, "application/json"))
{
//Set Body
request.Content = stringContent;
_logger.LogInformation(request.ToString());
//
var handler = new HttpClientHandler();
//
handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
//
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
//Continue
using (HttpClient client = new HttpClient(handler))
{
//
HttpResponseMessage resp = await client.SendAsync(request).ContinueWith(responseTask =>
{
return responseTask.Result;
//
});
//
_logger.LogInformation(resp.ToString());
//
if (resp != null)
{
string apnsResponseString = await resp.Content.ReadAsStringAsync();
//
handler.Dispose();
//ALL GOOD ....
return;
}
//
handler.Dispose();
}
}
}
catch (HttpRequestException e)
{
_logger.LogError(5, e.StackTrace, e);
}
For CreateToken() Refer Above Recommended solution by yaakov,
I has a problem like you. And i seen #gorniv answer. So it's work with me!
May be you can use: https://www.nuget.org/packages/Apple.Auth.Signin for it!
Goodluck!

How to use APNs Auth Key (.p8 file) in C#?

I'm trying to send push notifications to iOS devices, using token-based authentication.
As required, I generated an APNs Auth Key in Apple's Dev Portal, and downloaded it (it's a file with p8 extension).
To send push notifications from my C# server, I need to somehow use this p8 file to sign my JWT tokens. How do I do that?
I tried to load the file to X509Certificate2, but X509Certificate2 doesn't seem to accept p8 files, so then I tried to convert the file to pfx/p12, but couldn't find a way to do that that actually works.
I found a way to do that, using BouncyCastle:
private static CngKey GetPrivateKey()
{
using (var reader = File.OpenText("path/to/apns/auth/key/file.p8"))
{
var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
return EccKey.New(x, y, d);
}
}
And now creating and signing the token (using jose-jwt):
private static string GetProviderToken()
{
var epochNow = (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
var payload = new Dictionary<string, object>()
{
{"iss", "your team id"},
{"iat", epochNow}
};
var extraHeaders = new Dictionary<string, object>()
{
{"kid", "your key id"}
};
var privateKey = GetPrivateKey();
return JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, extraHeaders);
}
I hope this will be a solution;
private static string GetToken(string fileName)
{
var fileContent = File.ReadAllText(fileName).Replace("-----BEGIN PRIVATE KEY-----", "").Replace
("-----END PRIVATE KEY-----", "").Replace("\r", "");
var signatureAlgorithm = GetEllipticCurveAlgorithm(fileContent);
ECDsaSecurityKey eCDsaSecurityKey = new ECDsaSecurityKey(signatureAlgorithm)
{
KeyId = "S********2"
};
var handler = new JwtSecurityTokenHandler();
JwtSecurityToken token = handler.CreateJwtSecurityToken(
issuer: "********-****-****-****-************",
audience: "appstoreconnect-v1",
expires: DateTime.UtcNow.AddMinutes(5),
issuedAt: DateTime.UtcNow,
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(eCDsaSecurityKey, SecurityAlgorithms.EcdsaSha256));
return token.RawData;
}
private static ECDsa GetEllipticCurveAlgorithm(string privateKey)
{
var keyParams = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
var normalizedEcPoint = keyParams.Parameters.G.Multiply(keyParams.D).Normalize();
return ECDsa.Create(new ECParameters
{
Curve = ECCurve.CreateFromValue(keyParams.PublicKeyParamSet.Id),
D = keyParams.D.ToByteArrayUnsigned(),
Q =
{
X = normalizedEcPoint.XCoord.GetEncoded(),
Y = normalizedEcPoint.YCoord.GetEncoded()
}
});
}
A way to create the key without BouncyCastle:
var privateKeyString = (await File.ReadAllTextAsync("<PATH_TO_KEY_FILE>"))
.Replace("-----BEGIN PRIVATE KEY-----", "")
.Replace("-----END PRIVATE KEY-----", "")
.Replace("\n", "");
using var algorithm = ECDsa.Create();
algorithm.ImportPkcs8PrivateKey(Convert.FromBase64String(privateKeyText), out var _);
var securityKey = new ECDsaSecurityKey(algorithm) { KeyId = "<KEY_ID>" };

Sign data using CMS based format in UWP

I need to transfer data between WCF service and UWP app. So I sign and verify data after receive data. I have a problem. The signed data result in WCF is differences in UWP app.(Of course, I can't verify data) This is my source code:
// WCF
private String Sign(string Message)
{
ContentInfo cont = new ContentInfo(Encoding.UTF8.GetBytes(Message));
SignedCms signed = new SignedCms(cont, true);
_SignerCert = new X509Certificate2("Path", "Password");
CmsSigner signer = new CmsSigner(_SignerCert);
signer.IncludeOption = X509IncludeOption.None;
signed.ComputeSignature(signer);
return Convert.ToBase64String(signed.Encode());
}
and
//UWP
public static async Task<String> Sign(String Message)
{
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var CerFile = await appInstalledFolder.GetFileAsync(#"Assets\PAYKII_pkcs12.p12");
var CerBuffer = await FileIO.ReadBufferAsync(CerFile);
string CerData = CryptographicBuffer.EncodeToBase64String(CerBuffer);
await CertificateEnrollmentManager.ImportPfxDataAsync
(CerData, "Password",
ExportOption.NotExportable,
KeyProtectionLevel.NoConsent,
InstallOptions.None,
"RASKey2");
var Certificate = (await CertificateStores.FindAllAsync(new CertificateQuery() { FriendlyName = "RASKey2" })).Single();
IInputStream pdfInputstream;
InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream();
await originalData.WriteAsync(CryptographicBuffer.ConvertStringToBinary(Message,BinaryStringEncoding.Utf8));
await originalData.FlushAsync();
pdfInputstream = originalData.GetInputStreamAt(0);
CmsSignerInfo signer = new CmsSignerInfo();
signer.Certificate = Certificate;
signer.HashAlgorithmName = HashAlgorithmNames.Sha1;
IList<CmsSignerInfo> signers = new List<CmsSignerInfo>();
signers.Add(signer);
IBuffer signature = await CmsDetachedSignature.GenerateSignatureAsync(pdfInputstream, signers, null);
return CryptographicBuffer.EncodeToBase64String(signature);
}
I stumbled over your post, because I wanted to achieve something very similar: sign a message in an UWP app and verifying the signature in my WCF Service. After reading http://www.codeproject.com/Tips/679142/How-to-sign-data-with-SignedCMS-and-signature-chec, I finally managed to make this fly (with a detached signature, ie you need to have the original message for verification):
UWP:
public async static Task<string> Sign(Windows.Security.Cryptography.Certificates.Certificate cert, string messageToSign) {
var messageBytes = Encoding.UTF8.GetBytes(messageToSign);
using (var ms = new MemoryStream(messageBytes)) {
var si = new CmsSignerInfo() {
Certificate = cert,
HashAlgorithmName = HashAlgorithmNames.Sha256
};
var signature = await CmsDetachedSignature.GenerateSignatureAsync(ms.AsInputStream(), new[] { si }, null);
return CryptographicBuffer.EncodeToBase64String(signature);
}
}
WCF:
public static bool Verify(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, string messageToCheck, string signature) {
var retval = false;
var ci = new ContentInfo(Encoding.UTF8.GetBytes(messageToCheck));
var cms = new SignedCms(ci, true);
cms.Decode(Convert.FromBase64String(signature));
// Check whether the expected certificate was used for the signature.
foreach (var s in cms.SignerInfos) {
if (s.Certificate.Equals(cert)) {
retval = true;
break;
}
}
// The following will throw if the signature is invalid.
cms.CheckSignature(true);
return retval;
}
The trick for me was to understand that the desktop SignedCms needs to be constructed with the original content and then decode the signature to perform the verification.

Programmatically communicating with a Certificate Authority

I working with programmatically working with certificates and communicating with a Certificate Authority. I have been working with the CertClient and CertEnroll COM objects in C# on Windows 2008R2.
I can generate a request and get back a cert from the CA. I started with this example:
http://blogs.msdn.com/b/alejacma/archive/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c.aspx
I am having two issues that I can not figure out. First is, how can I get access to the private key that was used to generate the cert? The methods that are part of the IX509PrivateKey interface don't seem to work on my test env. The request I give the CA is different from the private key, correct?
The second issue is I can't seem to figure out to supply an enrollment agent cert when requesting a cert. The older versions of this API had a method, SetSignerCertificate, that was used. I can't find an equivalent in the new API.
An example using an Enrollment Agent certificate is found on MSDN under Create Enroll on Behalf of Another User Request. The certificate will be installed into the certificate store you specify, and you can utilize the private key as you would any other installed certificate.
Full example:
// Add references to CERTENROLL (CertEnroll 1.0 Type Library)
// and CERTCLILib (CertCli 1.0 Type Library)
using CERTCLILib;
using CERTENROLLLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using X509KeyUsageFlags = CERTENROLLLib.X509KeyUsageFlags;
namespace TestSubmitEnrollment
{
class Program
{
static void Main(string[] args)
{
string requesterName = #"DOMAIN\otherUser";
string caName = #"CA1.DOMAIN.LOCAL\DOMAIN-CA1-CA";
string template = "User";
// signerCertificate's private key must be accessible to this process
var signerCertificate = FindCertificateByThumbprint("3f817d138f32a9a8df2aa6e43b8aed76eb93a932");
// create a new private key for the certificate
CX509PrivateKey privateKey = new CX509PrivateKey();
// http://blogs.technet.com/b/pki/archive/2009/08/05/how-to-create-a-web-server-ssl-certificate-manually.aspx
privateKey.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
privateKey.MachineContext = false;
privateKey.Length = 2048;
privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE;
privateKey.Create();
// PKCS 10 Request
// we use v1 to avoid compat issues on w2k8
IX509CertificateRequestPkcs10 req = (IX509CertificateRequestPkcs10)new CX509CertificateRequestPkcs10();
req.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, template);
// PKCS 7 Wrapper
var signer = new CSignerCertificate();
signer.Initialize(false, X509PrivateKeyVerify.VerifyAllowUI, EncodingType.XCN_CRYPT_STRING_BASE64_ANY,
Convert.ToBase64String(signerCertificate.GetRawCertData()));
var wrapper = new CX509CertificateRequestPkcs7();
wrapper.InitializeFromInnerRequest(req);
wrapper.RequesterName = requesterName;
wrapper.SignerCertificate = signer;
// get CSR
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(wrapper);
var csr = enroll.CreateRequest();
//File.WriteAllText("csr.p7b", csr);
// submit
const int CR_IN_BASE64 = 1, CR_OUT_BASE64 = 1;
const int CR_IN_PKCS7 = 0x300;
ICertRequest2 liveCsr = new CCertRequest();
var disposition = (RequestDisposition)liveCsr.Submit(CR_IN_BASE64 | CR_IN_PKCS7, csr, null, caName);
if (disposition == RequestDisposition.CR_DISP_ISSUED)
{
string resp = liveCsr.GetCertificate(CR_OUT_BASE64);
//File.WriteAllText("resp.cer", resp);
// install the response
var install = new CX509Enrollment();
install.Initialize(X509CertificateEnrollmentContext.ContextUser);
install.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedRoot,
resp, EncodingType.XCN_CRYPT_STRING_BASE64_ANY, null);
}
else
{
Console.WriteLine("disp: " + disposition.ToString());
}
Console.WriteLine("done");
Console.ReadLine();
}
private enum RequestDisposition
{
CR_DISP_INCOMPLETE = 0,
CR_DISP_ERROR = 0x1,
CR_DISP_DENIED = 0x2,
CR_DISP_ISSUED = 0x3,
CR_DISP_ISSUED_OUT_OF_BAND = 0x4,
CR_DISP_UNDER_SUBMISSION = 0x5,
CR_DISP_REVOKED = 0x6,
CCP_DISP_INVALID_SERIALNBR = 0x7,
CCP_DISP_CONFIG = 0x8,
CCP_DISP_DB_FAILED = 0x9
}
private static X509Certificate2 FindCertificateByThumbprint(string sslCertThumbprint)
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint, sslCertThumbprint, true);
if (certs.Count > 0)
{
return certs[0];
}
else
{
throw new KeyNotFoundException();
}
}
finally
{
store.Close();
}
}
// we re-declare this to account for backcompat to 2k8
[ComImport, Guid("884E2042-217D-11DA-B2A4-000E7BBB2B09")]
class CX509CertificateRequestPkcs10
{
}
}
}
The request I give the CA is different from the private key, correct?
You only pass the public key to the CA.
I can't seem to figure out to supply an enrollment agent cert when requesting a cert.
You Need to wrap the PKCS10 in a CMS/CMC. Have a look here https://www.rfc-editor.org/rfc/rfc5272

Categories

Resources