RSA Decryption not working with an ambiguous exception - c#

I am trying to encrypt a string of information using RSA in dot net core, the intention is to only encrypt the plain text and send it to a server running PHP/MySQL and store the encrypted information. the server does not send any confirmation or other data in reply, so it is a one-way communication (if I could say).
for this purpose I have three methods, one that generates a Keypair of 2048, and stores the information in a List (not the RSAParameter) and returns, the other two methods are encryption and decryption methods.
The problem is the Encryption works fine with the public key as modulus and public exponent as an exponent, while at the decryption, with the private key as modulus, public exponent as an exponent, and the private exponent "D" as a private exponent, I am getting the exception " Modulus and Exponents are required fields", if I remove the "D" an exception of "Invalid Data Length for this Key size" is thrown, I am not so good at a mathematical aspect of RSA. I have also tried every method of getting bytes ( Encoding, Covert, etc). Below are the three methods I am using.
Method to Generate Keypair and other Parameters:
public static List<string> RsaKeyGen()
{
List<string> keyPair = new List<string>();
RSA rsa = RSA.Create(2048);
RSAParameters param = rsa.ExportParameters(true);
keyPair.Add(Convert.ToBase64String(rsa.ExportRSAPrivateKey()));
keyPair.Add(Convert.ToBase64String(rsa.ExportRSAPublicKey()));
keyPair.Add(Convert.ToBase64String(param.Exponent));
keyPair.Add(Convert.ToBase64String(param.D));
return keyPair;
}
The Encryption Method
public static string RsaEncrypt(byte[] PUBLIC_KEY ,byte[] EXPONENT, string text)
{
RSA rsa = RSA.Create(2048);
RSAParameters param = new RSAParameters();
param.Modulus = PUBLIC_KEY;
param.Exponent = EXPONENT;
rsa.ImportParameters(param);
return Convert.ToBase64String(rsa.Encrypt(Convert.FromBase64String(text), RSAEncryptionPadding.Pkcs1));
}
and finally the Decrypt Method:
public static string RsaDecrypt(byte[] PRIVATE_KEY, byte[] EXPONENT, byte[] PEXPO , string DATA)
{
RSA rsa = RSA.Create(2048);
RSAParameters param = new RSAParameters();
param.Modulus = PRIVATE_KEY;
param.Exponent = EXPONENT;
param.D = PEXPO;
rsa.ImportParameters(param);
return Convert.ToBase64String(rsa.Decrypt(Convert.FromBase64String(DATA), RSAEncryptionPadding.Pkcs1));
}

Here is a Minimum Working Example (MWE) using your code as a starting point. As I commented, you just need to import your private/public key. No need to supply Exponent or D.
(by the way, you are converting to-and-from binary and string types all over the place. I suggest you base your whole RSA code on byte[] and only convert back to string if/when you need to. The below code is written to match your supplied signatures)
public class RsaMwe
{
public static bool Demo()
{
var strings = RsaKeyGen();
var privKey = Convert.FromBase64String(strings[0]);
var pubKey = Convert.FromBase64String(strings[1]);
var clearText = "Hello World!";
var clearText64 = Convert.ToBase64String(Encoding.Default.GetBytes(clearText));
var encrypted64 = RsaEncrypt(pubKey, clearText64);
var decrypted64 = RsaDecrypt(privKey, encrypted64);
return clearText == Encoding.Default.GetString(Convert.FromBase64String(decrypted64));
}
public static List<string> RsaKeyGen()
{
List<string> keyPair = new List<string>();
using RSA rsa = RSA.Create(2048);
keyPair.Add(Convert.ToBase64String(rsa.ExportRSAPrivateKey()));
keyPair.Add(Convert.ToBase64String(rsa.ExportRSAPublicKey()));
return keyPair;
}
public static string RsaEncrypt(byte[] pubKey, string clearText64)
{
using RSA rsa = RSA.Create(2048);
rsa.ImportRSAPublicKey(pubKey, out _);
return Convert.ToBase64String(rsa.Encrypt(Convert.FromBase64String(clearText64), RSAEncryptionPadding.Pkcs1));
}
public static string RsaDecrypt(byte[] privKey, string cypherText64)
{
using RSA rsa = RSA.Create(2048);
rsa.ImportRSAPrivateKey(privKey, out _);
return Convert.ToBase64String(rsa.Decrypt(Convert.FromBase64String(cypherText64), RSAEncryptionPadding.Pkcs1));
}
}
Also don't forget to dispose your RSA objects.

