so I am working on an assignment that is meant to teach us the methods of encrypting and decrypting messages.
I have made a simple application that will take in text from one textBox and on a button click reproduce the encrypted bytes into another textBox. Also have another button that when pressed will take the encrypted byte array, and decrypt it.
Everything works, but if my message to be encrypted is larger than 128 bytes than it will throw an error. Makes sense since RSA key size is 128. So I am working on writing some code to handle cases where the byte array exceeds 128.
So far this is what I have come up with:
//Encode the data to encrypt as a byte array
var dataToEncrypt = encoder.GetBytes(txtPlain.Text);
//store dataLength
int dataLength = dataToEncrypt.Length;
//Check if dataLength > 128
if(dataLength > 128)
{
//Divide dataLength by 128 to determine how many cycles will be needed
double numOfCycles = (dataLength / 128);
//round up to nearest whole number
cycles = (int) Math.Ceiling(numOfCycles);
}
//for however many cycles
for (int i = 0; i < cycles; i++)
{
var myByteArray = new byte[128];
for (int j = 0; j < 128; j++)
{
int currentByte = i * 128 + j;
myByteArray[j] = dataToEncrypt[currentByte];
}
var encryptedByteArray = myRSA.Encrypt(myByteArray, false).ToArray();
var length = encryptedByteArray.Count();
var item = 0;
var sb = new StringBuilder();
//Change each byte in the encrypted byte array to text
foreach (var x in encryptedByteArray)
{
item++;
sb.Append(x);
if (item < length) sb.Append(",");
}
txtCypher.Text = sb.ToString();
}
I have tried to calculate how many cycles (encrypting 128 bytes at a time) will be needed, and then repeat this process of encrypting a byte array of 128 bytes and printing out.
However I continue to get an error An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Bad Length.
from line: var encryptedByteArray = myRSA.Encrypt(myByteArray, false).ToArray();
It appears that my byte array is exceeding the limit of 128, but I cannot seem to figure out exactly how.