Hey!

I am working on a project which involves RSA, and I am trying to get familiar with the RSA C# library.

I have successfully created key pairs, encrypted with the recievers public key, and decrypted with the recipients private key. This provides confidentiality.

RSA is supposed to be able to use both keys for either encryption or decryption. That is, I can encrypt with my own private key, and the recipient kan then decrypt with my public key. This does not provide confidentiality, but authentication, which I'm sure readers of this forum know.

I get an error when i try to do rsa.Decrypt without feeding the rsa component with my private key. I suppose I could null-ify some XML elements but I find it probable that it won't work.

How can I perform this operation with the C# library? I have also seen SignData, and SignHash. I guess perhaps these can be used. I can't really understand the difference between them though.

Please fill me in, any help is greatly appreciated!

Below is some code I use.

all the best

BendikM

using System;

using System.Collections.Generic;

using System.IO;

using System.Text;

using System.Security.Cryptography;

namespace BiometricsLibrary

{

public static class Cryptography

{

public static RSACryptoServiceProvider rsa;

//Assign parameters to the RSACryptoService. This is called upon all encryptions / decryptions

private static void AssignParameter()

{

const int PROVIDER_RSA_FULL = 1;

const string CONTAINER_NAME = "BiocrypticsContainer";

CspParameters cspParams;

cspParams = new CspParameters(PROVIDER_RSA_FULL);

cspParams.KeyContainerName = CONTAINER_NAME;

cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";

rsa = new RSACryptoServiceProvider(cspParams);

}

public static string EncryptData(string plaintext, StreamReader public_key_reader)

{

AssignParameter();

string publicOnlyKeyXML = public_key_reader.ReadToEnd();

rsa.FromXmlString(publicOnlyKeyXML);

public_key_reader.Close();

//read plaintext, encrypt it to ciphertext

byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(plaintext);

byte[] cipherbytes = rsa.Encrypt(plainbytes, false);

return Convert.ToBase64String(cipherbytes);

}

public static string DecryptData(string ciphertext, StreamReader private_key_reader)

{

AssignParameter();

byte[] ciphertextBytes = Convert.FromBase64String(ciphertext);

string publicPrivateKeyXML = private_key_reader.ReadToEnd();

rsa.FromXmlString(publicPrivateKeyXML);

private_key_reader.Close();

//read ciphertext, decrypt it to plaintext

byte[] plaintextBytes = rsa.Decrypt(ciphertextBytes, false);

return System.Text.Encoding.UTF8.GetString(plaintextBytes);

}

}

}