RC4 cypher in C#
Main method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public static string RC4(string input, string key) { StringBuilder result = new StringBuilder(); int x, y, j = 0; int[] box = new int[256]; for (int i = 0; i < 256; i++) { box[i] = i; } for (int i = 0; i < 256; i++) { j = (key[i % key.Length] + box[i] + j) % 256; x = box[i]; box[i] = box[j]; box[j] = x; } for (int i = 0; i < input.Length; i++) { y = i % 256; j = (box[y] + j) % 256; x = box[y]; box[y] = box[j]; box[j] = x; result.Append((char)(input[i] ^ box[(box[y] + box[j]) % 256])); } return result.ToString(); } |
Usage:
1 2 3 4 5 | // Results to º§(ÓM¦Kéµ(äþ« string cypheredText = RC4("fluxbytes.com", "mykey"); // Results to fluxbytes.com string deCypheredText = RC4(cypheredText, "mykey"); |
Line “y = i % 256;” is incorrect based on RC4 examples. Should be “y = i + 1 % 256;” could we review this?
So, I really like your code because it is short and simple. Less is usually better. I am trying to use it to encrypt SQLAzure login info. All works fine. But when passing the encrypted field to a db using SQL, the apostrophe (char)(39) kills the SQL string (SQL requires a double apostrophe if used in a string).
I’ve been able to cobble a crude fix that identifies the apostrophe and replaces it with another character, but this will not decrypt correctly.
int w;
w = (input[i] ^ box[(box[y] + box[j]) % 256]);
string w1 = “append: ” + w;
{
if (w1 != “append: 39”)
result.Append((char)(input[i] ^ box[(box[y] + box[j]) % 256]));
}
{
if (w1 == “append: 39”)
result.Append((char)(32));
}
Do you have a means of eliminating the apostrophe character in the random sequence?
Thanks in advance.
Hello Dana,
Have you tried replacing apostrophe (‘) with double apostrophe (”) before inserting the string in your database ?
yes- using the replacement code that I sent previously. This works well for the encryption and send sql string steps, but then when I try to decrypt the changed encrypted string, the double apostrophe is interpreted differently from the original single apostrophe and so I do not get the original unencrypted string back.
You are altering the algorithm on the example you are mentioning above.
What I suggesting was to replace the final result of the method before putting it in the database, as a method of escaping the apostrophes. That means that goes into your database is exactly the same output the method returns since ” will be replaced with ‘ when inserting.