I set up a small example where all the magic happens in just one method.
I'm using 3
TextBox
es to show the path from plain text via encryption to the decrypted text.
TextBoxes are named
textBoxPlain
,
textBoxEncrypted
and
textBoxDecrypted
.
So you can quite easily open a new project and just put 3 textboxes on the form.
textBoxEncrypted is set to multiline. Encrypting and decrypting all happens in
textBoxPlain_TextChanged
using System;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Collections;
namespace EncryptionRSA
{
public partial class Form1 : Form
{
private RSACryptoServiceProvider rsaSender;
private RSACryptoServiceProvider rsaReceiver;
private string publicKey;
private string privateKey;
private int keySize = 1024;
public Form1()
{
InitializeComponent();
rsaReceiver = new RSACryptoServiceProvider(keySize);
publicKey = rsaReceiver.ToXmlString(false);
privateKey = rsaReceiver.ToXmlString(true);
}
private void textBoxPlain_TextChanged(object sender, EventArgs e)
{
rsaSender = new RSACryptoServiceProvider();
rsaSender.FromXmlString(publicKey);
byte[] bytes = Encoding.UTF32.GetBytes(textBoxPlain.Text);
int maxLength = keySize/8 - 42;
int dataLength = bytes.Length;
int iterationsenc = dataLength / maxLength;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= iterationsenc; i++)
{
byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
byte[] encryptedBytes = rsaSender.Encrypt(tempBytes, true);
Array.Reverse(encryptedBytes);
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
}
textBoxEncrypted.Text = stringBuilder.ToString();
rsaReceiver = new RSACryptoServiceProvider();
rsaReceiver.FromXmlString(privateKey);
int base64BlockSize = ((keySize / 8) % 3 != 0) ? (((keySize / 8) / 3) * 4) + 4 : ((keySize / 8) / 3) * 4;
int iterationsdec = textBoxEncrypted.Text.Length / base64BlockSize;
ArrayList arrayList = new ArrayList();
for (int i = 0; i < iterationsdec; i++)
{
byte[] encryptedBytes = Convert.FromBase64String(textBoxEncrypted.Text.Substring(base64BlockSize * i, base64BlockSize));
Array.Reverse(encryptedBytes);
arrayList.AddRange(rsaReceiver.Decrypt(encryptedBytes, true));
}
textBoxDecrypted.Text = Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
}
}
}