Game Development Community

Need help with implementing Vigenere cipher into TorqueScript

by Ryan Froese · in Torque Developer Network · 09/06/2011 (6:43 pm) · 1 replies

Hey, i'm trying to make a plaintext encryptor/cipher, but it isnt working out so well. The exact one im trying to make is a Vigenere cipher, which perfectly suits my needs. Here's my code so far, but right now, it just returns whatever you put in as the input, but I have no idea how to fix this:

function Vigenere(%input, %key, %forward)
{
	%alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	%key = strUpr(%key);
	%key_len = strLen(%key);
	for (%i = 0; %i < %key_len; %i++)
	{
		%key_char = strpos(%alphabet, getSubStr(%key, %i, 1));
		if (%key_char < 0)
			continue;
		%adjusted_key = %adjusted_key @ getSubStr(%alphabet, %key_char, 1);
	}
	%key = %adjusted_key;
	%key_len = strLen(%key);
	if (%key_len == 0)
	{
		echo("no key");
		%key = "a";
		%key_len = 1;
	}

	// Transform input:
	%input_len = strLen(%input);
	%output = "";
	%key_index = 0;
	%in_tag = false;
	for (%i = 0; %i < %input_len; %i++)
	{
		%input_char = getSubStr(%input, %i, 1);
		if(%input_char == "<")
			%in_tag = true;
		else if(%input_char == ">")
			%in_tag = false;
		if(%in_tag)
		{
			%output = %output @ %input_char;
			continue;
		}
		%input_char_value = strpos(%alphabet, %input_char);
		if (%input_char_value < 0)
		{
			%output = %output @ %input_char;
			continue;
		}
		%lowercase = %input_char_value >= 26 ? true : false;
		if (%forward)
			%input_char_value += strpos(%alphabet, getSubStr(%key, %key_index, 1));
		else
			%input_char_value -= strpos(%alphabet, getSubStr(%key, %key_index, 1));
		%input_char_value += 26;
		if (%lowercase)
			%input_char_value = %input_char_value % 26 + 26;
		else
			%input_char_value %= 26;
		%output = %output @ getSubStr(%alphabet, %input_char_value, 1);
		%key_index = (%key_index + 1) % key_len;
	}
	return %output;
}

About the author

Hi, I'm Ryan. I'm 14 years old and im a junior programmer in TorqueScript and C# on my free time. I currently have about as much knowledge of TorqueScript as the average university grad does about C.


#1
09/07/2011 (1:46 am)
Here's a tip, when posting code for others to read, use the code /code tags to format things into something readable.

There are a couple of little errors in there that are stopping it working. Firstly,
if(%input_char == "<")
   %in_tag = true;
else if(%input_char == ">")
   %in_tag = false;

needs to be changed to use the $= comparison operator instead of == as you are comparing strings and not numbers. So that becomes:
if(%input_char $= "<")
   %in_tag = true;
else if(%input_char $= ">")
   %in_tag = false;


then, almost at the end of the function, you've left the % off the key_len variable name:
%key_index = (%key_index + 1) % key_len;
should be
%key_index = (%key_index + 1) % %key_len;