I have used my own scramble/unscramble methods in the past that did it another way but recently discovered some string just don't scramble I did not use swapping but a form of encoding.
I found this thread and have taken the last provided solution and made it more useable by encoding the seed into the scrambled string so the seed is not required to decode.
This allows a scrambled string to be used in a database to obfuscate it from easy reading.
Unless you know where the seed is imbedded in the string (currently the last chars but you could make it any part of the string if needed)
/// <summary>
/// Mix up a string (re-order character positions) using a random number set based from a seed value
/// </summary>
/// <param name="StringToScramble"></param>
/// <returns>Scrambled String with seed encoded</returns>
public static string RandomizeString(string StringToScramble)
{
int seed = RandomNumber(0, 250); // Get a random number (will be encoded into string , this will be the seed
Random r = new Random(seed);
char[] chars = StringToScramble.ToArray();
for (int i = 0; i < StringToScramble.Length; i++)
{
int randomIndex = r.Next(0, StringToScramble.Length); // Get the next random number from the sequence
Debug.Print(randomIndex.ToString());
char temp = chars[randomIndex]; // Copy the character value
// Swap them around
chars[randomIndex] = chars[i];
chars[i] = temp;
}
// Add the seed
return new string(chars) + seed.ToString("X").PadLeft(2, '0');
}
/// <summary>Unscramble a string that was previously scrambled </summary>
/// <param name="ScrambledString">String to Unscramble</param>
/// /// <returns>Unscrambled String</returns>
public static string UnRandomizeString(string ScrambledString)
{
try
{
// Get the last character from the string as this is the random number seed
int seed = int.Parse(ScrambledString.Substring(ScrambledString.Length - 2), System.Globalization.NumberStyles.HexNumber);
Random r = new Random(seed);
char[] scramChars = ScrambledString.Substring(0, ScrambledString.Length - 2).ToArray();
List<int> swaps = new List<int>();
for (int i = 0; i < scramChars.Length ; i++)
{
int randomIndex = r.Next(0, scramChars.Length );
swaps.Add(randomIndex);
}
for (int i = scramChars.Length - 1; i >= 0; i--)
{
char temp = scramChars[swaps[i]];
scramChars[swaps[i]] = scramChars[i];
scramChars[i] = temp;
}
return new string(scramChars);
}
catch (System.Exception ex)
{
return "";
}
}