Wednesday, September 29, 2010

Simple XML Generator in C

This is a simple XML Document Generator in C which generates simple XML Documents based on the user input.

To compile this program on linux :

Save the file as "createtree.c"

Then run following command :

gcc createtree.c -I/usr/include/libxml2 -L/usr/lib -lxml2 -lz -lpthread -lm

Now it has two options of output . Run the associated command to get the desired output.

1. Either the output to the stdout i.e. the terminal screen

Command :
./a.out

2. Or output to a file

Command :
./a.out output.xml

This program can be modified as per the needs .
For example :

The function
void create_child(xmlNodePtr root_node, int attr_on)

can operate in two modes :

1. With attribute

In this mode user cannot add the attribute to the child node.The second argument of function is 0 in this case.

2. Without attribute

In this mode user can add the attribute to the child node.The second argument of function is 1 in this case.

#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <string.h>
#if defined(LIBXML_TREE_ENABLED) && defined(LIBXML_OUTPUT_ENABLED)

char *fgetstr(char *string, int n, FILE *stream)
{
    char *result;
    result = fgets(string, n, stream);
    if(!result)
        return(result);

    if(string[strlen(string) - 1] == '\n')
        string[strlen(string) - 1] = 0;

    return(string);
}

xmlNodePtr create_child(xmlNodePtr root_node, int attr_on) //if attr_on is 0 no attribute is added
{
    xmlNodePtr node = NULL;
    char cn[30],ccon[256];
    printf("Enter child name: ");
    scanf("%s",cn);
    getchar();//To handle newline
    printf("Enter child content: ");
    fgetstr(ccon,sizeof(ccon),stdin);
    if(strcmp(ccon , "\n") == 0)
        node = xmlNewChild(root_node, NULL, BAD_CAST cn,NULL);
    else
        node = xmlNewChild(root_node, NULL, BAD_CAST cn,BAD_CAST ccon);

    if(attr_on)
    {
        char attrname[30],attrval[256];
        printf("Enter child attribute name: ");
        scanf("%s",attrname);
        printf("Enter child attribute value: ");
        scanf("%s",attrval);
        xmlNewProp(node, BAD_CAST attrname, BAD_CAST attrval);
    }

    return node;
}


int main(int argc, char **argv)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr root_node = NULL, node = NULL, node1 = NULL;
    xmlDtdPtr dtd = NULL;
    char buff[256];
    char rn[30];
    int i, j;

    LIBXML_TEST_VERSION;

    doc = xmlNewDoc(BAD_CAST "1.0");

    printf("Enter root name: ");
    scanf("%s",rn);

    root_node = xmlNewNode(NULL, BAD_CAST rn);
    xmlDocSetRootElement(doc, root_node);

    //Creates a DTD declaration.
    dtd = xmlCreateIntSubset(doc, BAD_CAST rn, NULL, BAD_CAST "tree2.dtd");

    //Creates new child nodes
    create_child(root_node , 0);
    node = create_child(root_node , 1);

    create_child(node , 0);

    //Dumping document to stdio or file
    xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1);

    xmlFreeDoc(doc);
    xmlCleanupParser();
    xmlMemoryDump();
    return(0);
}
#else
int main(void)
{
    fprintf(stderr, "tree support not compiled in\n");
    exit(1);
}
#endif

Traversing and Printing the XML Tree

This program traverses the nodes of the XML Document and prints them in the order.
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

#ifdef LIBXML_TREE_ENABLED

static void
print_tree(xmlNode * root_node)
{
    xmlNode *cur_node = NULL;

    for (cur_node = root_node; cur_node; cur_node = cur_node->next)
    {
        if (cur_node->type == XML_ELEMENT_NODE)
        {
            printf("<%s>\n", cur_node->name);
        }

        print_tree(cur_node->children);
    }
}


int
main(int argc, char **argv)
{
    xmlDoc *doc = NULL;
    xmlNode *root_element = NULL;

    if (argc != 2)
        return(1);


    doc = xmlReadFile(argv[1], NULL, 0);

    if (doc == NULL )
    {
        printf("Document parsing failed!!! \n");
        exit (1);
    }
    
    root_element = xmlDocGetRootElement(doc);
    
    if (root_element == NULL)
    {
        printf("Document is empty\n");
        xmlFreeDoc(doc);
        exit(1);
    }

    print_tree(root_element);

    xmlFreeDoc(doc);

    xmlCleanupParser();

    return 0;
}
#else
int main(void)
{
    printf("Tree support not compiled in\n");
    exit(1);
}
#endif

