我遇到了这段代码:
Byte Vigenere Cipher, error with decryption
但为了遵守规则,我提出了一个新问题。
使用了以下算法,我试图更好地理解它:
Byte[] result= new Byte[plaintext.Length];
key = key.Trim().ToUpper();
int keyIndex = 0;
int keylength = key.Length;
for (int i = 0; i < plaintext.Length; i++)
{
keyIndex = keyIndex % keylength;
int shift = (int)key[keyIndex] - 65;
result[i] = (byte)(((int)plaintext[i] + shift) % 256);
keyIndex++;
}
我认为 key 需要像在 Unicode 中那样被修剪是正确的吗?因此从大写字母中减去 65 会产生一个普通字符/符号?
最佳答案
大写 A 的 ASCII 值为 65。key
中的所有字符都转换为大写,这将简单地返回 key
中每个字母的字母索引。
key
中的每个字母都以这种方式转换为数字,原始字符串中的每个字母都“按字母表向上移动”了相应的位置数。
如果您的 key 是 BAD
,这将变成数字 1、0 和 3,然后应用于“hello world”,如下所示:
Hello world
10310310310 <-- added to each character
Ieomo#xoumd
您可以通过在您的下方添加以下代码来证明这一点:
StringBuilder demonstration = new StringBuilder();
foreach (byte b in result)
{
demonstration.Append((char)b);
}
Console.WriteLine(demonstration.ToString());
关于c# - C#解释中的Vigenere算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552959/