title: How to encrypt jpeg file correctly using xor operation
body: <p>I have a problem with encrypting JPEG file using xor operation.
  Here is how I am decoding the file:</p>
  
  <pre><code>        Stream imageStreamSource = new FileStream(filename, FileMode.Open,   FileAccess.Read, FileShare.Read);
          JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
          BitmapSource bitmapSource = decoder.Frames[0];
  
          return bitmapSource; 
  </code></pre>
  
  <p>Here is how I am encoding and encrypting it(bs is decoded BitmapSource):</p>
  
  <pre><code>        int stride = bs.PixelWidth * 3;
          int size = bs.PixelHeight * stride;
          byte[] pixels = new byte[size];
          bs.CopyPixels(pixels, stride, 0);
  
          pixels = xoring(pixels, size);
  
          int width = bs.PixelWidth;
          int height = bs.PixelHeight;
  
          BitmapSource image = BitmapSource.Create(
              width,
              height,
              bs.DpiX,
              bs.DpiY,
              bs.Format,
              bs.Palette,
              pixels,
              stride);
  
          FileStream stream = new FileStream(outName, FileMode.Create);
          JpegBitmapEncoder encoder = new JpegBitmapEncoder();
          TextBlock myTextBlock = new TextBlock();
          myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
          encoder.FlipHorizontal = false;
          encoder.FlipVertical = false;
          encoder.QualityLevel = 100;
          encoder.Rotation = Rotation.Rotate0;
          encoder.Frames.Add(BitmapFrame.Create(image));
          encoder.Save(stream);
  </code></pre>
  
  <p>This is xoring function:</p>
  
  <pre><code>    public byte[] xoring(byte[] data, int size)
      {
          const string key = "abc";
          for (int i = 0; i &lt; size; i++)
              data[i] = (byte)(data[i] ^ (byte)key[i % key.Length]);
          return data;
      }
  </code></pre>
  
  <p>I am expecting the image to be completly noise, but I am getting something like this:
  <a href="http://i.imgur.com/yNQqw8D.png" rel="nofollow">http://i.imgur.com/yNQqw8D.png</a></p>
  
  <p>This the original file:
  <a href="http://i.imgur.com/PILmdGL.png" rel="nofollow">http://i.imgur.com/PILmdGL.png</a></p>
  
  <p>I would appreciate any help! It seems like if only one color channel was encrypted...</p>