Tuesday, September 28, 2010

Simple password based authentication program in C

This is a simple password based authentication program which runs both on Windows as well as Linux.

#ifdef __linux__
#include <unistd.h>
#endif
#include <iostream>
#include <stdlib.h>
#ifndef __linux__
#include <conio.h>
#endif

using namespace std;

int main()
{
 string pass = "";
#ifdef __linux__
    system("clear");
    pass  = getpass("Enter Password : ");
#else
    system("cls");
    char ch;
    cout << "Enter Password : ";
    ch = _getch();
    while(ch != 13) //character 13 is enter
    {
        pass.push_back(ch);
        cout << '*';
        ch = _getch();
    }
#endif
    if(pass == "Hello")
    {
        cout << "\nAccess granted :P\n";
        //Further processing goes here...
    }
    else
    {
        cout << "\nAccess aborted...\n";
    }
}

Monday, September 27, 2010

Simple XML Parser in C using libxml

This is a simple XML parser example in C which uses the libxml library for parsing the XML Documents.
Libxml is a XML processor for the GNOME project. It implements a whole lot of existing standards related to markup languages and a few extras as well.It is open source and can be freely downloaded at ftp://xmlsoft.org/libxml2/

Also some useful documentation about its usage can be found at http://xmlsoft.org/downloads.html

This is just the usage of the library API to get the field values from a XML Document.

For example,

If the XML Doc is somewhat like this :


  
     John Fleck
     June 2, 2002

To get the author name we need to run the program like this -->

Compilation step : gcc xmlParse.c -I/usr/include/libxml2 -L/usr/lib -lxml2 -lz -lpthread -lm

Run : ./a.out test.xml storyinfo author
Output : John Fleck

Remember : This program assumes that the libxml is installed in the system.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

void die(char *msg)
{
  printf("%s", msg);
  return;
}

void
parseNode (xmlDocPtr doc, xmlNodePtr cur, char *subchild)
{

    xmlChar *key;
    cur = cur->xmlChildrenNode;
    while (cur != NULL)
    {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)subchild)))
        {
            key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);

            printf("%s\n", key);
            xmlFree(key);
        }
        cur = cur->next;
    }
    return;
}

static void
parseDoc(char *docname, char *child, char *subchild)
{

    xmlDocPtr doc;
    xmlNodePtr cur;

    doc = xmlParseFile(docname);

    if (doc == NULL )
        die("Document parsing failed. \n");

    cur = xmlDocGetRootElement(doc); //Gets the root element of the XML Doc

    if (cur == NULL)
    {
        xmlFreeDoc(doc);
        die("Document is Empty!!!\n");
    }

    cur = cur->xmlChildrenNode;
    while (cur != NULL)
    {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)child)))
        {
            parseNode (doc, cur, subchild);
        }
        cur = cur->next;
    }

    xmlFreeDoc(doc);
    return;
}

int
main(int argc, char **argv)
{
    char *docname;

    if (argc != 4)
    {
        printf("Usage: %s <docname> <child> <subchild>\n", argv[0]);
        return(0);
    }

    docname = argv[1];
    parseDoc (docname,argv[2],argv[3]);

    return (1);
}


Tuesday, September 21, 2010

Complete File Input Output Solution in C

This is a complete file input output solution where user enters some information on the terminal and it gets stored in a file. Also this is a structured file operation program which suports :

1. Insertion of a record
2. Deletion of a record
3. Updation of a record
4. Searching of a record

Note: This program assumes that user enters the data in the correct format as required. i.e. Where the input is number and user enters a character , the program will go into infinite loop. User input is not validated in this program as the intent for writing this program is to understand file input output.

#include <stdio.h>
#define REC_SIZE 56

enum { NOTFOUND = 0, FOUND};

FILE *fp;
typedef struct record
{
    int id;
    char name[20];
    char desig[30];
} Record;

void die(char* msg)
{
    perror(msg);
    exit(0);
}

