Friday, September 28, 2012

Password Generator

Today I want to present a "Password Generator" written in C#. Maybe the name is a bit wrong, it is about creating all possible passwords of a given length, so that they can for example be used for brute-force attacks.

The generator is capsuled in a class, when creating an instance of it a new thread is started, which generates the passwords and writes them to a queue. This can then be checked from the outside, so that the creating and asking of possible passwords can be done in parallel.
The creation of passwords happens in the function FillQueue(). Here an iteration counts from the given minimal length to the maximal length of a password and by recursion for every of these characters the function SetLetter() is called.
It goes over all possible characters (in the program can be set, that the characters A-Z, a-z and 0-9 are used), sets the current position to the current character and calls the function with the next position. If the last position is reached, the current password is written to the queue.
With the public function Dequeue() the lowest element of the queue is taken out and returned, that way the created passwords can be collected.

The code:
public class PasswordGenerator
        Queue<string> Results; // queue with created passwords

        bool UpperAZ; // true if capital letters should be used
        bool LowerAZ; // true if lower case letters should be used
        bool Numbers; // true if numbers should be used

        int Min; // min. length of the password
        int Max; // max. length of the password

        const int MaxQueueSize = 30000000; // maximal number of passwords, which can be in the queue simultaneously (protection of memory overflow)

        public PasswordGenerator(bool upperAZ, bool lowerAZ, bool numbers, int min, int max)
            UpperAZ = upperAZ;
            LowerAZ = lowerAZ;
            Numbers = numbers;

            Min = min;
            Max = max;
            Results = new Queue<string>();

            // create new thread for password generation
            Thread Creator = new Thread(new ThreadStart(FillQueue));

        private void FillQueue()
            // fill queue
            for (int i = Min; i <= Max; i++)
                SetLetter(i, 0, "");

        private void SetLetter(int length, int pos, string temp)
            // fill current position with all possible characters
            if (UpperAZ)
                for (int i = 65; i <= 90; i++)
                    NextStep(length, pos, temp + (char)i);
            if (LowerAZ)
                for (int i = 97; i <= 122; i++)
                    NextStep(length, pos, temp + (char)i);
            if (Numbers)
                for (int i = 0; i <= 9; i++)
                    NextStep(length, pos, temp + i.ToString());

        private void NextStep(int length, int pos, string temp)
           // function to finalize a step

           // if the queue is "full", the step is paused
           while (Results.Count > MaxQueueSize)

            // if not yet the last position is reached, call function with next position
            if (pos < length - 1)
                SetLetter(length, pos + 1, temp);
                // otherwise add complete password to the queue

        public string Dequeue()
            // returns the lowest element of the queue
            if (Results.Count > 0)
                return Results.Dequeue();
                return "";

The initialization of the generator then can be done e.g. via
PasswordGenerator Generator = new PasswordGenerator(true, true, true, 1, 4);
The asking for passwords via

Tuesday, September 25, 2012

Check Password of a Word Document Automatically

After I explained the basics about including Microsoft Word in the previous post, I today want to put special attention to the opening of password protected documents.
With the following code it can be checked, whether a password is the right one to open a document. By iteration then for example can be automatically searched for a password:

            Object oMissing = System.Reflection.Missing.Value;

            Word.Application WordApp = new Word.Application();

                Word.Document ExistingDocument = WordApp.Documents.Open("Filename", oMissing, false, oMissing, "Password");
                MessageBox.Show("Correct Password");
            catch (System.Runtime.InteropServices.COMException ex)
                MessageBox.Show("Wrong Password");

Friday, September 21, 2012

Word Tutorial

In this post I want to show, how to connect C# and Microsoft Office Word. I will show, how to create new Word documents using C#, insert texts, change settings, open documents, save and display them.
First we have to add the corresponding component to our project, which can be done via Project - Add Reference - COM - Microsoft Word xx Object Library. xx in that means the current version number.
Then we use the code using Word = Microsoft.Office.Interop.Word to be able to use the Word object under the name Word.

Create Word Instance and Show It:
Word.Application WordApp = new Word.Application();
WordApp.Visible = true;
With that a new instance of the Word object is created. With enabling the visibility, this is shown. Since no documents are loaded yet, simply the grey Word window is shown.

Create New Word Document:
The propety Documents of the instance contains opened documents, we can add documents to this enumeration e.g. by opening or creating new ones. To create a new document, the following command is needed:
Word.Document NewDocument = WordApp.Documents.Add();

Close Document:
For this the function Close() is responsible, which is called from the corresponding document, so with above example:

Open Existing Word Document:
Object oMissing = System.Reflection.Missing.Value;
Word.Document ExistingDocument = WordApp.Documents.Open("Filename", oMissing, true, oMissing, "Password");
All arguments except the first one are optional. The 3. says, whether the document is to be opened read-only (true if yes). The 5. is the optional password.
The argument oMissing with the value System.Reflection.Missing.Value is very practical, it always returns the default value of the current argument and therefore can always be used as a placeholder for unused arguments.

Insert Text:
WordApp.Selection.TypeText("Hallo Welt");
This code types the given text in the currently top most opened document in the Documents enumeration.

Set Formattings:
Also with the Selection property formattings can be taken. If these are done before a TypeText command, they are applied to the written text. All known formattings are available, as for example:
WordApp.Selection.Font.Size = 20;

Save Document:
A document can either be saved with the parameterless function Save() or SaveAs2(). The last version expects a save path.

Quit Word Instance:

Wednesday, September 19, 2012

Create System Restore Point

In today's post I want to show, how to create a system restore point using C#.
Therefor we use management classes, which connects with the Windows Management Instrumentation (WMI) and over this way reads information about the computer.
To run the project, via Project - Add Reference System.Management has to be included, furthermore this via using. The application also needs to run with administratrative rights.
Central point is an instance of the class ManagementClass.
Its constructor expects 3 parameters:
First a scope, which is here set to the local computer, then a path, which defines the operation to be executed (here: create a restore point) and lastly a class with options, for that we hand over the default options of a WMI call.
From the created instance the function GetMethodParameters() with the parameter "CreateRestorePoint" is called. This tells the application, to load the parameters of the WMI function "CreateRestorePo", so that these can be filled then. CreateRestorePoint expects 3 parameters:
  • Description: Description of the restore point
  • RestorePointType: Type of the restore point. Detailed information about the possible options can for example be found on this site. Here we hand over 0, which means, that an application was installed. A 10 would for example mean, that a driver was installed. 
  • EventType: Type of the event. We here hand over 100, which indicates, that a change has begun in the system. 101 would mean, that the change was done.
Finally we execute the action caling InvokeMethod and thus create a system restore point.
The code:

                // select local computer
                ManagementScope ManScope = new ManagementScope(@"\\localhost\root\default");
                // create system restore point
                ManagementPath ManPath = new ManagementPath("SystemRestore");
                // select default options
                ObjectGetOptions ManOptions = new ObjectGetOptions();
                // create management class with previous options
                ManagementClass ManClass = new ManagementClass(ManScope, ManPath, ManOptions);
                // load function parameters
                ManagementBaseObject ManBaseObject = ManClass.GetMethodParameters("CreateRestorePoint");
                // description
                ManBaseObject["Description"] = "Mein C# Wiederherstellungspunkt";
                // type of the restore point
                ManBaseObject["RestorePointType"] = 0;
                // ype of the event
                ManBaseObject["EventType"] = 100;

                ManagementBaseObject OutParam = ManClass.InvokeMethod("CreateRestorePoint", ManBaseObject, null);

Wednesday, September 12, 2012

Check If Current User Has Specific Role (e.g. Administrator)

An easy solution of checking whether the current user has specific roles (as administrator or guest), is the following (the example checks, whether the user is guest):

WindowsIdentity CurrentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal CurrentPrincipal = new WindowsPrincipal(CurrentIdentity);
bool UserIsAdmin = CurrentPrincipal.IsInRole(WindowsBuiltInRole.Guest);

From Windows Vista on though we get a problem, if the to be tested role is administrator. Although the user running the program might be administrator, the application is at first hand run without administrative rights, so that wrongly false is returned. Only when explicitely running the application as administrator true is returned, of course also then, if the user is no administrator.

I did not find an (easy) solution solving this problem, maybe some good advices come from you?

Sunday, September 9, 2012

Calculate MD5 Hash of a File

In the previous post I explained basics about hashing and hashing of strings, I will start from there on. For that reason I just publish the code which calculates the hash sum of a complete file:

MD5 Md5Hash = MD5.Create();
System.IO.FileStream HashStream = new System.IO.FileStream(@"C:\Users\User\Documents\c#.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] Data = Md5Hash.ComputeHash(HashStream);
string Hash =  System.BitConverter.ToString(Data);

Thursday, September 6, 2012

Calculate MD5 Hash of a String

In today's post I want to present, how to calculate the MD5 hash of a string using C#.
First a little basics about hashing in general:
A hash function is a function, which creates from a input of arbitrary length an output of fixed length. The function should one the one hand be not or hardly invertible, meaning given the output, calculating the corresponding input needs to be hard.
On the other hand the function should create only a few collisions, meaning, different inputs should create different outputs, furthermore little changes to the input should create big changes in the output.

Why all that?
One example is the storage of passwords on a webserver. The passwords are not saved in plain text but hashed. So on the one hand the administrator cannot see the passwords of his clients, since he cannot inverse the hash value, and on the other hand of course intruders cannot do so also.
Another example is the hash sum calculation of files, for example to verify the correct transfer. Comparing the 2 files in total would need too many ressources, so you compare the hash sums. Are these equivalent, the files are identical with a high probablity since there are little hash collisions, if already a small part of the file is different, the hash value is probably totally different.

Now to the code. With using System.Security.Cryptography the following code calculates the hash value of a string:

MD5 Md5Hash = MD5.Create();
byte[] Data = Md5Hash.ComputeHash(Encoding.Default.GetBytes("Zu hashende Zeichenkette"));
string Hash =  System.BitConverter.ToString(Data);

The first line creates a MD5 object. In the second line the string is hashed with MD5 and the hash is returned as a byte array. The function ToString() in the third line of the BitConverter then converts this array to a hexadecimal string, which is mostly used to represent hash values.

Monday, September 3, 2012

Start Program Automatically on Windows Startup

In this post I want to show, how to add a C# program to the autostart of Windows.
For this there are 2 possibilites: One the one hand, we can add a shortcut to the program in the startup folder, on the other hand we can create an entry in the registry.

1. Method: Create Shortcut
How to create a shortcut in general, I described in that post. We now have to set our program as link target and as path the startup folder of Windows, which is located under Windows 7 in C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup. The path to our own application we get by Application.ExecutablePath.ToString() - so the following code copies the program to the startup folder (as icon we can set an icon):
CreateShortcut(@"C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" + "\\CAutoStart.url",  Application.ExecutablePath.ToString(), "C:\\MeinIcon.ico");

2. Method: Create Registry Entry
The analogon to above path is located in the registry under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run. How to use the registry in general with C#, is described in this tutorial. Here I just show the complete code, which creates the needed entry so that the application starts automatically when Windows starts:
RegistryKey AutostartKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
AutostartKey.SetValue("CAutoStart", Application.ExecutablePath.ToString());