这个问题是关于加密/解密算法的大学项目。
加密效果很好,我需要做的就是解密。目标是将ASCII代码解密为纯文本。但在我的情况下,它用另一个ASCII码解密它。这是解密代码:
public static string BinaryToString(string data)
{
List byteList = new List();
for (int i = 0; i < data.Length; i += 8)
{
byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
}
return Encoding.ASCII.GetString(byteList.ToArray());
}
private void BTN_Decrypt_Click(object sender, EventArgs e) {
lis.Clear();
lisToBeDone.Clear();
lb_output.Items.Clear();
bkey = ""; btext = "";
if (tb_key.Text.Length <= 1)
MessageBox.Show("Enter a valid key.");
else
{
skey = tb_key.Text;
stext = tb_input.Text;
int strlength = stext.Length;
if (stext.Length % 2 != 0)
{
stext += '/';
strlength++;
}
char[,] twoDarray = new char[strlength / 2, 16];
int rowcount = 0;
//converts the key to binary 2 by 2 chars
foreach (char ch in skey)
{
string bit = Convert.ToString(ch, 2);
if (bit.Length !=
bit = bit.PadLeft(8, '0');
bkey += bit;
}
lb_output.Items.Add("Key in Binary:" + bkey);
lb_output.Update();
//converts the text to binary 2 by 2 chars
char[] temparray = new char[2];
for (int i = 0; i < strlength; i++)
if (i % 2 == 0)
{
temparray[0] = stext.ElementAt(i);
temparray[1] = stext.ElementAt(i + 1);
foreach (char ch in temparray)
{
string bit = Convert.ToString(ch, 2);
if (bit.Length !=
bit = bit.PadLeft(8, '0');
btext += bit;
}
for (int y = 0; y < 16; y++)
{
twoDarray[rowcount, y] = btext.ElementAt(y);
}
btext = "";
rowcount++;
}
lb_output.Items.Add("Text in binary form: ");
lb_output.Items.Add(btext);
lb_output.Update();
//here we Decrypt our text
string s;
int z = rowcount;
int x = 0;
lb_output.Items.Add("Decrypted text:");
for (int i = 0; i < z; i++)
{
s = "";
x = 0;
while(x <=15)
{
s += twoDarray[i, x].ToString();
x++;
}
lisToBeDone.Add(s);
}
for (int k = 0; k < lisToBeDone.Count; k++)
{
cipherText = "";
mydes.Decrypt(bkey, lisToBeDone[k]);
cipherText = mydes.CipherText;
lis.Add(cipherText);
}
string tmptext = "";
for (int l = 0; l < lis.Count; l++)
{
tmptext +=BinaryToString( lis[l]);
}
lb_output.Items.Add(tmptext);
}