void insert(num)
{
    Record rec;
    int i ;

    fp = fopen("Record.dat", "a");
    if(!fp)
        die("fopen");

    for(i = 0 ; i< num ; i++)
    {
        printf("\nEnter id (number): ");
        scanf("%d",&rec.id);  //User is expected to enter an integer here

        printf("\nEnter name : ");
        getchar();
        scanf("%[^\n]",rec.name);

        printf("\nEnter desig : ");
        getchar();
        scanf("%[^\n]",rec.desig);

        fwrite(&rec,sizeof(struct record),1,fp);
    }
    fclose(fp);
}

FILE* search(int id)
{
    FILE *fp;
    short flag = NOTFOUND;

    fp = fopen("Record.dat", "r");
    int temp;
    char ch;


    while( fread(&temp,sizeof(int),1,fp) != 0)
    {
        //printf("temp: %d\n",temp);
        if(temp == id)
        {
            flag = FOUND;
            break;
        }
        else
            fseek(fp,sizeof(struct record)- sizeof(int),SEEK_CUR);
    }

    if(flag == NOTFOUND)
    {
        fp = NULL;
        //printf("Record Not Found!!!\n");

    }
    else
    {
        fseek(fp,-sizeof(int),SEEK_CUR);
    }

    return fp;
}

void replace(char *initial , char * final)
{
    strcpy(initial, final);
}

void delete(int id)
{
    FILE *fp1 , *fp2 ,*fpfinal;
    char ch;
    int i = 0;
    int prior = 0 ,tempfp;

    if((fp1 = search(id)) == NULL)
    {
        printf("Record Not Found");
        return;
    }

    fp2 = fopen("temp.txt","w+");

    if(!fp2)
        die("fopen()");

    tempfp = ftell(fp1);
    fseek(fp1,0,SEEK_SET);

    prior =  ftell(fp1);

    while(prior < tempfp)
    {
        fputc(fgetc(fp1),fp2);
        prior++;
    }

    fseek(fp1,sizeof(struct record),SEEK_CUR);
    while((ch = fgetc(fp1)) != EOF)
    {
        fputc(ch,fp2);
    }

    fseek(fp2,0,SEEK_SET);
    fpfinal = fopen("Record.dat","w");

    while((ch = fgetc(fp2)) != EOF)
    {
        fputc(ch,fpfinal);
    }

    fclose(fp1);
    fclose(fp2);
    fclose(fpfinal);

    if(remove("temp.txt") == -1)
        die("Error removing temp file");
}


void update(int id)
{
    int choice;
    FILE *fp ,*fpnew;
    Record temprec;

    if((fp = search(id)) == NULL)
    {
        printf("Record not present!!\n");
        return;
    }

    printf("\nWhich field u wanna update ? \n1. Id 2. Name 3. Designation\n Enter : ");
    scanf("%d",&choice); //User is expected to enter an integer here

    fpnew = fopen("Record.dat","r+");
    fseek(fpnew, ftell(fp), SEEK_SET);

    fclose(fp);

    switch (choice)
    {
    case 1 :
        printf("\nEnter new id : ");
        scanf("%d",&temprec.id); //User is expected to enter an integer here
        fwrite(&temprec.id,sizeof(temprec.id),1,fpnew);
        break;
    case 2 :
        printf("\nEnter new name : ");
        getchar();
        scanf("%[^\n]",temprec.name);
        fseek(fpnew,sizeof(temprec.id),SEEK_CUR);
        fwrite(temprec.name,sizeof(temprec.name),1,fpnew);
        break;
    case 3 :
        printf("\nEnter new desig : ");
        getchar();
        scanf("%[^\n]",temprec.desig);
        fseek(fpnew,sizeof(temprec.id)+ sizeof(temprec.name),SEEK_CUR);
        fwrite(temprec.desig,sizeof(temprec.desig),1,fpnew);
        break;
    default :
        printf("Wrong Choice\n");
        break;
    }
    fclose(fpnew);
}

