Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Created July 19, 2020 15:36
Show Gist options
  • Save arman-hpp/4bac6e6b9d1bf02e8143023dbd084488 to your computer and use it in GitHub Desktop.
Save arman-hpp/4bac6e6b9d1bf02e8143023dbd084488 to your computer and use it in GitHub Desktop.
SignController.cs
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Http;
namespace SignGenApi.Controllers
{
public class SignController : ApiController
{
public string Get(string text, string certSubject)
{
// Access Personal (MY) certificate store of current user
var my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);
// Find the certificate we'll use to sign
RSACryptoServiceProvider csp = null;
foreach (var cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
// We found it.
// Get its associated CSP and private key
csp = (RSACryptoServiceProvider)cert.PrivateKey;
}
}
if (csp == null)
{
return string.Empty;
//throw new Exception("No valid cert was found");
}
// Hash the data
var sha1 = new SHA1Managed();
var encoding = new UnicodeEncoding();
var data = encoding.GetBytes(text);
var hash = sha1.ComputeHash(data);
// Sign the hash
var bytes = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
// Convert to base64
return Convert.ToBase64String(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment