My text
has 6 letters, my key
has 4 letters. After XOR I get newText
with only 4 letters. How can I make my key
longer (repeat it till text length?
我的文字有6个字母,我的密钥有4个字母。异或后我得到只有4个字母的newText。如何让我的钥匙更长(重复直到文字长度?
for ex.: string text = "flower"
,string key = "hell"
I want to make my string key = "hellhe" and so on...)
例如:string text =“flower”,string key =“hell”我想让我的字符串键=“hellhe”等等...)
private string XorText(string text,string key)
{
string newText = "";
for (int i = 0; i < key.Length; i++)
{
int charValue = Convert.ToInt32(text[i]);
int keyValue = Convert.ToInt32(key[i]);
charValue ^= keyValue % 33;
newText += char.ConvertFromUtf32(charValue);
}
return newText;
}
2 个解决方案
#1
Use the remainder operator (%):
使用余数运算符(%):
private string XorText(string text,string key)
{
string newText = "";
for (int i = 0; i < text.Length; i++)
{
int charValue = Convert.ToInt32(text[i]);
int keyValue = Convert.ToInt32(key[i % key.Length]);
charValue ^= keyValue % 33;
newText += char.ConvertFromUtf32(charValue);
}
return newText;
}
#2
Use StringBuilder
for string operations.
使用StringBuilder进行字符串操作。
private string XorText(string text, string key)
{
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text");
if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
StringBuilder sb = new StringBuilder();
int textLength = text.Length;
int keyLength = key.Length;
for (int i = 0; i < textLength; i++)
{
sb.Append((char)(text[i] ^ key[i % keyLength]));
}
return sb.ToString();
}
#1
Use the remainder operator (%):
使用余数运算符(%):
private string XorText(string text,string key)
{
string newText = "";
for (int i = 0; i < text.Length; i++)
{
int charValue = Convert.ToInt32(text[i]);
int keyValue = Convert.ToInt32(key[i % key.Length]);
charValue ^= keyValue % 33;
newText += char.ConvertFromUtf32(charValue);
}
return newText;
}
#2
Use StringBuilder
for string operations.
使用StringBuilder进行字符串操作。
private string XorText(string text, string key)
{
if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text");
if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
StringBuilder sb = new StringBuilder();
int textLength = text.Length;
int keyLength = key.Length;
for (int i = 0; i < textLength; i++)
{
sb.Append((char)(text[i] ^ key[i % keyLength]));
}
return sb.ToString();
}