Related

Verify JWT using public key in string

I have public key in following format:
-----BEGIN RSA PUBLIC KEY-----MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJg+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIaNyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qqmHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4svz4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhvdzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB-----END RSA PUBLIC KEY-----
How can I implement C# to verify my JWT using that string? I have found similar topic at Verifying JWT signed with the RS256 algorithm using public key in C# but none of solutions suits my case.
There is my code:
public static bool TransformKey(string fullKey)
{
try
{
var publicKey = fullKey.Replace("-----BEGIN RSA PUBLIC KEY-----", "");
publicKey = publicKey.Replace("-----END RSA PUBLIC KEY-----", "");
publicKey = publicKey.Replace("\n", "");
var keyBytes = Convert.FromBase64String(publicKey); // your key here
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters
{
Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
};
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
}
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
string key = "-----BEGIN RSA PUBLIC KEY-----MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJg+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIaNyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qqmHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4svz4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhvdzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB-----END RSA PUBLIC KEY-----";
bool test = TransformKey(key);
Console.ReadKey();
}
It returns exception when I try to initialize asymmetricKeyParameter object:
System.ArgumentException: Unknown object in GetInstance: Org.BouncyCastle.Asn1.DerInteger
Parameter name: obj
w Org.BouncyCastle.Asn1.Asn1Sequence.GetInstance(Object obj)
w Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier.GetInstance(Object obj)
w Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo..ctor(Asn1Sequence seq)
w Org.BouncyCastle.Asn1.X509.SubjectPublicKeyInfo.GetInstance(Object obj)
w Org.BouncyCastle.Security.PublicKeyFactory.CreateKey(Byte[] keyInfoData)
Code snippet with Modulus and Exponent in string type that can be useful:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(
new RSAParameters()
{
Modulus = FromBase64Url("w7Zdfmece8iaB0kiTY8pCtiBtzbptJmP28nSWwtdjRu0f2GFpajvWE4VhfJAjEsOcwYzay7XGN0b-X84BfC8hmCTOj2b2eHT7NsZegFPKRUQzJ9wW8ipn_aDJWMGDuB1XyqT1E7DYqjUCEOD1b4FLpy_xPn6oV_TYOfQ9fZdbE5HGxJUzekuGcOKqOQ8M7wfYHhHHLxGpQVgL0apWuP2gDDOdTtpuld4D2LK1MZK99s9gaSjRHE8JDb1Z4IGhEcEyzkxswVdPndUWzfvWBBWXWxtSUvQGBRkuy1BHOa4sP6FKjWEeeF7gm7UMs2Nm2QUgNZw6xvEDGaLk4KASdIxRQ"),
Exponent = FromBase64Url("AQAB")
});
In the case of the .NET Framework (e.g. 4.7.2), a public PKCS#1 key can be imported for example using BouncyCastle (e.g. v1.8.6.1):
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
...
string publicPKCS1 = #"-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA1pjRK+cOnEsh5L1wrt1Tmx+FvyNRj4wuAotlqIWtHS8pIqRzsIOJ
g+tlbUtEXYju+KOcIohZnnmfj0cq28RcQ19HIohqUXypmUbNy9np/M+Aj9NcyKIa
NyuEZ+UhcU/OIStHK4eTUJt+RWL+0Q1/rl49tg7h+toB9Y6Y3SeytXvZhMx3N5qq
mHHNorpfb65bvvHsicGDB7vK5kn55o+C2LhRIxfnw87nKnhPBMRbZg+BKCTXD4sv
z4a2xiR/uM4rxebIBgB3Sm4X1w3yoRr0F3IDhAgXmEhSZ078wm3ohPfuuwymfVhv
dzavm42NwzixZ7n52SowFE2v0DSJh3IbPwIDAQAB
-----END RSA PUBLIC KEY-----";
PemReader pemReader = new PemReader(new StringReader(publicPKCS1));
AsymmetricKeyParameter asymmetricKeyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters((RsaKeyParameters)asymmetricKeyParameter);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
...
The validation of the JWT can be done with a JWT library (e.g. System.IdentityModel.Tokens.Jwt) or with a pure cryptography API. Both are described in detail in the answers to the linked question. Regarding the former, see also here, 2nd paragraph.