void list_rec()
{
    FILE *fp;
    char line[REC_SIZE];
    Record rec;
    int nbytes,i=0;

    fp = fopen("Record.dat","r");
    if(fp == NULL)
        die("Open Record.dat");
    while(1)
    {
        nbytes = fread(&rec,sizeof(struct record),1,fp);
        if(nbytes == 0)
            break;
        printf("%d\t%s\t%s\n",rec.id,rec.name,rec.desig);
    }
    fclose(fp);
}
int main()
{
    int id, num, choice ;
    while(1)
    {
        printf("\n1.Insert\n2.Search\n3.Delete\n4.List\n5.Update\n6.Exit\nEnter choice : ");
        scanf("%d",&choice); //User is expected to enter an integer here

        switch (choice)
        {
        case 1 :
            printf("\nEnter num of records: ");
            scanf("%d",&num);//User is expected to enter an integer here
            insert(num);
            break;
        case 2 :
            printf("\nEnter id to search: ");
            scanf("%d",&id); //User is expected to enter an integer here

            if(search(id) == NULL)
            {
                printf("\nRecord Not Found!!\n");
            }
            else
                printf("\nRecord is present in the system!!!\n");

            break;
        case 3 :
            printf("\nEnter id to delete: ");
            scanf("%d",&id); //User is expected to enter an integer here
            delete(id);
            break;
        case 4 :
            list_rec();
            break;
        case 5 :
            printf("\nEnter id to update: ");
            scanf("%d",&id); //User is expected to enter an integer here 

            update(id);
            break;
        case 6 :
            exit(0);
        default :
            printf("Wrong Choice\n");
            break;
        }
    }
}




Output in file "Record.dat" , in the same directory as the proram resides.

Wednesday, September 15, 2010

Simple multithreading example

This is a simple implementation showing how multithreading works.
It prints the multiples of 2 , 3 and 7 in different time intervals.

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

void* thfn1()
{
  int i ;
  printf("Started processing thread 1\n");
  
  for(i=0; i<100; i++)
  {
   printf("%d\n",i*2);
   sleep(5);
  }

}
void* thfn2()
{
  int i ;
  printf("Started processing thread 2\n");
  for(i=0; i<100; i++)
  {
   printf("\t%d\n",i*3);
   sleep(10);
  }

}
void* thfn3()
{
  int i ;
  printf("Started processing thread 3\n");
  for(i=0; i<100; i++)
  {
   printf("\t\t%d\n",i*7);
   sleep(1);
  }

}

int main()
{
  pthread_t tid1,tid2,tid3;
  //pthread_attr_t attr1,attr2,attr3;

  printf("Started main thread\n");
  printf("Thread1\tThread2\tThread3\n");
  pthread_create(&tid1,NULL,thfn1,NULL);
  pthread_create(&tid2,NULL,thfn2,NULL);
  pthread_create(&tid3,NULL,thfn3,NULL);

  pthread_join(tid1,NULL);
  pthread_join(tid2,NULL);
  pthread_join(tid3,NULL);
  
}

DES Implementation in C++

Implementation of DES Encryption and decryption algorithms

//Code from www.programmersheaven.com


# include <stdio.h>
# include <fstream>
# include <string.h>
# include <iostream>
# include <stdlib.h>
using namespace std;

int key[64]=
{
    0,0,0,1,0,0,1,1,
    0,0,1,1,0,1,0,0,
    0,1,0,1,0,1,1,1,
    0,1,1,1,1,0,0,1,
    1,0,0,1,1,0,1,1,
    1,0,1,1,1,1,0,0,
    1,1,0,1,1,1,1,1,
    1,1,1,1,0,0,0,1
};
class Des
{
public:
    int keyi[16][48],
        total[64],
        left[32],
        right[32],
        ck[28],
        dk[28],
        expansion[48],
        z[48],
        xor1[48],
        sub[32],
        p[32],
        xor2[32],
        temp[64],
        pc1[56],
        ip[64],
        inv[8][8];

    char final[1000];
    void IP();
    void PermChoice1();
    void PermChoice2();
    void Expansion();
    void inverse();
    void xor_two();
    void xor_oneE(int);
    void xor_oneD(int);
    void substitution();
    void permutation();
    void keygen();
    char * Encrypt(char *);
    char * Decrypt(char *);
};
void Des::IP() //Initial Permutation
{
    int k=58,i;
    for(i=0; i<32; i++)
    {
        ip[i]=total[k-1];
        if(k-8>0)  k=k-8;
        else       k=k+58;
    }
    k=57;
    for( i=32; i<64; i++)
    {
        ip[i]=total[k-1];
        if(k-8>0)   k=k-8;
        else     k=k+58;
    }
}
void Des::PermChoice1() //Permutation Choice-1
{
    int k=57,i;
    for(i=0; i<28; i++)
    {
        pc1[i]=key[k-1];
        if(k-8>0)    k=k-8;
        else      k=k+57;
    }
    k=63;
    for( i=28; i<52; i++)
    {
        pc1[i]=key[k-1];
        if(k-8>0)    k=k-8;
        else         k=k+55;
    }
    k=28;
    for(i=52; i<56; i++)
    {
        pc1[i]=key[k-1];
        k=k-8;
    }

}
void Des::Expansion() //Expansion Function applied on `right' half
{
    int exp[8][6],i,j,k;
    for( i=0; i<8; i++)
    {
        for( j=0; j<6; j++)
        {
            if((j!=0)||(j!=5))
            {
                k=4*i+j;
                exp[i][j]=right[k-1];
            }
            if(j==0)
            {
                k=4*i;
                exp[i][j]=right[k-1];
            }
            if(j==5)
            {
                k=4*i+j;
                exp[i][j]=right[k-1];
            }
        }
    }
    exp[0][0]=right[31];
    exp[7][5]=right[0];

    k=0;
    for(i=0; i<8; i++)
        for(j=0; j<6; j++)
            expansion[k++]=exp[i][j];
}
void Des::PermChoice2()
{
    int per[56],i,k;
    for(i=0; i<28; i++) per[i]=ck[i];
    for(k=0,i=28; i<56; i++) per[i]=dk[k++];

    z[0]=per[13];
    z[1]=per[16];
    z[2]=per[10];
    z[3]=per[23];
    z[4]=per[0];
    z[5]=per[4];
    z[6]=per[2];
    z[7]=per[27];
    z[8]=per[14];
    z[9]=per[5];
    z[10]=per[20];
    z[11]=per[9];
    z[12]=per[22];
    z[13]=per[18];
    z[14]=per[11];
    z[15]=per[3];
    z[16]=per[25];
    z[17]=per[7];
    z[18]=per[15];
    z[19]=per[6];
    z[20]=per[26];
    z[21]=per[19];
    z[22]=per[12];
    z[23]=per[1];
    z[24]=per[40];
    z[25]=per[51];
    z[26]=per[30];
    z[27]=per[36];
    z[28]=per[46];
    z[29]=per[54];
    z[30]=per[29];
    z[31]=per[39];
    z[32]=per[50];
    z[33]=per[46];
    z[34]=per[32];
    z[35]=per[47];
    z[36]=per[43];
    z[37]=per[48];
    z[38]=per[38];
    z[39]=per[55];
    z[40]=per[33];
    z[41]=per[52];
    z[42]=per[45];
    z[43]=per[41];
    z[44]=per[49];
    z[45]=per[35];
    z[46]=per[28];
    z[47]=per[31];
}
void Des::xor_oneE(int round) //for Encrypt
{
    int i;
    for(i=0; i<48; i++)
        xor1[i]=expansion[i]^keyi[round-1][i];
}
void Des::xor_oneD(int round) //for Decrypt
{
    int i;
    for(i=0; i<48; i++)
        xor1[i]=expansion[i]^keyi[16-round][i];
}

void Des::substitution()
{
    int s1[4][16]=
    {
        14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,
        0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,
        4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,
        15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13
    };

    int s2[4][16]=
    {
        15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,
        3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,
        0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,
        13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9
    };

    int s3[4][16]=
    {
        10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,
        13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,
        13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,
        1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12
    };

    int s4[4][16]=
    {
        7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,
        13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,
        10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,
        3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14
    };

    int s5[4][16]=
    {
        2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,
        14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,
        4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,
        11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3
    };

    int s6[4][16]=
    {
        12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,
        10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,
        9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,
        4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13
    };

    int s7[4][16]=
    {
        4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,
        13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,
        1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,
        6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12
    };

    int s8[4][16]=
    {
        13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,
        1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,
        7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,
        2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11
    };
    int a[8][6],k=0,i,j,p,q,count=0,g=0,v;

    for(i=0; i<8; i++)
    {
        for(j=0; j<6; j++)
        {
            a[i][j]=xor1[k++];
        }
    }

    for( i=0; i<8; i++)
    {
        p=1;
        q=0;
        k=(a[i][0]*2)+(a[i][5]*1);
        j=4;
        while(j>0)
        {
            q=q+(a[i][j]*p);
            p=p*2;
            j--;
        }
        count=i+1;
        switch(count)
        {
        case 1:
            v=s1[k][q];
            break;
        case 2:
            v=s2[k][q];
            break;
        case 3:
            v=s3[k][q];
            break;
        case 4:
            v=s4[k][q];
            break;
        case 5:
            v=s5[k][q];
            break;
        case 6:
            v=s6[k][q];
            break;
        case 7:
            v=s7[k][q];
            break;
        case 8:
            v=s8[k][q];
            break;
        }

        int d,i=3,a[4];
        while(v>0)
        {
            d=v%2;
            a[i--]=d;
            v=v/2;
        }
        while(i>=0)
        {
            a[i--]=0;
        }

        for(i=0; i<4; i++)
            sub[g++]=a[i];
    }
}

