2

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?

Community
  • 1
  • 1
Flak714
  • 59
  • 3
  • 9
  • You can write `(int)key[keyIndex] - 'A'`. – usr Nov 25 '12 at 16:31
  • the key is needed to be trimmed in order to get rid from the white spaces in the beginning and at the end. you don't have to use vigenere just with letters, you could use any symbol. – elyashiv Nov 25 '12 at 16:32

1 Answers1

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());
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • Looking further into this I'm not a bit confused into why it is modulated by 256 rather than 127 as C# doesn't seem to use extended ASCII? – Flak714 Dec 06 '12 at 11:48
  • ASCII data still occupies 8 bits, even if only 7 of them are used - so the 256 is safe - however you are right it does not take into account this "overflow" situation. By the way, C# uses Unicode for `string`s and `char`s; the `result` variable is a byte array (without encoding) of 8 bits each. – C.Evenhuis Dec 06 '12 at 12:16