1

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?

for ex.: string text = "flower",string key = "hell" I want to make my string key = "hellhe" and so on...)

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;
        }
1
  • 1
    Instead of key[i] use key[i%key.Length] and change your for loop to use i < text.Length. Look up "modulus" to see how this works. Commented May 12, 2015 at 13:04

2 Answers 2

3

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;
  }
Sign up to request clarification or add additional context in comments.

Comments

0

Use StringBuilder for string operations.

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.