void Des::permutation()
{
    p[0]=sub[15];
    p[1]=sub[6];
    p[2]=sub[19];
    p[3]=sub[20];
    p[4]=sub[28];
    p[5]=sub[11];
    p[6]=sub[27];
    p[7]=sub[16];
    p[8]=sub[0];
    p[9]=sub[14];
    p[10]=sub[22];
    p[11]=sub[25];
    p[12]=sub[4];
    p[13]=sub[17];
    p[14]=sub[30];
    p[15]=sub[9];
    p[16]=sub[1];
    p[17]=sub[7];
    p[18]=sub[23];
    p[19]=sub[13];
    p[20]=sub[31];
    p[21]=sub[26];
    p[22]=sub[2];
    p[23]=sub[8];
    p[24]=sub[18];
    p[25]=sub[12];
    p[26]=sub[29];
    p[27]=sub[5];
    p[28]=sub[21];
    p[29]=sub[10];
    p[30]=sub[3];
    p[31]=sub[24];
}

void Des::xor_two()
{
    int i;
    for(i=0; i<32; i++)
    {
        xor2[i]=left[i]^p[i];
    }
}

void Des::inverse()
{
    int p=40,q=8,k1,k2,i,j;
    for(i=0; i<8; i++)
    {
        k1=p;
        k2=q;
        for(j=0; j<8; j++)
        {
            if(j%2==0)
            {
                inv[i][j]=temp[k1-1];
                k1=k1+8;
            }
            else if(j%2!=0)
            {
                inv[i][j]=temp[k2-1];
                k2=k2+8;
            }
        }
        p=p-1;
        q=q-1;
    }
}

