我已经编写了一个关于单字母密码的程序,我的代码运行非常适合加密,但是当我进行解密时它会给我错误的值。 这是我的代码
using System;
class SubstitutionCipher
{
static void Main()
{
string key = "zyxwvutsrqponmlkjihgfedcba";
string plainText = "the quick brown fox jumps over the lazy dog";
string cipherText = Encrypt(plainText, key);
string decryptedText = Decrypt(cipherText, key);
Console.WriteLine("Plain : {0}", plainText);
Console.WriteLine("Encrypted : {0}", cipherText);
Console.WriteLine("Decrypted : {0}", decryptedText);
Console.ReadKey();
}
static string Encrypt(string plainText, string key)
{
char[] chars = new char[plainText.Length];
for (int i = 0; i < plainText.Length; i++)
{
if (plainText[i] == ' ')
{
chars[i] = ' ';
}
else
{
int j = plainText[i] - 97;
chars[i] = key[j];
}
}
return new string(chars);
}
public string reverse(string cipherText)
{
char[] charArray = cipherText.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Decrypt(string cipherText, string key)
{
char[] chars = new char[cipherText.Length];
for (int i = 0; i < cipherText.Length; i++)
{
if (cipherText[i] == ' ')
{
chars[i] = ' ';
}
else
{
int j = key.IndexOf(cipherText[i]) - 97;
chars[i] = (char)j;
}
}
return new string(chars);
}
}
如果key = zyxwvutsrqponmlkjihgfedcba
输出:
平原:快速的棕色狐狸跳过懒狗
加密:wyo xevks flnqa tnu hecdr nbol wyo pjzi gnm
解密:> p>其解密无法正常工作
答案 0 :(得分:0)
替换Decrypt函数中的行:
int j = key.IndexOf(cipherText[i]) - 97;
带
int j= key.IndexOf(cipherText[i]) + 97;