January 27
2009

RSA Cryptography in C# Tutorial Part 4a & b

C# Tutorial Windows

Decrypting the message is exactly the same process, but backwards.

Get the Ciphertext, XML key,( and bitstrength) from the text and key files.

Make a new RsaCryptoServiceProvider, like before, with the correst bitstrength.

Finding the MaxLength here is hard. This command is a shorthand version of a if statement.

int maxLength = ( ( bitStrength / 8 ) % 3 != 0 ) ? ( ( ( bitStrength / 8 ) / 3 ) * 4 ) + 4 : ( ( bitStrength / 8 ) / 3 ) * 4;

Just trust me, it works.

Next, work out the amount of loops, which is the amount of maxLengths in the encoded text length.

int loops = cipherText.Length / maxLength;

Create a byte array, called fullbytes with a length of 0.

Make a loop for the amount of loops.

in the loop, make another byte array called encBytes, and get the corresponding chunk of ciphertext.

byte[] encBytes = Convert.FromBase64String(text.Substring(base64BlockSize * i, base64BlockSize));

Then, another byte array for the decrypted text, and use rsa.Decrypt on the encBytes.

byte[] bytes = rsa.Decrypt(encBytes, false);

if you use true here, it uses fOAEP padding, but this is only available in XP and above.

Resize the fullbytes array, to make room for the decrypted text.

Array.Resize(ref fullbytes, fullbytes.Length + bytes.Length);

Then add on the new bytes.

for (int k = 0; k < bytes.Length; k++)
{
fullbytes[l] = bytes[k];
l++;
}

Convert this back into a string, and you are done!

ptext = Encoding.UTF32.GetString(fullbytes);

Decode

The only thing left to do now is to add a few final touches to your program/library.

Feel free to post any, results/comments/thoughts in the comments, and I hope this tutorial works for you!

One Comment on “RSA Cryptography in C# Tutorial Part 4a & b”

  1. [...] Tutorial Part 4a & b [...]

Leave a Reply