Skip to content

Instantly share code, notes, and snippets.

@njmube
Forked from angelobelchior/RSA.cs
Last active August 29, 2015 14:23
Show Gist options
  • Save njmube/3ef8500b0161d82d6990 to your computer and use it in GitHub Desktop.
Save njmube/3ef8500b0161d82d6990 to your computer and use it in GitHub Desktop.
using System;
using System.Security.Cryptography;
namespace Cryptography
{
public class RSA
{
public static string Encrypt(string text, string key)
{
Throw.IfIsNullOrEmpty(text);
Throw.IfIsNullOrEmpty(key);
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(text), true);
return BitConverter.ToString(bytes);
}
public static string Decrypt(string text, string key)
{
Throw.IfIsNullOrEmpty(text);
Throw.IfIsNullOrEmpty(key);
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
string[] decryptArray = text.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
return System.Text.UTF8Encoding.UTF8.GetString(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment