问题
I came across this code:
Byte Vigenere Cipher, error with decryption
But trying to follow the rules I made a new question about it.
The following algorithm is used and I'm trying to get a better understanding into it:
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++;
}
Am I right in thinking the key needs to be trimmed as it is in Unicode? therefore subtracting 65 from a capital produces a common character/symbol?
回答1:
The ASCII value for the capital A is 65. All characters in key
are converted to uppercase, this would simply return the alphabetical index of each letter in key
.
Each letter in key
is converted to a number that way, and each letter in the original string is "shifted up the alphabet" that number of positions.
If your key was BAD
, this would turn into the numbers 1, 0 and 3, then applied to "hello world" as follows:
Hello world
10310310310 <-- added to each character
Ieomo#xoumd
You can demonstrate this by adding this code below yours:
StringBuilder demonstration = new StringBuilder();
foreach (byte b in result)
{
demonstration.Append((char)b);
}
Console.WriteLine(demonstration.ToString());
来源:https://stackoverflow.com/questions/13552959/the-vigenere-algorithm-in-c-sharp-explanation