Google

Tuesday, January 22, 2008

Two Rotation Cypher Algorithm


This is a simple encryption algorithm for strings containing only lowercase letters and spaces. You start by splitting the alphabet into two groups. The first group consists of the first firstSize letters of the alphabet, and the second consists of the remaining 26 - firstSize letters. To encrypt a character in your message, you do the following:

1. If it a space, it is kept as is.
2. If it is a letter in the first group, it is moved firstRotate letters forward in the group,
wrapping back to the start if necessary. For example, if firstSize is 6 and firstRotate is 2,
then 'A' would become 'C', and 'F' would become 'B'.
3. If it is a letter in the second group, then it is moved secondRotate letters forward in the
group, again wrapping back to the start of the group if necessary.

This is the C# implementation of the above algorithm I've developed.

public String encrypt(int firstSize, int firstRotate, int secondRotate, String originalMessage)
{
originalMessage = originalMessage.ToLower(); //converts original message to lowercase
string[] firstSet = new string[firstSize]; //splits the alphabet in to fist part
string[] secondSet = new string[26 - firstSize]; //splits the alphabet in to second part

for (int i = 0; i < c =" (char)(97" i =" 0;" c =" (char)(97" i =" 0;" character =" originalMessage[i].ToString();">= 0) //character is in the first part.
{
int index1 = Array.IndexOf(firstSet, character);
int index2 = Array.IndexOf(firstSet, character);

index1 = index1 + firstRotate;

if (index1 > (firstSize - 1))
{
index1 = firstRotate - (firstSize - index2);
}

string str = firstSet[index1];
originalMessage = originalMessage.Remove(i, 1);
originalMessage = originalMessage.Insert(i, str);
}

else if (Array.IndexOf(secondSet, character) >= 0) //character is in the second part.
{
int index1 = Array.IndexOf(secondSet, character);
int index2 = Array.IndexOf(secondSet, character);

index1 = index1 + secondRotate;
if (index1 > (25 - firstSize))
{
index1 = secondRotate - (26 - firstSize - index2);
}

string str = secondSet[index1];
originalMessage = originalMessage.Remove(i, 1);
originalMessage = originalMessage.Insert(i, str);
}
}

return originalMessage; //returns the encrypted message.
}


sample outputs :

encrypt(13, 0, 0, "this string will not change at all") returns "this string will not change at all"

encrypt(13, 7, 0, "only the letters a to m in this string change") returns "onfy tbl flttlrs h to g cn tbcs strcna jbhnal"

encrypt(17, 9, 5, "the quick brown fox jumped over the lazy dog") returns "yqn izalc kwgsf ogt bzehnm grnw yqn djvu mgp"

0 Comments:

Post a Comment

<< Home