C#, Programming

RSA 2048 using CryptoAPI and C#

RSACryptoServiceProvider performs asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP). – MSDN

Generate Public and Private Keys

public static void GenerateKeys(out string PublicKey, out string PrivateKey)
{
	using (RSACryptoServiceProvider RSA2048 = new RSACryptoServiceProvider(2048))
	{
		PublicKey = RSA2048.ToXmlString(false);
		PrivateKey = RSA2048.ToXmlString(true);
	}
}

Encrypt

public static string Encrypt(string PublicKey, string plain)
{
	byte[] encrypted;
 
	using (RSACryptoServiceProvider RSA2048 = new RSACryptoServiceProvider(2048))
	{
		RSA2048.FromXmlString(PublicKey);
		encrypted = RSA2048.Encrypt(Encoding.UTF8.GetBytes(plain), false);
	}
 
	return Convert.ToBase64String(encrypted);
}

Decrypt

public static string Decrypt(string PrivateKey, string cipher)
{
	byte[] decrypted;
 
	using (RSACryptoServiceProvider RSA2048 = new RSACryptoServiceProvider(2048))
	{
		RSA2048.FromXmlString(PrivateKey);
		decrypted = RSA2048.Decrypt(Convert.FromBase64String(cipher), false);
	}
 
	return Encoding.UTF8.GetString(decrypted);
}

Download full source code from GitHub.

git clone https://github.com/maldevel/RSA2048Sharp