How can I verify signature for open PGP using BouncyCastle

How can I verify signature for open PGP using BouncyCastle?
I am using C#
I have pulic key http://itransact.com/support/toolkit/html-connection/pgp.php
I am using BouncyCastle as open pgp library
I have signature that I recieve in query string.
According to instruction (http://itransact.com/downloads/PCFullDocument-4.4.pdf p.145) algorithm is RSA.
I checked a lot of resource but no success. As I understood I need to pass public key and signature to some Verify method.
It is also not clear if I have to convert given public key in string format to some appropriate public key object. If I have to what is the type? I have tried to convert it to RsaKeyParameters but got error message about inappropriate block on public key.
At the moment I have the following code
private bool VerifyWithPublicKey(string data, byte[] sig)
{
RSACryptoServiceProvider rsa;
using (var keyreader = new StringReader(publicKey))
{
var pemReader = new PemReader(keyreader);
var y = (RsaKeyParameters)pemReader.ReadObject();
rsa = (RSACryptoServiceProvider)RSA.Create();
var rsaParameters = new RSAParameters();
rsaParameters.Modulus = y.Modulus.ToByteArray();
rsaParameters.Exponent = y.Exponent.ToByteArray();
rsa.ImportParameters(rsaParameters);
// compute sha1 hash of the data
var sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
// This always returns false
return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), sig);
}
Using RSA is not your case. You need
Define public key
Convert public ket into PgPPublicKey
Get PgpSignature object
Verify signature
To verify signature you will need original data that was signed.
public class iTransactVerifier
{
private const string PublicKey = #"-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: 4.5
mQCNAjZu
-----END PGP PUBLIC KEY BLOCK-----";
public static bool Verify(string signature, string data)
{
var inputStream = ConvertStringToStream(signature);
PgpPublicKey publicKey = ReadPublicKeyFromString();
var stream = PgpUtilities.GetDecoderStream(inputStream);
PgpObjectFactory pgpFact = new PgpObjectFactory(stream);
PgpSignatureList sList = pgpFact.NextPgpObject() as PgpSignatureList;
if (sList == null)
{
throw new InvalidOperationException("PgpObjectFactory could not create signature list");
}
PgpSignature firstSig = sList[0];
firstSig.InitVerify(publicKey);
firstSig.Update(Encoding.UTF8.GetBytes(data));
var verified = firstSig.Verify();
return verified;
}
....
private static PgpPublicKey ReadPublicKeyFromString()
{
var varstream = ConvertStringToStream(PublicKey);
var stream = PgpUtilities.GetDecoderStream(varstream);
PgpObjectFactory pgpFact = new PgpObjectFactory(stream);
var keyRing = (PgpPublicKeyRing)pgpFact.NextPgpObject();
return keyRing.GetPublicKey();
}
}

What is the difference between signing by OpenSSL and Microsoft Cryptography libraries?

I wrote two methods for signing using RSA and SHA256, the first one with OpenSSL library and the second one with Microsoft Cryptography library.
OpenSSL implementation:
private string PasswordHandler(bool verify, object userdata)
{
return userdata.ToString();
}
private string Sign(string signParams)
{
var privateCertPath = HttpContext.Current.Server.MapPath(#"~\certificate.pem");
string privateKey;
using (StreamReader sr = new StreamReader(privateCertPath))
{
privateKey = sr.ReadToEnd();
}
OpenSSL.Crypto.RSA rsa = OpenSSL.Crypto.RSA.FromPrivateKey(new BIO(privateKey), PasswordHandler, _password);
//hash method
MessageDigest md = MessageDigest.SHA1;
BIO b = new BIO(signParams);
CryptoKey ck = new CryptoKey(rsa);
byte[] res1 = MessageDigestContext.Sign(md, b, ck);
return Uri.EscapeDataString(System.Convert.ToBase64String(res1));
}
Cryptography implementation:
private string Sign(string data)
{
var privateCertPath = HttpContext.Current.Server.MapPath(#"~\certificate.pfx");
X509Certificate2 privateCert = new X509Certificate2(privateCertPath, _password, X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
RSACryptoServiceProvider privateKey1 = new RSACryptoServiceProvider();
privateKey1.ImportParameters(privateKey.ExportParameters(true));
// Get the bytes to be signed from the string
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
//const string sha256Oid = "2.16.840.1.101.3.4.2.1";
//HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
//byte[] hashBytes = algorithm.ComputeHash(bytes);
//byte[] signature = privateKey1.SignHash(hashBytes, sha256Oid);
byte[] signature = privateKey1.SignData(bytes, "SHA256");
// Base 64 encode the sig so its 8-bit clean
return Convert.ToBase64String(signature);
}
Signing with OpenSSL works, generates valid digital signature but signing with Cryptography lib generates invalid signature so my question is what I implemented wrong?
I tried to use different encoding but it did not help. Certificates are generated correctly.
It might by also useful to tell basic info about the .pem certificate:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC

Encryption with certificate

I'm quite new to all this encryption thing and I'm trying to do a simple app to encrypt a given string. Here's my code:
public static X509Certificate2 getPublicKey()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
X509Certificate2 cert2 = new X509Certificate2("c:\\certificate.cer");
return cert2;
}
public static string cipherRequest(byte[] stringToEncrypt)
{
X509Certificate2 certificate = getPublicKey();
RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;
byte[] cryptedData = rsa.Encrypt(stringToEncrypt, true);
return Convert.ToBase64String(cryptedData);
}
public static void Main()
{
try
{
ASCIIEncoding ByteConverter = new ASCIIEncoding();
byte[] test = ByteConverter.GetBytes("stringtoencrypt");
string first = cipherRequest(test);
string second= cipherRequest(test);
Console.WriteLine("first: {0}", first);
Console.WriteLine("second: {0}", second);
}
catch(CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
So every time I call the cipherRequest it produces different results. I've checked the certificate is loaded but it produces different results.
Any thoughts?
Random padding is added before the actual encryption to avoid certain attacks. This is why you are getting different results each time you call the encryption method.
For more info, see this post:
RSA in C# does not produce same encrypted string for specific keys?

CryptographicException intermittently occurs when encrypting/decrypting with RSA

I'm trying to encrypt and decrypt data using RSA in C#. I have the following MSTest unit test:
const string rawPassword = "mypass";
// Encrypt
string publicKey, privateKey;
string encryptedPassword = RSAUtils.Encrypt(rawPassword, out publicKey, out privateKey);
Assert.AreNotEqual(rawPassword, encryptedPassword,
"Raw password and encrypted password should not be equal");
// Decrypt
string decryptedPassword = RSAUtils.Decrypt(encryptedPassword, privateKey);
Assert.AreEqual(rawPassword, decryptedPassword,
"Did not get expected decrypted password");
It fails during decryption, but only sometimes. It seems like whenever I set breakpoints and step through the test, it passes. This made me think perhaps something wasn't finishing in time for decryption to occur successfully, and me slowing stepping through it while debugging gave it enough time to complete. When it fails, the line it seems to fail at is decryptedBytes = rsa.Decrypt(bytesToDecrypt, false); in the following method:
public static string Decrypt(string textToDecrypt, string privateKeyXml)
{
if (string.IsNullOrEmpty(textToDecrypt))
{
throw new ArgumentException(
"Cannot decrypt null or blank string"
);
}
if (string.IsNullOrEmpty(privateKeyXml))
{
throw new ArgumentException("Invalid private key XML given");
}
byte[] bytesToDecrypt = ByteConverter.GetBytes(textToDecrypt);
byte[] decryptedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKeyXml);
decryptedBytes = rsa.Decrypt(bytesToDecrypt, false); // fail here
}
return ByteConverter.GetString(decryptedBytes);
}
It fails with this exception:
System.Security.Cryptography.CryptographicException: Bad Data
My Encrypt method is as follows:
public static string Encrypt(string textToEncrypt, out string publicKey,
out string privateKey)
{
byte[] bytesToEncrypt = ByteConverter.GetBytes(textToEncrypt);
byte[] encryptedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
encryptedBytes = rsa.Encrypt(bytesToEncrypt, false);
publicKey = rsa.ToXmlString(false);
privateKey = rsa.ToXmlString(true);
}
return ByteConverter.GetString(encryptedBytes);
}
The ByteConverter used throughout is just the following:
public static readonly UnicodeEncoding ByteConverter = new UnicodeEncoding();
I've seen a few questions on StackOverflow about RSA encryption and decryption with .NET. This one was due to encrypting with the private key and trying to decrypt with the public key, but I don't think I'm doing that. This question has the same exception as me, but the selected answer was to use OpenSSL.NET, which I would prefer not to do.
What am I doing wrong?
Could you replace ByteConverter.GetBytes with Convert.FromBase64String and replace ByteConverter.GetString with Convert.ToBase64String and see if that helps. Bad Data exception usually means that you have an invalid character in the data or that the length is not the correct length for decrypting. I think using the Convert functions might fix your problems.
public static readonly UnicodeEncoding ByteConverter = new UnicodeEncoding();
public static string Encrypt(string textToEncrypt, out string publicKey,
out string privateKey)
{
byte[] bytesToEncrypt = ByteConverter.GetBytes(textToEncrypt);
byte[] encryptedBytes;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
encryptedBytes = rsa.Encrypt(bytesToEncrypt, false);
publicKey = rsa.ToXmlString(false);
privateKey = rsa.ToXmlString(true);
}
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string textToDecrypt, string privateKeyXml)
{
if (string.IsNullOrEmpty(textToDecrypt))
{
throw new ArgumentException(
"Cannot decrypt null or blank string"
);
}
if (string.IsNullOrEmpty(privateKeyXml))
{
throw new ArgumentException("Invalid private key XML given");
}
byte[] bytesToDecrypt = Convert.FromBase64String(textToDecrypt);
byte[] decryptedBytes;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKeyXml);
decryptedBytes = rsa.Decrypt(bytesToDecrypt, false); // fail here
}
return ByteConverter.GetString(decryptedBytes);
}
Your problem is with the conversion from bytes to string. Not all sequences of bytes are a valid UTF-16 encoding and you are using a UnicodeEncoding that silently ignores invalid bytes. If you used
public static readonly UnicodeEncoding ByteConverter = new UnicodeEncoding(false, false, true);
instead, your code would have failed when trying to convert the bytes instead of silently replacing the invalid byte-pairs with 0xFFFD.
The fact that the test worked while debugging was a coincidence. You are using a random RSA key-pair, so sometimes you will get a encryption that is a valid UTF-16 encoding.
The fix is, as SwDevMan81 suggests, to use an encoding that can convert all possible byte-arrays. F.x. Base64-encoding.
I would recommend using this class, sadly I don't remember the original author though..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Encryption
{
class AsymmetricED
{
private static RSAParameters param = new RSAParameters();
/// <summary>
/// Get Parameters
/// </summary>
/// <param name="pp">Export private parameters?</param>
/// <returns></returns>
public static RSAParameters GenerateKeys(bool pp)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
if (param.Equals(new RSAParameters()))
{
param = RSA.ExportParameters(true);
}
RSA.ImportParameters(param);
return RSA.ExportParameters(pp);
}
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
{
ConsoleColor col = Console.BackgroundColor;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(e.ToString());
Console.BackgroundColor = col;
return null;
}
}
}
}
Use as:
Encryption.AsymmetricED.RSAEncrypt(Data, GenerateKeys(false), false);
Encryption.AsymmetricED.RSADecrypt(Data, GenerateKeys(true), false);
EDIT:
I also recommend that you don't use this for large data encryption. Usually you would encrypt the actual data with a symmetric algorithm (AES, etc), then encrypt the symmetric key (randomly generated) with the RSA algorithm, then send the rsa encrypted symmetric key, and the symmetric key data..
You should also look at RSA signing, to make sure the data is coming from where it says it is..

Categories