char * Des::Encrypt(char *Text1)
{
    int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
    char *Text=new char[1000];
    strcpy(Text,Text1);
    i=strlen(Text);
    int mc=0;
    a1=i%8;
    if(a1!=0) for(j=0; j<8-a1; j++,i++) Text[i]=' ';
    Text[i]='\0';
    keygen();
    for(iB=0,nB=0,m=0; m<(strlen(Text)/8); m++) //Repeat for TextLenth/8 times.
    {
        for(iB=0,i=0; i<8; i++,nB++)
        {
            n=(int)Text[nB];
            for(K=7; n>=1; K--)
            {
                B[K]=n%2;  //Converting 8-Bytes to 64-bit Binary Format
                n/=2;
            }
            for(; K>=0; K--) B[K]=0;
            for(K=0; K<8; K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
        }
        IP(); //Performing initial permutation on `total[64]'
        for(i=0; i<64; i++) total[i]=ip[i]; //Store values of ip[64] into total[64]

        for(i=0; i<32; i++) left[i]=total[i]; //     +--> left[32]
        // total[64]--|
        for(; i<64; i++) right[i-32]=total[i]; //            +--> right[32]
        for(round=1; round<=16; round++)
        {
            Expansion(); //Performing expansion on `right[32]' to get  `expansion[48]'
            xor_oneE(round); //Performing XOR operation on expansion[48],z[48] to get xor1[48]
            substitution();//Perform substitution on xor1[48] to get sub[32]
            permutation(); //Performing Permutation on sub[32] to get p[32]
            xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
            for(i=0; i<32; i++) left[i]=right[i]; //Dumping right[32] into left[32]
            for(i=0; i<32; i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
        }
        for(i=0; i<32; i++) temp[i]=right[i]; // Dumping   -->[ swap32bit ]
        for(; i<64; i++) temp[i]=left[i-32]; //    left[32],right[32] into temp[64]

        inverse(); //Inversing the bits of temp[64] to get inv[8][8]
        /* Obtaining the Cypher-Text into final[1000]*/
        k=128;
        d=0;
        for(i=0; i<8; i++)
        {
            for(j=0; j<8; j++)
            {
                d=d+inv[i][j]*k;
                k=k/2;
            }
            final[mc++]=(char)d;
            k=128;
            d=0;
        }
    } //for loop ends here
    final[mc]='\0';
    return(final);
}
char * Des::Decrypt(char *Text1)
{
    int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
    char *Text=new char[1000];
    unsigned char ch;
    strcpy(Text,Text1);
    i=strlen(Text);
    keygen();
    int mc=0;
    for(iB=0,nB=0,m=0; m<(strlen(Text)/8); m++) //Repeat for TextLenth/8 times.
    {
        for(iB=0,i=0; i<8; i++,nB++)
        {
            ch=Text[nB];
            n=(int)ch;//(int)Text[nB];
            for(K=7; n>=1; K--)
            {
                B[K]=n%2;  //Converting 8-Bytes to 64-bit Binary Format
                n/=2;
            }
            for(; K>=0; K--) B[K]=0;
            for(K=0; K<8; K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
        }
        IP(); //Performing initial permutation on `total[64]'
        for(i=0; i<64; i++) total[i]=ip[i]; //Store values of ip[64] into total[64]

        for(i=0; i<32; i++) left[i]=total[i]; //     +--> left[32]
        // total[64]--|
        for(; i<64; i++) right[i-32]=total[i]; //            +--> right[32]
        for(round=1; round<=16; round++)
        {
            Expansion(); //Performing expansion on `right[32]' to get  `expansion[48]'
            xor_oneD(round);
            substitution();//Perform substitution on xor1[48] to get sub[32]
            permutation(); //Performing Permutation on sub[32] to get p[32]
            xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
            for(i=0; i<32; i++) left[i]=right[i]; //Dumping right[32] into left[32]
            for(i=0; i<32; i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
        } //rounds end here
        for(i=0; i<32; i++) temp[i]=right[i]; // Dumping   -->[ swap32bit ]
        for(; i<64; i++) temp[i]=left[i-32]; //    left[32],right[32] into temp[64]

        inverse(); //Inversing the bits of temp[64] to get inv[8][8]
        /* Obtaining the Cypher-Text into final[1000]*/
        k=128;
        d=0;
        for(i=0; i<8; i++)
        {
            for(j=0; j<8; j++)
            {
                d=d+inv[i][j]*k;
                k=k/2;
            }
            final[mc++]=(char)d;
            k=128;
            d=0;
        }
    } //for loop ends here
    final[mc]='\0';
    char *final1=new char[1000];
    for(i=0,j=strlen(Text); i<strlen(Text); i++,j++)
        final1[i]=final[j];
    final1[i]='\0';
    return(final);
}
int main()
{
    Des d1,d2;
    char *str=new char[1000];
    char *str1=new char[1000];
    //strcpy(str,"PHOENIX it & ece solutions.");
    cout<<"Enter a string : ";
    cin >> str;
    str1=d1.Encrypt(str);
    cout<<"\ni/p Text: "<<str<<endl;
    cout<<"\nCypher  : "<<str1<<endl;
    //  ofstream fout("out2_fil.txt"); fout<<str1; fout.close();
    cout<<"\no/p Text: "<<d2.Decrypt(str1)<<endl;
}

void Des::keygen()
{
    PermChoice1();

    int i,j,k=0;
    for(i=0; i<28; i++)
    {
        ck[i]=pc1[i];
    }
    for(i=28; i<56; i++)
    {
        dk[k]=pc1[i];
        k++;
    }
    int noshift=0,round;
    for(round=1; round<=16; round++)
    {
        if(round==1||round==2||round==9||round==16)
            noshift=1;
        else
            noshift=2;
        while(noshift>0)
        {
            int t;
            t=ck[0];
            for(i=0; i<28; i++)
                ck[i]=ck[i+1];
            ck[27]=t;
            t=dk[0];
            for(i=0; i<28; i++)
                dk[i]=dk[i+1];
            dk[27]=t;
            noshift--;
        }
        PermChoice2();
        for(i=0; i<48; i++)
            keyi[round-1][i]=z[i];
    }
}


Tuesday, September 7, 2010

'ls' command implementation for Linux/Unix in C

This program simulates the simple list directory 'ls' command in Unix. It uses the inbuilt system calls to create this functionality.

#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE !FALSE

extern  int alphasort(); //Inbuilt sorting function

char pathname[MAXPATHLEN];

void die(char *msg)
{
  perror(msg);
  exit(0);
}

int file_select(struct direct *entry)
{
    if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))
        return (FALSE);
    else
        return (TRUE);
}

int main()
{
    int count,i;
    struct direct **files;

    if(!getcwd(pathname, sizeof(pathname)))
        die("Error getting pathname\n");

    printf("Current Working Directory = %s\n",pathname);
    count = scandir(pathname, &files, file_select, alphasort);

    /* If no files found, make a non-selectable menu item */
    if(count <= 0)
      die("No files in this directory\n");
    
    printf("Number of files = %d\n",count);
    for (i=1; i<count+1; ++i)
        printf("%s  ",files[i-1]->d_name);
    printf("\n"); /* flush buffer */
}

Thursday, September 2, 2010

Usage of Map in C++

This is a simple implementation of usage of maps in C++ . Here I have used a simple map containing an int as the key and string as the value . This can further be extended to any data type needed by the use of templates.

Maps are like arrays used to store a pair of values together , each value identified by a key. So it becomes easier to search the values in a Map. One big advantage of maps is that they extend as we use them. Here the duplicate keys are not allowed , which means at a particular key value only one data would be stored. The new data is the one which stays in that particular key value , old one is overwritten .

We can use MultiMap if we need duplicates to be stored.


#include <iostream>
#include <string>
#include <map>
#include <limits>
#define BAD_INPUT_CUTOFF 3

using namespace std;

class MapDemo
{
private :
    map<int, string> mymap;
public:
    MapDemo();
    ~MapDemo();
    void insert_element();
    void delete_element();
    bool find(int);
    bool isEmpty();
    int mapsize();
    void display();
    void revdisplay();
    void clear();
};

unsigned int getInt(const char *prompt)
{
    int input, //used to get input
        bad_count=0; //used to keep track of how many bad attempts.
    do
    {
        std::cout << prompt;
        std::cin >> input;
        if (!std::cin.good())
        {
            std::cout << "\nInvalid Input! : Enter a number only..." << std::endl;
            std::cin.clear(); 

            //clear the buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

            bad_count++; //User made a bad input, count it
            input = 0;   // user did not enter a valid number
        }
    }
    while (input == 0 && bad_count < BAD_INPUT_CUTOFF);
    return input;
}

MapDemo :: MapDemo()
{
    cout<<"New Map created..."<<endl;
}

MapDemo :: ~MapDemo()
{
    cout<<"Map destroyed..."<<endl;
}

void MapDemo :: insert_element()
{
    int key;
    string value;

    key = getInt("\nEnter Key : ");
    
    if(find(key))
      cout<<"Warning : Duplicate Key!!!"<<endl;

    cout<<"\nEnter Value : ";
    cin>>value;
    
    mymap.insert(pair<int,string>(key, value));
}

void MapDemo :: delete_element()
{
  int key;
    if(!isEmpty())
    {
        key = getInt("\nEnter Key of the value to be deleted: ");
        if(find(key))
          mymap.erase(key);
        else
          cout<<"Key not Found !!! ";
    }
}

bool MapDemo :: find(int key)
{
    if(!mymap.empty())
    {
        if(mymap.find(key)->first != key )
        {
          return false;
        }
        else 
          return true;
    }
    return false;
}

bool MapDemo :: isEmpty()
{
    if(mymap.empty())
    {
        cout<<"Map is empty ! ! !"<<endl;
        return true;
    }
    else
        return false;
}

int MapDemo :: mapsize()
{
    return mymap.size();
}

void MapDemo :: display()
{
    map <int, string>::iterator itr;

    for(itr = mymap.begin(); itr != mymap.end(); itr++)
    {
        cout << (*itr).first <<" = "<<(*itr).second<<endl;
    }

}

void MapDemo :: revdisplay()
{
    map <int, string>::reverse_iterator ritr;
    cout << "Displaying in reverse.. "<<endl;
    for(ritr = mymap.rbegin(); ritr != mymap.rend(); ritr++)
    {
        cout << ritr->first <<" = "<<ritr->second<<endl;
    }

}

void MapDemo :: clear()
{
    mymap.clear();
}

int main()
{
    MapDemo m1, m2;

    m1.insert_element();
    m1.insert_element();
    m1.insert_element();
    m1.delete_element();
    m1.display();
    m1.revdisplay();
    m2.insert_element();
    m2.insert_element();
    m2.insert_element();
    m2.display();
    m2.clear();
    m2.delete_element();


}

Suggestions are Welcome... ;)