Skip to content

Instantly share code, notes, and snippets.

@flytzen
Created October 7, 2014 22:52
Show Gist options
  • Save flytzen/f876757061608d9d44d3 to your computer and use it in GitHub Desktop.
Save flytzen/f876757061608d9d44d3 to your computer and use it in GitHub Desktop.
Sample of using a self-signed X509 certificate to do public/private key encryption. **Use at your own risk **
namespace EncryptionWithCertificate
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
class Program
{
//// makecert -pe MyCryptCert.cer -ss my -n "CN=Frans" -sky exchange -r
static void Main(string[] args)
{
Console.WriteLine("***********************");
string input = "Hello there";
Console.WriteLine("Input: {0}", input);
var encrypted = Encrypt(input);
Console.WriteLine("Encrypted: {0}", encrypted);
var decrypted = Decrypt(encrypted);
Console.WriteLine("Decrypted: {0}", decrypted);
Console.WriteLine("***********************");
Console.ReadLine();
}
private static string Encrypt(string input)
{
var cert = new X509Certificate2(@"c:\temp\MyCryptCert.cer");
RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] cipherData = rsaEncryptor.Encrypt(Encoding.UTF8.GetBytes(input), true);
return Convert.ToBase64String(cipherData);
}
private static string Decrypt(string input)
{
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var matches = store.Certificates.Find(X509FindType.FindBySubjectName, "Frans", false);
X509Certificate2 cert = null;
foreach (var c in matches)
{
cert = c;
Console.WriteLine("Found a cert"); // Should test for finding more than one
}
RSACryptoServiceProvider encryptor = (RSACryptoServiceProvider)cert.PrivateKey;
var inputBytes = Convert.FromBase64String(input);
var decoded = encryptor.Decrypt(inputBytes, true);
var decodedString = Encoding.UTF8.GetString(decoded);
return decodedString;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment