Password Evaluation Algorithm in C

Have you ever wondered, how websites and applications check if your password contains the required characters? They do it by using algorithms and in this post I’d like to show you an example I’ve written in C.

If you learn programming in C, you’ll quickly find out that you can accomplish pretty much anything with loops and if else statements. By combining these in themselves incredibly simple building blocks, you can construct just as incredibly complex and powerful algorithms. Algorithms are the pieces of code that do even the most fundamental tasks like sorting data, finding characters in a text and so on. In higher level programming languages like C#, Java, C++ and even in C itself, standard algorithms for common tasks are readily available in the form of classes or functions. In most cases, those algorithms are more than good enough. However, there are two main reasons for writing your own code. One is obviously to create customized and optimized solutions for custom problems not covered by ready-made code. The other reason is to learn and understand how algorithms work, which is a must have skill for any good programmer.

Checking whether a password meets minimum requirements, for example that it contains at least one number, upper-case letter and a special character, is a fundamental task for any website or application. There are no doubt many pre-written algorithms to accomplish this task, but writing your own piece of code that actually works is very rewarding. The code I produced might not be the smartest, shortest or prettiest in the world, but it does exactly what it is supposed to do. It loops through each character of a string and checks if at least one number, upper-case letter and a dollar sign has been included. If it is so, it drops a “Good password!” message, if not, it instructs the user to include the required characters. The app also makes sure that the password meets a minimum and maximum length requirement.

First let’s see the headers and libraries you need:

#include <stdio.h>  //standard input and output
#include <stdlib.h> //standard library
#include <ctype.h>  //includes isupper() and isdigit() functions for obvious purposes
#include <string.h> //includes the strlen() function to check password length
#define MIN 5       //minimum length
#define MAX 11      //maximum length

These are the necessary variables:

char pwd[MAX];     //array containing the password
int upper[MAX];    //array for keeping track of upper-case letters
int num[MAX];      //array for keeping track of numbers
int dollar[MAX];   //array for keeping track of dollar signs
int sumUpper = 0;  //sum of upper-case letters in password
int sumNum =0;     //sum of numbers in password
int sumDollar = 0; //sum of dollar signs in password
int i = 0;         //index for the loops

To make sure that memory locations allocated to the arrays don’t contain any unwanted data, it’s always a good idea to initialize or “clean up” the arrays in advance:

for (i = 0; i < MAX; i++) //initializing the arrays makes sure they
{                         //start with "clean" memory locations
    pwd[i] = 0;
    upper[i] = 0;
    num[i] = 0;
    dollar[i] = 0;
}

You can use an if else statement to make sure the password meets length requirements:

if (strlen(pwd) >= MIN && strlen(pwd) < MAX) //if password meets minimum and
{                                            //maximum length requirement
    algorithm
}
else //if password doesn't meet minimum and maximum length requirements
    printf("\nYour password has to be between 4 and 10 characters!\n");

If the password isn’t too short nor too long, the actual algorithm can run. A for loop runs through each character of the password until the \0 special character is reached. This character signifies the end of each string in C. That’s why you have to be careful with manipulating the individual characters of strings: if this “invisible”, special character gets overwritten, it can cause real problems. Whenever an upper-case letter, a number or a dollar sign is found, a 1 is written to the corresponding position of the upper, num and dollar arrays:

for (i = 0; pwd[i] != '\0'; i++) //for loop runs until it reaches the
{                                //special \0 end of string character
    if (isupper(pwd[i]))         //if a character is upper-case, a 1 is written to
        upper[i] = 1;            //the corresponding location of the upper array
    if (isdigit(pwd[i]))         //same applies when a number is found
        num[i] = 1;
    if (pwd[i] == '$')           //same applies when a dollar sign is found
        dollar[i] = 1;
}

In the next steps the digits at each position of the upper, num and dollar arrays are added up. Adding up zeros amounts to zero, but adding up ones accurately indicates how many of the required characters are included in the password:

for (i = 0; i < MAX; i++) //the digits in each position of the
{                         //upper, num and dollar arrays are added up
    sumUpper += upper[i];
}                         //adding up zeros amounts to zero, but adding up
                          //ones accurately indicates how many of the required
for (i = 0; i < MAX; i++) //characters are included in the password
{
    sumNum += num[i];
}

for (i = 0; i < MAX; i++)
{
    sumDollar += dollar[i];
}

If sumUpper, sumNum and sumDollar are greater than one, it means that at least one of each required character has been included in the password, resulting in a “Good password!” message:

if (sumUpper > 0 && sumNum > 0 && sumDollar > 0)
    printf("\nGood password!\n");

Since the occurrences are summed up, you can easily adjust the minimum number to demand more than one of those characters. By expanding the algorithm with more loops and variables accordingly, you can also demand any other character you want.

If even one of the requirements is unmet, the user is instructed to include the required characters:

else
    printf("\nYou have to include at least one number, upper-case letter and dollar sign!\n");

There may be more efficient ways to accomplish this task, but figuring out something like this yourself is an important step to understanding how programs actually do what they do. If you look at this code more carefully, you will realiese that even the algorithm I’ve written includes other algorithms. Isupper, isdigit and strlen are all algorithms included in the ctype.h and string.h libraries, written by someone else. I don’t know how about you, but I have an unquenchable desire to understand how this kind of stuff works, even if I wouldn’t need to write my own code. By the way, I use CodeBlocks to program in C and I recommend the video tutorials on thenewboston.com to get started.

Finally, let’s see the whole code in one chunk:

#include <stdio.h>  //standard input and output
#include <stdlib.h> //standard library
#include <ctype.h>  //includes isupper() and isdigit() functions for obvious purposes
#include <string.h> //includes the strlen() function to check password length
#define MIN 5       //minimum length
#define MAX 11      //maximum length

int main()
{
    char pwd[MAX];     //array containing the password
    int upper[MAX];    //array for keeping track of upper-case letters
    int num[MAX];      //array for keeping track of numbers
    int dollar[MAX];   //array for keeping track of dollar signs
    int sumUpper = 0;  //sum of upper-case letters in password
    int sumNum =0;     //sum of numbers in password
    int sumDollar = 0; //sum of dollar signs in password
    int i = 0;         //index for the loops

    for (i = 0; i < MAX; i++) //initializing the arrays makes sure they
    {                         //start with "clean" memory locations
        pwd[i] = 0;
        upper[i] = 0;
        num[i] = 0;
        dollar[i] = 0;
    }

    printf("Your password has to include at least one upper-case letter, number and dollar sign!\n\n");
    printf("Type in your password: ");

    scanf("%s", pwd); //storing the password

    if (strlen(pwd) >= MIN && strlen(pwd) < MAX)   //if password meets minimum and maximum length requirement
    {
        for (i = 0; pwd[i] != '\0'; i++) //for loop runs until it reaches the
        {                                          //special \0 end of string character
            if (isupper(pwd[i]))                   //if a character is upper-case, a 1 is written to
                upper[i] = 1;                      //the corresponding location of the upper array
            if (isdigit(pwd[i]))                   //same applies when a number is found
                num[i] = 1;
            if (pwd[i] == '$')                     //same applies when a dollar sign is found
                dollar[i] = 1;
        }

        for (i = 0; i < MAX; i++) //the digits in each position of the
        {                         //upper, num and dollar arrays are added up
            sumUpper += upper[i];
        }                         //adding up zeros amounts to zero, but adding up
                                  //ones accurately indicates how many of the required
        for (i = 0; i < MAX; i++) //characters are included in the password
        {
            sumNum += num[i];
        }

        for (i = 0; i < MAX; i++)
        {
            sumDollar += dollar[i];
        }

        if (sumUpper > 0 && sumNum > 0 && sumDollar > 0) //If sumUpper, sumNum and sumDollar are greater than one,
            printf("\nGood password!\n");                //it means that at least one of each required character
        else                                             //has been included in the password
            printf("\nYou have to include at least one number, upper-case letter and dollar sign!\n");
    }
    else //if password doesn't meet minimum and maximum length requirement
        printf("\nYour password has to be between 5 and 10 characters!\n");

    return 0;
}
Advertisements

I enjoy microcontroller programming (AVR), programming in C/C#, playing with electronics, the Raspberry Pi and Arduino. My other passion is for IT - virtualization, PowerShell, servers and so on.

Tagged with: , ,
Posted in Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 167 other followers

%d bloggers like this: