Created
December 2, 2014 15:40
-
-
Save flytzen/446e86fe6c517f80dd80 to your computer and use it in GitHub Desktop.
Basic encryption with certificates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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=Frans2" -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, "Frans2", false); // You should use a thumbprint instead of name here | |
X509Certificate2 cert = null; | |
foreach (var c in matches) // Not sure if you need this with thumbprints... | |
{ | |
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