C # exception error

0

Hello, I have made a small program that basically encrypts any file the code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;

namespace Crypter
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //No Arguments -> Exit
            if (args.Length < 2)
            {
                Console.WriteLine("Syntax: crypter.exe <Exe/Dll to get Encrypted> <Password> (Optional: output file name)");
                Environment.Exit(0);
            }

            String file = args[0];
            String pass = args[1];
            String outFile = "Crypted.exe";

            //If Output Name is specified -> Set it
            if (args.Length == 3)
            {
                outFile = args[2];
            }

            //File doesn't exist -> Exit
            if (!File.Exists(file))
            {
                Console.WriteLine("[!] The selected File doesn't exist!");
                Environment.Exit(0);
            }

            //Everything seems fine -> Reading bytes
            Console.WriteLine("[*] Reading Data...");
            byte[] plainBytes = File.ReadAllBytes(file);

            //Yep, got bytes -> Encoding
            Console.WriteLine("[*] Encoding Data...");
            byte[] encodedBytes = encodeBytes(plainBytes, pass);

            Console.Write("[*] Save to Output File... ");
            File.WriteAllBytes(outFile, encodedBytes);
            Console.WriteLine("Done!");

            Console.WriteLine("\n[*] File successfully encoded!");
        }
        private static byte[] encodeBytes(byte[] bytes, String pass)
        {
        byte[] XorBytes = Encoding.Unicode.GetBytes(pass);

        for (int i = 0; i < bytes.Length; i++)
        {
            bytes[i] ^= XorBytes[i % 16];
        }

        return bytes;
        }
    }
}

When I insert the fichero.txt it returns me:

My question is why this exception should be. And second part of the code is the cause because I have not found the solution so far.

The error that returns to me is:

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bou
ds of the array.
   at Crypter.Program.encodeBytes(Byte[] bytes, String pass)
   at Crypter.Program.Main(String[] args)
    
asked by jeronimo urtado 29.03.2017 в 23:57
source

1 answer

3

The error (I consider) of the reading of the code occurs in encodeBytes

<!-- languaje: c# -->
byte[] XorBytes = Encoding.Unicode.GetBytes(pass);

For the case used it has no more than 4 characters: Crypter.exe a.txt 1234 o.txt

in the for tu:

<!-- languaje: c# -->
bytes[i] ^= XorBytes[i % 16];

must be

<!-- languaje: c# -->
bytes[i] ^= XorBytes[i % XorBytes.Length];
    
answered by 30.03.2017 / 00:17
source