Reputation: 23
I'm making a simple obfuscator in c# forms and I'm using this code to insert it:
string a = RandomString(8);
string b = RandomString(8);
string c = RandomString(8);
string d = RandomString(8);
etc...
Code.Text = Code.Text.Insert(0, "set " + a + "=a\n" + "set " + b + "=b\n" + "set " + c + "=c\n" + "set " + d + "=d\n" etc...);
This is the output:
set pbatbpkz=a
set aqtwbqlg=b
set hitsvkvc=c
set imuwqdfy=d
etc...
I need to keep the random strings separate so that I can later insert code to replace characters like "a" with string a.
This obviously does not look efficient or professional. I'm considerably new to c#, so I don't know how I could make something like an array to insert this block of text.
Here's the slightly better code:
Dictionary<char, string> strDict = new Dictionary<char, string>();
for (int i = 0; i < 26; i++)
{
if (!strDict.ContainsKey((char)(i + 97)))
{
strDict.Add((char)(i + 97), RandomString(8));
}
else
{
strDict[(char)(i + 97)] = RandomString(8);
}
}
string letterTable = "abcdefghijklmnopqrstuvwxyz";
StringBuilder obfuscationTable = new StringBuilder("");
foreach (char c in letterTable)
{
obfuscationTable.AppendLine("set " + c + "=" + strDict[c]);
}
Code.Text = Code.Text.Insert(0, obfuscationTable.ToString());
Upvotes: 1
Views: 73
Reputation: 1
You could use a dictionary that maps these characters to random strings.
Dictionary<string, string> RandomStringDictionary = new Dictionary<string, string>();
RandomStringDictionary.Add("a", RandomString(8));
...
RandomStringDictionary.Add("z", RandomString(8));
Then iterate over your text, and for each character do
RandomStringDictionary[CurrentCharacter]
Upvotes: 0
Reputation: 111
One way to do this is to use a Dictionary.
Dictionary<char, string> strDict = new Dictionary<char, string>();
for (int i = 0; i < 26; i++)
{
if(!strDict.ContainsKey((char)(i+97)))
{
strDict.Add((char)(i + 97), RandomString());
}
else
{
strDict[(char)(i + 97)] = RandomString();
}
}
This will fill your strDict with random strings that can be accessed with characters from 'a' to 'z' Then you get these strings by:
string strA = strDict['a'] //and so on
Upvotes: 2
Reputation: 34309
I think the structure you are looking for is a Dictionary<char, string>
Naively you would use it like this:
var charLookup = new Dictionary<char, string>{
{'a', RandomString(8)},
...
{'z', RandomString(8)},
};
Code.Text = Code.Text.Insert(0, "set " + charLookup['a'] + "=a\n" ....
There are many ways to write this in less code. I would recommend using a loop to populate your dictionary, and linq to generate your string.
You should be able to do this in 3 lines of code.
Alternately use a seeded random number generator to do this in one line.
Upvotes: 0