我有一个代码,如果我将输入数据传递为" sail"我的代码将生成一个屏蔽输出,例如" aisl"或者" isal"。输出将是混乱的输入格式。我想要一个输出,不应该在输入中生成具有相同完全字母的输出。这是我当前的代码,请帮助我这个
string InputData = "123456";
string MaskedData = InputData;
if (MaskedData.Length > 0)
{
// The technique used to mask the data is to replace numbers with random numbers and letters with letters
//char[] chars = new char[InputData.Length];
char[] chars = new char[InputData.Length];
Random rand = new Random(DateTime.Now.Millisecond);
int index = 0;
while (InputData.Length > 0)
{
// Get a random number between 0 and the length of the word.
int next = rand.Next(0, InputData.Length - 1);
// Take the character from the random position and add to our char array.
//chars[index] = InputData[next];
chars[index] = InputData[next];
// Remove the character from the word.
InputData = InputData.Substring(0, next) + InputData.Substring(next + 1);
++index;
}
MaskedData = new String(chars);
}
答案 0 :(得分:1)
In this page in dotnetperls.com有一种算法随机化一串字符串。通过一些更改,您可以使用它来随机化字符串,使用字符串也是字符数组的事实。你有:
static class RandomCharArrayTool
{
static Random _random = new Random();
public static string RandomizeChars(string theString)
{
var arr = theString.ToCharArray();
List<KeyValuePair<int, char>> list = new List<KeyValuePair<int, char>>();
// Add all strings from array
// Add new random int each time
foreach (char s in arr)
{
list.Add(new KeyValuePair<int, char>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array
char[] result = new char[arr.Length];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, char> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return string generated from copied array
return new string(result);
}
}
你这样使用它:
RandomCharArrayTool.RandomizeChars("sail");
答案 1 :(得分:1)
请尝试使用以下代码段。
Mehtod 1:
string word = "123456";
string temp = word;
string result = string.Empty;
Random rand = new Random();
for (int a = 0; a < word.Length; a++)
{
//multiplied by a number to get a better result, it was less likely for the last index to be picked
int temp1 = rand.Next(0, (temp.Length - 1) * 3);
result += temp[temp1 % temp.Length];
temp = temp.Remove(temp1 % temp.Length, 1);
}
string str = result;
<强>方法2:强>
var rnd = new Random();
string InputData = "123456";
string MaskedData = new string(InputData.OrderBy(r => rnd.Next()).ToArray());
答案 2 :(得分:0)
您有几种不同的方法,但最简单的方法可能是实施SecureString
或Hash
。其中一个可以很容易地加密您的数据。根据这一概念,mask
将隐藏所述内容。
// SecureString
var secure = new SecureString();
foreach(var character in textbox.Text.ToCharArray())
secure.AppendChar(character);
将string
放入内存后,它将在内存中加密。这是一个粗略的实现,但文档将帮助您改进满足您需求的方法。
// Hash (BCrypt for simplicity)
private const int factor = 12;
var hashed = BCrypter.HashPassword(textbox.Text, BCrypter.GenerateSalt(factor));
另一种方法只是随机化,类似于单词shuffle。像其他答案一样。