Saturday, February 27, 2010

SLANG4.net Interpreter now runs on Linux using Mono

To learn Mono , I decided to port the SLANG4.net compiler/interpreter to run on GNU Linux. I am using Fedora Core 10. To my surprise , I could do this by changing couple of lines. This shows that , Mono can compile Visual C# code correctly. ( Mono was never in mind when I wrote the code )

The SLANG4.net .net executable generation module got ported quite easily. But, the executable generated is throwing Invalid exception for ret instruction. Need to investigate it further.

C/C++ Programming under Linux - Part 3

The following program will spit the environment variables inherited when invoked.

///////////////////////////////////
// envspitter.cpp
//
// A C/C++ program to spit the environmental variables
//
// g++ -oenvspitter.exe envspitter.cpp
//

#include <stdio.h>

int main( int argc , char **argv , char **envp )
{

char **temp = envp;

while (*(temp+1) != 0 ) {
puts(*temp);
temp++;
}

return 0;

}

C/C++ Programming under Linux - Part 2

Most console programs in GNU Linux ( for that matter Windows ) accept command line arguments. The following program will spit the arguments given at the command line to the console.


///////////////////////////////////////////
// commandline.cpp
//
// Command Line argument spitter
//
// g++ -ocmdline.exe commandline.cpp
//
//
#include <stdio.h>


int main( int argc , char **argv )
{
if ( argc == 1 ) {
printf("No command Line Argument\n");
//
// argc will be at least 1 in the case of C/C++ Programs
// argv[0] will contain the executable name
return 0;
}


//---------------- Print the Executable name
printf("%s\n", argv[0] );


//------------- Spit the rest of the arguments
for( int j=1; j< argc ; ++j )
puts(argv[j]);

}


C/C++ Programming under Linux - Part 1

Here is a small Program which I helped one of my friend to write.

///////////////////////
//
//
// A hello world program using GNU C/C++ under Linux
//
// g++ test.cpp => a.out
// if you want to give another name (say test.exe ) for
// the executable
//
// g++ -otest.exe test.cpp
//
// ./test.exe
//
//
#include <stdio.h>

int main( int argc , char **argv )
{
printf("Hello world \n" );

}

Friday, February 26, 2010

There is need for good plumbers.

Thanks to the "heroics" of my son and subsequent "bravery" of his father , it was made sure that a pipe connection got broken. Our regulation guy ( always intoxicated with alcohol was not well this time... ) could not be reached and one day was lost finding a substitute.

Finally , thanks to some advice from my uncle , I could fix the problem after visiting my neighbourhood tools shop and some 30 minutes of jugglery. I think , decent living can be made as a plumber... no income tax and paper work... and satisfaction of fixing a leak or break is as pleasurable as learning a new algorithm.

Wednesday, February 24, 2010

Now,I'm a Complan Boy !

Yesterday , when i had gone to a medical shop , i came across a board which announces the availability of Complan Family lite product. As Per the manufacturer , it is 100% sugar free and cholestrol free. I purchased one pack immediately for the price of Rs. 143. Just now i prepared a cup of it (watched India vs RSA match while sipping it ) and i can safely use the moniker -"I'm a complan boy"

Tuesday, February 23, 2010

Encumbrance In Object Oriented Design

Encumbrance is a legal term which has been brought forward to the Object Oriented World.

The defenition given is
" Total Ancillary machinery comprising all other classes that given class must rely on doing it work."

The algorithm to find Enumbrance of class ( C ) is

Find out all the classes C refers to , Count all the classes which they refers to and so on , the total will be the Encumbrance of a class C.

You have to understand the defenition of "Direct Class Reference set" and "Indirect class Reference set" to fully understand Encumbrance.

The celebrated Law of Demeter is based on this notion. ( The idea is to minimize the Direct Class Reference set )

Consult "Fundamentals of Object Oriented Design In UML" by Meilir Page-Jones by Addison Wesley press for more on this. ( Page 241-252 )

Tilakan vs Mohanlal - can be good for Malayalam movie industry !!

I was watching (on Telivision ) how an "outsider" like Sukumar Azhikkode is able to make inroads into a "scuffle" which he does not have much role.

It is a well known fact that some "Individuals" and their cronies are in control of the Malayalam Cinema Industry. The People of Kerala are forced to watch stereo typical movies because of this "situation" in the film Industry.

Mr. Thilakan's "Audacity" has crossed a limit and thanks to this,Keralites might think SreeSanth is a better behaved person. ( SreeSanth is a remarkable character as when he plays cricket , 30 million Mallus will be praying that he should be hit for a Boundary or Six ...despite that he has surivived in the Indian Cricket team for more than five years...first time...some mallu has done it )

Even M.A. Baby ( may be ..because he is Minister of "Culture" ) has agreed to mediate between "superstar" Thilakan (he thinks he is super star ) and "actor" Mohan Lal ( Mammootty vs Mohan Lal is in a stalemate...so..keralites has not conferred "superstar" status on both of them ).

I think , Keralites should hope that these "clashes" will continue and in the end , a new breed of Producers , Directors , Actors come to the scene. Let us pray to the Devil about the plight of "God's own country's?" Malayalam Film Industry.

CSLA.net - Good .net Programming Techniques

CSLA.net is an application development framework written by Rockford Lhotka and can be downloaded from this site.

If you are a person who is fond of bed side reading , you can purchase Expert C# 2008 Business Objects by Rockford Lhotka himself.

Some of the cool techniques include Portable Objects ( aka Mobile Objects ) , Serialization techniques , Fine grained undo/redo ( at property level ) , Authorization rules (at a fine grained level ) , Data Portal , Business rules and Failed rules management , LinQ integration
and how things can be used with UI technology of your choice. ( A Silverlight version is coming soon )

This framework can be an excellent starting place for MiddleWare and Backend integration for .net.

Highly recommended ( Both the book and framework )

Cyrus Broacha and his Week that wasn't

The Show "Week that was not" is one of my favorite shows as it is one of the best example of jugglery of words and shifting the weight can keep you laughing for hours.

I happen to see repeat telecast of a show today. He covered Javed Akthar - Amir Khan spat, BJP leadership's reuse (or recycle) of leaders etc in a hilarious manner.

Another goodie this time was how all time romantic hits of Bollywood were compiled from slang words.

Model View Presenter Pattern

I came across Model View Presenter ( MVP ) from "Agile Principles , Patterns and Practices" by Robert and Micah Martin (father and son duo ). I did not fully comprehend the difference between the Model View Controller (MVC) and the MVP then.

Today , i did some reading and found out that for Test Driven Development (TDD), MVP is a better pattern than MVC. ( May be your Test Client might have to implement IView Interface..! )

In a MVC scenario for classical ASP.net , too much code will be lying in the code behind and there is going to be coupling between UI Layer and Controller Layers. In MVP , presenter sits in the middle and interacts with the UI through Interfaces.

To put it in another way , validation and other preprocessing code can be moved to Presenter Interface to minimize the code fragmentation. (One can have hierarchy of presenters for different UI technologies )

Monday, February 22, 2010

Rizwanur Suicide case

The Rizwanur suicide case ( aka "Rizwanur Murder Case " ) is back in the news after some time. This time , due to an agreement signed between Kolkotta Knight Riders and Lux Cozi company. The company is owned by Ashok Todi (his daughter Priyanka married Rizwanur ) whom CBI suspects to have induced Rizwan into committing his act.

Some time back , this case was all in the news. Falling in love is natural , Eloping is also natural ( as i write it ....it might be happening all across the country) and revenge by girl's family ( or in some case boy's family ) soon follows in some of them. Why this case was singled out ?

The fact that boy was a Muslim by faith and the girl was Hindu by faith gave this case , some national prominence as

1) Trinamool Congress and Congress choose it as a weapon against ruling CPM
2) CPM was forced to take action to show that they are not anti-Muslim
3) Left leaning liberals and Intellectuals used it as a platform to be in news.....

Even some Muslim groups rioted and burnt public property on this issue.

Had the boy been a person from other faiths , I do not think any of the above groups would have chosen to make that cry.

The CBI has "found" out that Rizwanur has committed suicide. But for abetting suicide has charge sheeted some people ( which includes Ashok Todi )

Moral of the story is "Before Eloping with some one ....double check where the partner belongs to..". Others who cry for you are just using you to further their goals.

Extrovert vs Outspoken

At a get together some of my friends laughed at me for "claiming" that i am an Introvert. The Problem is in the interpretation of meaning of the term Extrovert

I am an Outspoken Guy. That does not mean , i am an Extrovert.
Most People are confused between the two.


All Extroverts are outspoken. All Outspoken guys need not be Extroverts.

Sunday, February 21, 2010

Interpreter Taxonomy

Programming language implementation can be broadly classified as Compilers and Interpreters.

Today , i was going through documentation of the XIDEK ( An interpreter development tool kit from Parsifal software ) and happen to come across four class of interpreters

Direct Execution Interpreter
The script is executed as it is parsed.

Direct Compilation Interpreter
The script is compiled into bytecode as it is parsed. The bytecode is then executed.

Tree Execution Interpreter
An abstract syntax tree is created as the script is parsed. The script is then executed by walking the tree.

Tree Compilation Interpreter
An abstract syntax tree is created as the script is parsed. The script is then compiled into bytecode by walking the tree. Finally, the bytecode is executed.

The Interpreter available with SLANG4.net belongs to Tree Execution Interpreter category.

KISS principle - a small addition

Keep It Stupid Simple is a maxim which seasoned engineers use. Over a period of time , i have seen this term being abused to force one to go in a naive route in most software engineering projects.

Today i came across , (@ http://lambda-the-ultimate.org/classic/message12104.html )

"Dave Parnas makes the distinction between 'short-sighted simplicity' and 'visionary simplicity'. "
By Peter Van Roy.


When some one uses KISS maxim....it should be for advocating visionary simplicity....!

P.S :- Peter Van Roy is the co-author of "Concepts , Techniques and Models of Programming.." which every programmer should read as well as own a copy. In some circles it is regarded as the modern day equivalent of Structure and Interpretation of Computer Programs.

Finally...Sukumar Azhikkode is telling something sensible

While cycling through channels , i happen to come across a news item where Sukumar Azhikkode telling the Keralites that "Emperors are naked......".

In my younger days , i used to wonder how Kannadigas,Tamilians and Telugus could tolerate their actors who were well into their graves. When i got opportunity, i took up the matter with couple of people from Andhra and Karnataka. They asked me to carefully look at Malayalam heroes of the day. When i saw malayalam movies through eyes of others , i understood how they tolerated RajKumar,MGR and NTR when they were dancing with heroines who are 1/3 their age.


It might be a case that Azhikkode's musing is a classic case of "sour grapes". Any way i feel he was right in this issue. (Your perception may differ )

Narrow Escape

Pls. watch this .....

Sabash Taliban !

After hearing the massacare of some Sikh youths in NWFP of Pakistan , "Bollywood ka Badshah" is planning a new movie titled , My Name Is Singh (MNIS)

MNIS story centers around Jaswinder Singh, an ordinary Sikh youth with Alzheimers disease from Gurdaspur travelling all the way to Pakistan via England , Dubai , Iraq War Zone , Iran , Afghanistan to reach Arms bazar of Peshawar to meet his love , Parveena Sultana.

MNIS will bring joy to all secular indians as climax of the movie shows how Jaswinder Singh survived the journey with the help of a war lord who wants to settle score with Parveena's father. It has been done not to hurt the religious sentiment of already hurt Sikh Community.

"Badshah" hopes that with his acting age old enimity between two communities can be brought to an end through his Films. Since there is no equivalent of "Sena Nayak" in Pakistan (they will only kill...not verbally roar !) , Badshah hopes his new film can be released in pakistan as well.

"Badshah" wants to thank those Talibanis the way he thanked Mohammed Atta and co for giving him space to produce his ealier film.

The entire film crew is in a hurry as film has to be released before the next massacare.

FOSS

Tilak is very passionate about Free and Open Source Movement. Not only he is passionate about it , he brags about it as well..

Tilak =>"Had it not been for FOSS movement ...MS would have sat on top of us "

Prem =>"It is debatable...!"

Tilak =>"FOSS movement helped to disseminate knowledge to the masses"

Prem=>"I agree to that ... "

Prem =>" FOSS knowledge is Freely Usable Computer Knowledge as well"

What does API stand for ?

One day Prem and Tilak went to meet the Guruji. Tilak was euphoric as he has just managed to learn an Image Processing API from Microsoft.

Tilak => "Guruji, I learned a new API to write an image processing application..."

Guruji => "What is so special about it ?"

Tilak => "It is tough to learn that ...!... Prem would have definitely struggled with it"

Prem =>"Tilak , if an API is tough to learn ... it is a bad case of API design...!"

Guruji =>"APIs are Average Programmer Interface... if Tilak can learn it...Prem can do it as well"

Friday, February 19, 2010

A nice podcast on Intentional programming

Charles Simonyi was the primary architect of Microsoft Word and moreover Hungarian notation which was in vogue with Windows Programmers ( C/C++ ) owes it's name to the fact that he ( a Hungarian ) invented it.

He has sponsored a chair for popularization of science and Richard Dawkins was an occupant of that chair. He is an ardent proponent of Intentional programming, a top secret project whose information is slowly trickling out only recently. He runs a company to realize Intentional software
development. ( A DSL work bench is the closest stuff )

I was listening to a podcast in Software Engineering Radio.

Idleness is a virtue !

I have long felt it and practice it. This is what English Philosopher and Mathematician Bertrand Russel has to say on the topic.

Language Implementation Patterns Book

The above book is something anyone who has got interest in .NET and java should not miss. using ANTLR and Java , the author covers most of the language translation and interpretation issues without Formal language theory. The author is the creator of the ANTLR tool ( formerly PCCTS ).

This book gives a subtle message that Compiler Theory is for Tool implementers. Inside the ANTLR implementation all the wisdom of Lexing and Parsing is already embedded in it. ( ANTLR supports LL(k) parsing...Yacc supports LALR(1) ). So, as a software developer you can focus on how well to structure the Compilation Process and the input language in question.

He covers

LL(1) ( Top down parser with one token look ahead ) Lexer
Moves on to LL(1) Parser
LL(k) Parser ( which Antlr is )
Other non standard parsing strategies
Abstract Syntax Tree creation techniques
Tree Transformation for optimization
Building Symbolic Interpreters
Building Byte code interpreters ( on a VM )
Template processing using StringTemplates

There are code examples for every strategy he covers. After reading this book , you
can treat language processing as a version of configuration file processor. Since the examples are in java , .NET developers can profit from it.

Java Code is easy to read for .NET developers
ANTLR supports C# code generation ( it has got a .net run time DLL )

.NET developer can learn by porting the code from java to .net

In the future , front end for the SLANG4.net project will be written using
ANTLR.

Check out the site of the book here.

DSLs need not be Turing Complete

Now a days there is lot of hype generated on the idea of Domain Specific Languages (DSLs). The moment a software developer hears a language , a general purpose language like Java,C# , C++ or Python will come to his mind.

All general purpose language has a implicit property that they are Turing Complete. if you are having a virtual machine with 15 instructions , you have got the infrastructure to create a Turing Complete Language. The language "Brain Fuck" does that in 8 instructions or so.

When one says about DSL , they need not be Turing Complete. DSLs handle constructs in a limited domain and we need not write a language to process set of all possible programs.

I think DSL ( Domain Specific Languages ) and DSPL ( Domain specific Programming Languages ) needs to be distinguished.

Wednesday, February 17, 2010

Couple of Quotes from the book MetaMath

Today morning , i got up around 5.00 am and was flipping through the book MetaMath written by Gregory Chaitin. The book is an entertaining read. It talks about Prime Numbers,Computability , Randomness , LISP , Godel's proof to name a few. Couple of
Quotations from his book fascinated me and i hope it will be inspiration for others

"without math , you cannot understand Philosophy . without philosophy you cannot understand mathematics and without understanding both of them , you cannot understand
anything worthwhile" - Adapted by Chaitin from Leibniz

"To me , you understand something only if you can program it (You,not some one else )
Otherwise you do not really understand it. you only think you understand it "
- Gregory Chaitin

Tuesday, February 16, 2010

Buffered File I/O

When i was working with 16 bit software development under Windows , i landed in a peculiar problem. C standard File I/O (fopen,fread,fgets) is not working from a 16 bit DLL. Since i was porting code from an existing program , i was forced to write a small I/O package to port the code. ( This was from an old archive of mine )



//
// BUFF.h
//
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>;

#define PNULL 0
#define EOF (-1)
#define BUFFER_SIZE 4096

/////////////////////
//
// A "psuedo" clone of FILE
//
//

typedef struct
{
    int Count; // Characters left in the Buffer
    char Ptr[4096]; // Pointer To Locked handle
    int EoF; // flag
    HFILE file_handle; // file_handle
    int max_read; // number of Characters read
    long FileSize; // Size of the File
}P_FILE;

#ifdef __cplusplus
extern "C" {
#endif

    P_FILE *pfopen( char *FileName );  //for fopen
    int pfclose( P_FILE *pfile );      //for fclose
    int pfgetc( P_FILE *pfile );       //for fgetc
    int pfgets( char *buff , int ncount , P_FILE *file ); //for fgets

#ifdef __cplusplus
}
#endif





///////////
//
// BUFF.cpp
//
//
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include "buff.h"

// Analogous to fopen from standard c library

extern "C" P_FILE *pfopen( char *FileName )
{
    P_FILE *memory = ( P_FILE * ) malloc( sizeof( P_FILE ) );

    if ( memory == NULL )
        return NULL;


    memory->file_handle = _lopen( FileName , OF_READWRITE );



    if ( memory->file_handle == HFILE_ERROR )
    {
        free( memory );
        return NULL;
    }



    memory->FileSize = _llseek( memory->file_handle , 0L , 2 );
    _llseek( memory->file_handle , 0 , 0 );
    memory->Count = 0;
    memory->EoF = 0;
    memory->max_read = 0;
    return memory;

}

extern "C" int pfclose( P_FILE *pfile )
{
    if ( pfile == NULL )
        return 0;

    _lclose( pfile->file_handle );

    free( pfile );
    pfile = NULL;
    return 1;
}



extern "C" int pfgetc( P_FILE *pfile )
{
    if ( pfile->EoF == 1 )
        return -1;


    if ( pfile->Count == 0 ||
        pfile->Count == pfile->max_read )
    {
        pfile->max_read = _lread( pfile->file_handle ,
            pfile->Ptr , 4096 );

        if ( pfile->max_read == 0 )
        {
            pfile->EoF = 1;
            return -1;
        }

        pfile->Count = 0;
    }


    return (int) pfile->Ptr[ pfile->Count++ ];

}


extern "C" int pfgets( char *buff , int ncount , P_FILE *file )
{
    static int old_left = 0;
    int index = 0;
    int c;


    if (file->EoF == 1 )
        return -1;

    buff[ 0 ] = 0;

    if ( old_left != 0 )
    {
        buff[ index++ ] = (char)old_left;
        old_left =0;
    }


    while (1) {
        c = pfgetc( file );

        if ( c == -1 )
        {
            buff[ index ] = 0;
            return 1;
        }

        else if ( c == 13 )
        {
            c = pfgetc( file );

            if ( c != 10 )
            {
                old_left = c;

            }

            buff[ index++ ] = 0;
            return 1;
        }

        else if ( c == 10 ) {

            buff[ index++ ] =0;
            return 1;
        }
        else
            buff[ index++ ] = (char)c;

    }

    return 0;

}

Serial Communication in MSDOS ( C/C++)

I was just going through some of my old CD-ROM collection out of curiosity . I happen to stumble upon some Serial Communication code which i wrote way back in 1994 using Turbo C/C++. Without comments i am placing the code here. ( This code has gone into PC to PC file transfer protocol implementation )

//
// COMM.H
//
//
#ifndef COMM_DOT_H
#define COMM_DOT_H


// Ring Buffer For Maintaining Cirular Queue

typedef struct {

unsigned short c_count; // characters currently in buffer
unsigned short c_start; // Head index
unsigned short c_next; // Tail index
unsigned short b_size; // Size of The Buffer
unsigned char far *pbuffer; // pointer to Buffer

}COM_QUEUE;


typedef struct {

int irqno; // irq number
int int_no; // interupt number
int picaddr; // addres of priority interrupt controller
int lsr_val; // line status register value (last read)
int msr_val; // modem status register value (last read)
unsigned char picmask; // value to enable/disable pic
void interrupt far (*oldhand)(); // Address of OldHandler
unsigned int msr_count;
unsigned int lsr_count;
unsigned int dsr_count;
unsigned int thr_count;
unsigned long total_hit;
unsigned int txr_enabled;


}GLOBAL_DATA;



#ifdef MAIN_MODULE

unsigned int port_address;
GLOBAL_DATA globaldata;
COM_QUEUE far *input_queue;
COM_QUEUE far *output_queue;

#else

extern unsigned int port_address;
extern GLOBAL_DATA globaldata;
extern COM_QUEUE far *input_queue;
extern COM_QUEUE far *output_queue;

#endif



#define RECEIVE_BUFFER_REGISTER (port_address + 0)
#define TRANSMIT_HOLDING_REGISTER (port_address + 0)
#define INTERRUPT_ENABLE_REGISTER (port_address + 1)
#define INTERRUPT_ID_REGISTER (port_address + 2)
#define LINE_CONTROL_REGISTER (port_address + 3)
#define MODEM_CONTROL_REGISTER (port_address + 4)
#define LINE_STATUS_REGISTER (port_address + 5)
#define MODEM_STATUS_REGISTER (port_address + 6)


#define MCR_D_T_R 0x01
#define MCR_R_T_S 0x02
#define MCR_OUT1 0x04
#define MCR_OUT2 0x08

/********** masks for interrrupt enable register ***********/

#define IER_R_D_I 0x01
#define IER_T_H_I 0x02
#define IER_R_L_I 0x04
#define IER_M_S_I 0x08
#define IER_A_L_L 0x0F

#define MODEM_STATUS_I 0x00
#define LINE_STATUS_I 0x06
#define TRANSMIT_BUFFER_I 0x02
#define RECEIVE_BUFFER_I 0x04

#define IIR_II 0x07

#define PIC_VALUE_1 0x20
#define PIC_VALUE_2 0xa0
#define E_O_I 0x20

#define ISOVER_FLOW( x , y ) ( (x) >= (y) )
#define SHOULD_WRAP( x , y ) ( (x) >= (y) )

extern int SetBaudRate( long BaudToSet );
extern COM_QUEUE far *CreatePortBuffer( unsigned short buffer_length );
extern int WritePortBuffer( COM_QUEUE far *ptr , unsigned char c );
extern int ReadPortBuffer( COM_QUEUE far *ptr );
extern int ResetHandler (void);
extern void SetUartBaseAdress(int port_no );
extern void InitGlobals( void );

#endif

//
//
//
// COMM.CPP
//
//

// routines to perform Serial Comm

#define MAIN_MODULE
#define _DEBUG_THIS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dos.h>
#include <conio.h>
#include "comm.h"



// Routine is meant to Set Line Condition
// Give intended baud rate as the parameter
// Line Will Be Set to <BaudRate> <No parity > <1 stop bit>
// Ideal [ 9600 , N , 8 , 1 ]

int SetBaudRate( long BaudToSet )
{

unsigned int Divisor;
unsigned char lcr_value;


outportb( INTERRUPT_ENABLE_REGISTER , 0 );

/*********** Read UART register to Clear Them *****/

inportb( MODEM_STATUS_REGISTER );
inportb( LINE_STATUS_REGISTER );
inportb( INTERRUPT_ID_REGISTER );
inportb( RECEIVE_BUFFER_REGISTER);


// compute the Divisor word


Divisor = ( unsigned int ) ( 115200L / BaudToSet );

// Read The lcr value

lcr_value = inportb( LINE_CONTROL_REGISTER );

lcr_value |= 0x80;

// set the DLAB bit of Line Control Register

disable(); // asm cli // disable interrupts


outportb( LINE_CONTROL_REGISTER , lcr_value );
outportb( port_address , (unsigned char) (Divisor&0xFF ) );
outportb( port_address+1 , (unsigned char) ((Divisor>>8)));

lcr_value &= ~(0x80);

outportb( LINE_CONTROL_REGISTER , lcr_value );
outportb( MODEM_CONTROL_REGISTER,
MCR_D_T_R | MCR_R_T_S | MCR_OUT2);


enable(); // asm sti

// Clear Parity Mask
// equivalent to No parity

lcr_value &=~(0x38); // 56 decimal [ 00111000 ]

lcr_value |=3; // No parity 1 Stop Bit

outportb( LINE_CONTROL_REGISTER , lcr_value );
outportb( INTERRUPT_ENABLE_REGISTER ,
IER_R_L_I | IER_M_S_I | IER_R_D_I );


return 1;

}

// Routine to Allocate Buffer for Cirular Queue

COM_QUEUE far *CreatePortBuffer( unsigned short buffer_length )
{
COM_QUEUE far *temp_ptr;

temp_ptr = ( COM_QUEUE far * )malloc( sizeof( COM_QUEUE ) );

if ( temp_ptr == NULL )
return NULL;


memset(( char *) temp_ptr , 0 , sizeof(COM_QUEUE) );

temp_ptr->pbuffer = (unsigned char far *)malloc( buffer_length );

if ( temp_ptr->pbuffer == NULL )
{
free((void *)temp_ptr);
return NULL;
}

temp_ptr->b_size = buffer_length;

return temp_ptr;

}


int WritePortBuffer( COM_QUEUE far *ptr , unsigned char c )
{

ptr->pbuffer[ ptr->c_next++ ] = c;


ptr->c_count++; // bump the counter

if ( ISOVER_FLOW( ptr->c_count , ptr->b_size ) )
{
ptr->c_count--;
ptr->c_start++;

if ( SHOULD_WRAP( ptr->c_start , ptr->b_size ) )
ptr->c_start -= ptr->b_size;
}


if ( SHOULD_WRAP( ptr->c_next , ptr->b_size ) )
{
ptr->c_next -= ptr->b_size;
}


if ( globaldata.txr_enabled == 0 )
{
globaldata.txr_enabled == 1;
outportb(INTERRUPT_ENABLE_REGISTER ,
IER_R_L_I | IER_M_S_I | IER_R_D_I | IER_T_H_I );
}


return 1;
}



int ReadPortBuffer( COM_QUEUE far *ptr )
{
int c;

if ( ptr->c_count <= 0 )
return -1;


c = ptr->pbuffer[ ptr->c_start++];

ptr->c_count--;

if ( SHOULD_WRAP( ptr->c_start , ptr->b_size ) )
ptr->c_start -= ptr->b_size;

return c;

}

// Routine To Clear Characters from the buffer
//

int ClearBuffer( COM_QUEUE *ptr )
{
disable();

ptr->c_start=0;
ptr->c_next=0;
ptr->c_count=0;

enable();

return 1;

}



// interrupt service routine
//

void interrupt far CommHandler()
{

int c;
unsigned char reg;



globaldata.total_hit++;

enable(); //asm sti // renable interrupts


while(( (reg=inportb(INTERRUPT_ID_REGISTER))&0x1) == 0 )

{
switch(reg&7)
{
case MODEM_STATUS_I : // Handle modem status interrupt

globaldata.msr_count++;
globaldata.msr_val = inportb(MODEM_STATUS_REGISTER);
break;

case LINE_STATUS_I :

globaldata.lsr_count++;
globaldata.lsr_val = inportb(LINE_STATUS_REGISTER);
break;



case TRANSMIT_BUFFER_I :

globaldata.thr_count++;

if (( c = ReadPortBuffer(output_queue)) != -1 )
{
outportb(TRANSMIT_HOLDING_REGISTER,c);

if ( output_queue->c_count == 0 )
{
outportb( INTERRUPT_ENABLE_REGISTER ,
IER_R_L_I | IER_M_S_I | IER_R_D_I);
globaldata.txr_enabled = 0;
}



}



break;


case RECEIVE_BUFFER_I :

globaldata.dsr_count++;
while (inportb(LINE_STATUS_REGISTER) & 1)
{
c = inportb(RECEIVE_BUFFER_REGISTER);
WritePortBuffer(input_queue,c);
}

break;


otherwise:
return;

}


}

// Write End of Interrupt
outportb(0x20 , E_O_I);


}







// routine to Set the handler in the IVT
// IVT - interrupt vector table


int SetHandler( int irqno )
{

unsigned char picmask;
int picaddr;
unsigned char picval;
unsigned int int_no;
unsigned char new_mask;

globaldata.irqno = irqno; // save irqno

// find out the pic mask

picmask = (unsigned char ) ( ~( 1 << ( irqno % 8 ) ));

if ( irqno < 7 )
{
picaddr = PIC_VALUE_1; // address of pic
int_no = irqno + 8;
}
else
{
picaddr = PIC_VALUE_2;
int_no = irqno + 104;
}

globaldata.int_no = int_no;
globaldata.picaddr = picaddr;
globaldata.picmask = picmask;
globaldata.oldhand=getvect(int_no);
globaldata.msr_count = 0;
globaldata.lsr_count = 0;
globaldata.dsr_count = 0;
globaldata.thr_count = 0;
globaldata.txr_enabled=0;

/******* intitialize Global Queue for input and output *****/

input_queue = CreatePortBuffer( 1024 );

if ( input_queue == NULL )
{
fprintf( stdout , "Out of Memory \n" );
exit(0);
}

output_queue = CreatePortBuffer( 1024 );

if ( output_queue == NULL )
{
fprintf( stdout , "Out of Memory\n" );
exit(0);
}


setvect(int_no,CommHandler);


disable(); //asm cli // clear interrupt

picval = inportb( picaddr + 1 );


new_mask = picval&picmask;
outportb( picaddr + 1 , new_mask );

enable(); //asm sti // renenable interrupts

// clear all UART interrupts


/*********** reset the PIC ***********************/


outportb( picaddr , E_O_I );

return 1;

}

int ResetHandler ()

{
unsigned char value;
value = inportb(globaldata.picaddr+1);
value = value | ( 1 << globaldata.irqno );
outportb(globaldata.picaddr+1,value);
setvect(globaldata.int_no,globaldata.oldhand);
free( (void *)input_queue );
free( (void *)output_queue);

return 1;
}

void SetUartBaseAdress(int port_no )
{
port_address = ( port_no == 1 ) ? 0x3f8 : 0x2f8;

}

void InitGlobals( )
{
input_queue = NULL;
output_queue = NULL;
memset( (void *)&globaldata , 0 , sizeof( GLOBAL_DATA ) );
port_address = 0x3f8; // default for COM1
}




#ifdef _DEBUG_THIS

// Routine To Clear The Screen
// analogous to clrscr


void clr_scr()
{
int i;
for( i=0; i<=24; ++i )
{
printf("\n" );
}
}


void main(int argc , char **argv )
{
int c;
int port_no;
int irqno;
int key_val;

if ( argc == 1 )
port_no = 1;
else
port_no = atoi( argv[1] );


/********* if port_no is not 1 or 2 exit ********/

if ( !( ( port_no != 2 ) || ( port_no != 1 )) )
{
fprintf( stdout , "Usage : Comm < 1 | 2 < \n" );
exit(0);

}


InitGlobals(); // intialise Global Variables


/******* determine UART port Address **************/

SetUartBaseAdress(port_no);

irqno = ( port_no == 1 ) ? 4 : 3;

/********** Line Settings ***************/

SetBaudRate( 9600L );

/********* Set The Handler for Com port interrupt *********/

SetHandler( irqno );

/********** Clear Screen *****/
clr_scr();


while ( 1 )
{

if ( kbhit() )
{
c = getch();
if (!c)
c=getch();

if ( c== 27 )
break;
WritePortBuffer( output_queue , c );

}

if ( ( c = ReadPortBuffer( input_queue ) ) != -1 )
{
printf( "Recieved %c\n" ,c );
}

}


ResetHandler();

clr_scr();


printf( "--------------------------------------\n" );
printf( "Comm Statistics \n" );
printf( "--------------------------------------\n" );
printf( "MSI hit := %u \n" , globaldata.msr_count );
printf( "LSI hit := %u \n" , globaldata.lsr_count );
printf( "DSR hit := %u \n" , globaldata.dsr_count );
printf( "THR hit := %u \n" , globaldata.thr_count );
printf( "TOTAL hit := %u\n", globaldata.total_hit );
getch();

}

#endif

AES encryption using OpenSSL (C++)

The following code demonstrates how one can use OpenSSL to incorporate AES encryption to your program ( I adapted a public domain program written by saju pillai )


//////////////////////////////////
//
//
// AES Encryption using OpenSSL
//
//
//

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h> // use high level interface

#pragma comment(lib,"libeay32.lib")
#pragma comment(lib,"ssleay32.lib")


///////////////////////////////////////
//
// initialize Encryption and decryption context
// using OpenSSL
//
int INITIALIZEAES(
unsigned char *KeyData,
int KeyLength,
unsigned char *Salt,
EVP_CIPHER_CTX *en_ctx,
EVP_CIPHER_CTX *de_ctx)
{
int rc;
int Rounds = 10;
unsigned char aes_key[32], aes_iv[32];

///////////////////////////////////////////
//
//
// Cipher Block chaining mode , SHA1
rc = EVP_BytesToKey(
EVP_aes_256_cbc(), // Cryptographic mode
EVP_sha1(), // SHA1
Salt, // a fuzzifier
KeyData,
KeyLength,
Rounds, // more rounds
aes_key, aes_iv); // return buffers

EVP_CIPHER_CTX_init(en_ctx);
EVP_EncryptInit_ex(en_ctx,
EVP_aes_256_cbc(),
NULL,
aes_key,
aes_iv);

EVP_CIPHER_CTX_init(de_ctx);
EVP_DecryptInit_ex(de_ctx,
EVP_aes_256_cbc(),
NULL, aes_key, aes_iv);

return 0;

}

#define AES_BLOCK_SIZE 128

unsigned char *Encrypt(
EVP_CIPHER_CTX *en_ctx,
unsigned char *msg,
int *msglen)
{
int buffer_length = *msglen + AES_BLOCK_SIZE;
int final_length = 0;
unsigned char *ciphermsg = (unsigned char *)malloc(buffer_length );

EVP_EncryptInit_ex(en_ctx, NULL, NULL, NULL, NULL);
EVP_EncryptUpdate(en_ctx, ciphermsg, &buffer_length, msg, *msglen);
EVP_EncryptFinal_ex(en_ctx, ciphermsg+buffer_length, &final_length);
*msglen = buffer_length + final_length;
return ciphermsg;
}

unsigned char *DeCrypt(EVP_CIPHER_CTX *de_ctx,
unsigned char *ciphertext,
int *len)
{
int p_len = *len, f_len = 0;
unsigned char *plaintext =(unsigned char *)malloc(p_len);

EVP_DecryptInit_ex(de_ctx, NULL, NULL, NULL, NULL);
EVP_DecryptUpdate(de_ctx, plaintext, &p_len, ciphertext, *len);
EVP_DecryptFinal_ex(de_ctx, plaintext+p_len, &f_len);
*len = p_len + f_len;
return plaintext;
}




void main( int argc , char **argv )
{
EVP_CIPHER_CTX en_ctx;
EVP_CIPHER_CTX de_ctx;

unsigned int Salt[] = {12345, 54321};
unsigned char *KeyData;
int KeyDataLen, i;

char *msgtoencrypt = "Hello World";

KeyData = (unsigned char *)argv[1];
KeyDataLen = strlen(argv[1]);

if (INITIALIZEAES(KeyData, KeyDataLen,
(unsigned char *)&Salt, &en_ctx, &de_ctx))
{
printf("Couldn't initialize AES System\n");
return ;
}


char *msg;
unsigned char *ciphermsg;
int outlen, inlen;
outlen = inlen = strlen(msgtoencrypt)+1;

ciphermsg = Encrypt(&en_ctx,
(unsigned char *)msgtoencrypt, &inlen);

msg = (char *)DeCrypt(&de_ctx, ciphermsg , &outlen);

if (strncmp(msg, msgtoencrypt, outlen))
printf("FAIL: enc/dec failed for \"%s\"\n", msgtoencrypt);
else
printf("OK: enc/dec ok for \"%s\"\n", msg);

free(ciphermsg);
free(msg);

return ;

}

Base64 using OpenSSL (C++)

The following program demonstrates how one can use OpenSSL library to do Base64 encoding and decoding

#include <string.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>


#pragma comment(lib,"libeay32.lib")
#pragma comment(lib,"ssleay32.lib")

char *Base64Encode(char *input, int length);
char *Base64Decode(char *input, int length);


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

if ( argc != 2 ) {
fprintf(stdout,"Usage OpenSSLBase64E text \n");
return 1;

}

char *output = Base64Encode(argv[1],strlen(argv[1]));
printf("Base64: %s\n", output);



char new_buffer[512];
strcpy(new_buffer,output);
strcat(new_buffer,"\n\0");

char *temp = Base64Decode(new_buffer,strlen(new_buffer));

printf("Base64: %s\n", temp);

free(output);
free(temp);
}

/////////////////////////////////////////
//
//
//
//
//

char *Base64Encode( char *input, int length)
{
BIO *bmem, *b64;
BUF_MEM *bptr;

b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);

char *buff = (char *)malloc(bptr->length);
memcpy(buff, bptr->data, bptr->length-1);
buff[bptr->length-1] = 0;

BIO_free_all(b64);

return buff;
}

char *Base64Decode( char *input, int length)
{
BIO *b64, *bmem;

char *buffer = (char *)malloc(length);
memset(buffer, 0, length);

b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, length);
bmem = BIO_push(b64, bmem);

BIO_read(bmem, buffer, length);

BIO_free_all(bmem);

return buffer;
}

MD5 using OpenSSL ( C++ )

Following C++ Program computes the MD5 message digest of a string.

/////////////////////////////////
//
// Message Digest using MD5
// (using OpenSSL library )
// Compile using Visual C++ command line compiler...Path to
// OpenSSL import library should be given in the PATH environment
// variable..
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <openssl/evp.h>

#pragma comment(lib,"libeay32.lib")
#pragma comment(lib,"ssleay32.lib")


void MessageDigest( void *msg , int len ,void *msgout,int *outsize)
{
EVP_MD_CTX mdctx;
unsigned char md_result[EVP_MAX_MD_SIZE];
unsigned int md_length;

EVP_DigestInit(&mdctx, EVP_md5());
EVP_DigestUpdate(&mdctx, msg, (size_t) len);
EVP_DigestFinal_ex(&mdctx, md_result, &md_length);
EVP_MD_CTX_cleanup(&mdctx);
memcpy( msgout,md_result,md_length);
*outsize= md_length;

}


void main( int argc , char **argv )
{
FILE *fp = 0;

char Output[EVP_MAX_MD_SIZE];
int len;

MessageDigest( "Hello World",11,Output,&len);

printf("%d\n\n\n",len);

for(int i = 0; i < len; i++)
{

printf ("%02x", Output[i]&255);
}




}

MD5 computation using Java

Here is a short program which shows how to compute MD5 message digest.

import java.security.*;
import java.math.*;

public class MD5
{
public static void main(String args[])
throws Exception {

String s="Hello World";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
System.out.println(new BigInteger(1,m.digest()).toString(16));
}
}

MD5 computation using C# CSP

The following program computes MD5 hash of a message.

using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

class MD5Test
{

public static string EncodeMD5(string str)
{
Byte[] ByteStr;
Byte[] ByteEnc;
MD5 md5;
md5 = new MD5CryptoServiceProvider();
ByteStr = ASCIIEncoding.Default.GetBytes(str);
ByteEnc = md5.ComputeHash(ByteStr);
return Regex.Replace(
BitConverter.ToString(ByteEnc),
"-","").ToLower();

}

public static void Main(String [] args ) {
Console.WriteLine(EncodeMD5("Hello World"));
}

}

Permutation generation using C#

Subset construction and Permutation generation are the two examples which i used to demonstrate computational intractability as part of a OWASP presentation on cryptography.

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

namespace CRYPTCODE
{
public class CPermutation
{
private int[] rs = null;
private String _str = "";
private int _Len;
private bool first_perm = false;
///
///
///

///
public CPermutation(string str)
{
_str = str;
_Len = str.Length;
rs = new int[_Len + 1];
rs[0] = -1;
for (int j = 1; j <= _Len; ++j)
rs[j] = j;
first_perm = false;
}

///
///
///

public string NextPerm
{
get
{
if (first_perm == false)
{
first_perm = true;
return _str;
}
int k = _Len - 1;

while (k > 0 && rs[k] > rs[k + 1])
k--;

int left = k + 1;
int right = _Len;

while (left < right)
{
int tmp = rs[left];
rs[left] = rs[right];
rs[right] = tmp;
left++;
right--;
}

if (k == 0)
return null;

int i = k + 1;

while (rs[i] < rs[k])
i++;
int tmps = rs[i];
rs[i] = rs[k];
rs[k] = tmps;

//---------- Now that we have generated
//-----------next permutation form the string..

string ret_str = "";

for (int tk = 1; tk < _Len + 1; ++tk)
{
ret_str = ret_str + _str[rs[tk] - 1];
}

return ret_str;

}

}

}
}


Given below is a routine which uses the above class

public static void PermutationDemo()
{
// This will take years to exeucte
// CPermutation cp = new CPermutation("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

CPermutation cp = new CPermutation("ABCDE");
string str = "";

long nd = 1;
while ((str = cp.NextPerm) != null)
Console.WriteLine(str + " " + nd++);
}

DSA using C#/.NET

To Digitally Sign a message , we can use any of the hash algorithm available out there. In the case of RSA , we use Public Key to encrypt and Private key to decrypt the message. Digital signature uses Private key to compute signature and Public key to verify ( you can only verify signature ) This is because RSA algorithm has
got a property which can be mathematically depicted as f(g(M)) == g(f(M))



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace DIGITALSIGNATURE
{
class Program
{
static void Main(string[] args)
{
byte[] data = Encoding.UTF8.GetBytes("Hello World");
byte[] publickey;
byte[] signature;

SHA1 hasher = SHA1.Create();

using (var publicprivate =
new RSACryptoServiceProvider())
{
signature = publicprivate.SignData(data, hasher);
publickey = publicprivate.ExportCspBlob(false);
}

using (var publiconly =
new RSACryptoServiceProvider())
{
publiconly.ImportCspBlob(publickey);
Console.WriteLine(publiconly.VerifyData(data, hasher, signature));
data[0] = 0;
Console.WriteLine(publiconly.VerifyData(data, hasher, signature));
}





}
}
}

RSA encryption in C#/.net

For the OWASP meetup held on 14th February 2010,i wrote a program to do RSA encryption using Crypto Service Provider ( CSP ) which is available with all
.net implementation. The code depends on the XML file generated by the code
available on this blog post.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;


namespace RSADEMO
{
class Program
{
public static byte[] RsaEncrypt(byte[] msg)
{
string pubkeyonly = File.ReadAllText("PubKey.xml");
byte[] encrypted;
using (RSACryptoServiceProvider rsp =
new RSACryptoServiceProvider())
{
rsp.FromXmlString(pubkeyonly);
encrypted = rsp.Encrypt(msg, true);

}
return encrypted;
}

public static byte[] RsaDecrypt(byte[] cipher)
{
string privatepublickey = File.ReadAllText("PublicPrivateKey.xml");
byte[] decrypted;
using (RSACryptoServiceProvider rsp =
new RSACryptoServiceProvider())
{
rsp.FromXmlString(privatepublickey);
decrypted = rsp.Decrypt(cipher, true);

}
return decrypted;
}

static void Main(string[] args)
{
byte[] data = Encoding.UTF8.GetBytes("Hello World");
byte[] enc = RsaEncrypt(data);
byte[] dec = RsaDecrypt(enc);
string outp ="";
foreach (byte b in dec)
outp += (Char)b;
Console.WriteLine(outp);

Console.Read();

}

}
}

RSA public key/private key generation using CSP API

The following C# program will generate two xml files. The first one will contain a public key and second one will contain public key/private key file..

using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

class RSATest
{

public static void Main(String [] args ) {

RSACryptoServiceProvider rsap =
new RSACryptoServiceProvider();


File.WriteAllText("PubKey.xml",
rsap.ToXmlString(false));

File.WriteAllText("PublicPrivateKey.xml",
rsap.ToXmlString(true));


}


}

Subset Generation in C#

To demonstrate intractability of algorithms , i wrote a subset generation class. The source code is given below and a program to demonstrate the usage is also given. This was shown at the OWASP meetup held on 14th February , 2010 at Kochi.

//////////////////////////////
// test.cs
// Subset Generation in C#
//
// Visual C#
//
// csc test.cs
//
// Mono
// mcs test.cs
// mono test.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRYPTCODE
{
public class SubSet
{
private string _str;
private int _length;
private ulong _count;
private ulong _max;

public SubSet(string str)
{
_str = str;
_length = _str.Length;
_count = 0;
_max = (ulong)Math.Pow(2, _length);
}

public string Next
{
get
{

if (_count == _max) {
return null;
}
uint rs = 0;
string retstr = "";
while (rs < _length)
{
if ((_count & (1u << (int)rs)) > 0)
{
retstr = retstr + _str[(int)rs];
}
rs++;
}
_count++;
return retstr;

}
}


}


class TestStub {

public static void SubsetTest()
{
// This will take years to execute
// SubSet sb = new SubSet("Thequickbrownfoxjumpsoverthelazydog");

SubSet sb = new SubSet("ABC"); // 8 sub sets
string s = null;
while ((s = sb.Next) != null)
{
Console.WriteLine(s);
}
}

public static void Main( String [] args ) {
SubsetTest();
}

}

}


[sandhya@localhost cs]$ mcs test.cs
[sandhya@localhost cs]$ mono test.exe

A
B
AB
C
AC
BC
ABC
[sandhya@localhost cs]$

RSA key generation

For the OWASP meetup held @ kochi on februrary 14,2010 i wrote a program to demonstrate the working of RSA algorithm.

Here is the source code of the routine
////////////////////////////////////////
// Key Generation Algorithm
// -------------------------
//
// a) Choose two Large Primes , P and Q
// b) Compute N = P*Q
// c) Compute Z = ( P - 1 ) * (Q - 1 )
// d) Choose a number which is relatively prime
// to Z and call it D
// e) Find E such that ExD = 1 (mod Z )
// Public Key => { E , N }
// Private Key => { D , N }
//
//
//
// Encryption
// ----------
// C = P^E (mod N) => Modular Exponentiation
// P = C^D (mod N) => Modular Exponentiation
//

public static void RSAKEYGENDEMO()
{
BigInteger P =
BigInteger.genPseudoPrime(200, 25, new Random());
BigInteger Q = BigInteger.genPseudoPrime(200, 25, new Random());

//
// Let N be P*Q
BigInteger N = P * Q;
BigInteger Z = (P - 1) * (Q - 1);
BigInteger D = Z.genCoPrime(200, new Random());
BigInteger E = D.modInverse(Z);

// "ABC" can be converted to 656667
//
BigInteger MSG = new BigInteger(656667);
// Compute
BigInteger ENCMSG = MSG.modPow(E, N);
BigInteger DECMSG = ENCMSG.modPow(D, N);


Console.WriteLine(ENCMSG);
Console.WriteLine(DECMSG);
}

I used BigInteger implementation available on the Codeproject.

RSA encryption - Tanenbaum's example

In his celebrated Computer Network book , Andrew Tanenbaum gives an example of RSA encryption using the string "SUZANNE" ( his wife's name ?) . The conceptual idea behind RSA algorithm is deceptively simple. I implemented it using C# for an OWASP meetup presentation.

////////////////////////////// 
//
// A Very Naive RSA implementation
//
//
//
//
// Key Generation Algorithm
// -------------------------
//
// a) Choose two Large Primes , P and Q
// b) Compute N = P*Q
// c) Compute Z = ( P - 1 ) * (Q - 1 )
// d) Choose a number which is relatively prime
// to Z and call it D
// e) Find E such that ExD = 1 (mod Z )
// Public Key => { E , N }
// Private Key => { D , N }
//
//
//
// Encryption
// ----------
// C = P^E (mod N) => Modular Exponentiation
// P = C^D (mod N) => Modular Exponentiation
//


using System;

class PublicKey
{
public ulong E;
public ulong N;
}

class PrivateKey
{
public ulong D;
public ulong N;
}


class RSANaive
{
public static byte [] StringToBytes( string ast )
{
int length = ast.Length;
byte [] ret = new byte[length];
int i=0;
foreach(char s in ast )
ret[i++] = Convert.ToByte(s);

return ret;
}

public static ulong ModExp( ulong a , ulong b , ulong n )
{
ulong Y=1;

while ( b != 0)
{
if ( (b & (ulong)1) == 1)
Y = (Y*a)%n;

a= (a*a)%n;

b = b >> 1;
}

return Y;

}

public static ulong Encrypt( ulong msg , PublicKey key )
{

return ModExp( msg , key.E , key.N );

}

public static ulong DeCrypt( ulong msg , PrivateKey key )
{
return ModExp( msg , key.D , key.N );

}

public static void Main(String [] args )
{

Byte [] msg = StringToBytes("SUZANNE");

PublicKey pub = new PublicKey();
pub.E = 3;
pub.N = 33;

PrivateKey pri = new PrivateKey();
pri.D = 7;
pri.N = 33;

ulong [] outp = new ulong[7];
int i=0;
foreach( Byte b in msg ) {

outp[i++] = Encrypt((ulong)((long)(b - 'A')+1) , pub );
Console.WriteLine(outp[i-1]);
}

Byte [] rsn = new Byte[outp.Length];
i=0;
foreach( ulong rs in outp )
{
rsn[i++] = (byte)(DeCrypt( rs , pri ) + 64 );
Console.WriteLine((Char)rsn[i-1]);

}

}


}

Monday, February 15, 2010

JavaScript - I am getting hooked now a days

To help couple of my friends , i happen to take a look at AJAX. I did not use any toolkit , even if i was using C#/ASP.net ( AjaxToolkit is a cool one to save development time ) as my aim was to teach the concept behind Ajax and how various components can be put together.

They ( were designers with some technical bent ) asked me to emulate various UI models available with desk top applications. In couple of days time , i could show most of what they have asked using XML HTTP request model.

From my shelf , i pulled out a cool book by the tile "Beginning JavaScript with D0m Scripting and Ajax" (Apress) to help me understand the internals of some of the script which i pulled out from the internet.

As i went deep , i began to notice JavaScript supports almost all paradigms ( Object Oriented , Functional , Procedural ) available in the computer programming languages. In the book , "Beautiful Code" book there is an article on writing an Interpreter using JavaScript. I went and picked the book and read the code inside the book. (Now, i am able to read it well !)

Later , from wiki i happen to learn about Jint , a javascript interpreter written using C#. I am now considering it as a "first class" programming language.

Friday, February 12, 2010

Base64 Encoding

Have you ever wondered how the email attachment size being wrongly reported by your browser ?
when you upload 1 MB file ...the web based email will report it as 1333 KB.

Email attachments are encoded into a set of 64 characters , thus the name Base64 encoding.

The idea is as follows

a) Take three bytes from the file ( 24 bits )
b) Convert three bytes into four six bit index
c) Look up in a table and emit the character at the specified index
from that table ( Base64Table )

So, three bytes will encoded as four bytes. Thus the file size increase. The reason for this method is old mail gateways do not recognize 8 bit ascii. By mapping the file into printable characters in the first 7 bit of Ascii , we are making sure that binary files are transported without any problem.

Base64 encoding is used by Digital Certificates and Cryptographic algorithms too. The C/C++ program given below will clarify any remaining doubts.

////////////////////////////////
//
//
// Base64 encoding technique demo
//
//
// Written by Praseed Pai K.T.
// http://praseedp.blogspot.com
//
//
//

#include <stdio.h>
#include <windows.h>

///////////////////////////////////
//
// Legal Base64 characters
// Encoder looks up in the table using
// a 6 bit index.
//

BYTE Base64tab[]={

'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X',
'Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l', 'm','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3',
'4','5','6','7','8','9','+','/'

};

////////////////////////////////
//
// Get the index of the character from
// the Base 64 table. This routine is
// used by the Decoder .. This can be
// optimized by using a Base 64 reverse
// table...
//

int ConvertAlphabetToIndex( BYTE alpha )
{
for(int i=0; i < 63; ++i )
if ( Base64tab[i] == alpha )
return i;
return -1;

}

/////////////////////////////////////////////
//
// Encode three bytes (in ) into four bytes
// of data (out) .. The algorithm converts
// three bytes of data (24 bits ) into 4
// 6 bit indexes and uses the index to emit
// the character from the Base64 table into
// output (out)

void EncodeThree( BYTE *inp , BYTE *out)
{

long val = inp[0];
val = val | inp[1] << 8;
val = val | inp[2] << 16;
out[0] = Base64tab[val&63];
out[1] = Base64tab[( val >> 6 )&63];
out[2] = Base64tab[(val >> 12 )&63];
out[3] = Base64tab[(val >> 18 ) &63];
}
///////////////////////////////////
//
// Takes four bytes of Base64 encoded data and
// converts to three bytes of data ...
// Convert the Character into the index of Base
// 64 table and assemble four indexes into a
// long value and extract the lowest three bytes
//
void DecodeThree( BYTE *inp , BYTE *out )
{
long val;
val = ConvertAlphabetToIndex(inp[0]);
val |= ConvertAlphabetToIndex(inp[1]) << 6;
val |= ConvertAlphabetToIndex(inp[2]) << 12;
val |= ConvertAlphabetToIndex(inp[3]) << 18;

out[0] = val&255;
out[1] = (val >> 8 )& 255;
out[2] = (val >> 16)& 255;

}
//////////////////////////////////////////
//
// A driver program....
//
//
void main( int argc , char **argv )
{
BYTE in[3];
BYTE out[4];
in[0]='B';
in[1]='O';
in[2]='B';

EncodeThree(in,out);
printf("%c%c%c%c\n",out[0],out[1],out[2],out[3]);
DecodeThree(out,in);
printf("%c%c%c\n",in[0],in[1],in[2]);

}

Thursday, February 11, 2010

XorCrypt Algorithm

Xor encryption/decryption algorithm is an example of Mono alphabetic substitution cipher. Though not useful , it is a good algorithm to introduce bit-wise operations , substitution and other source coding issues involved in Cryptography.

////////////////////////////////
//
// A (Practically useless ) Naive implementation
// of Xor Encryption.. Written for Demonstration
//
// Praseed Pai K.T.
// http://praseedp.blogspot.com
//
// Compile using Visual C++ command line compiler
// cl XorCrypt.cpp
//
// Usage :-
// XorCrypt "Hello World" A
// XorCrypt "Quick Brown Lazy Fox" z
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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

if ( argc != 3 ) {
fprintf(stdout,"Usage: XorCrypt plaintext key ");
return 1;
}

int plain_len = strlen(argv[1])+1;

char *p =(char *)malloc(plain_len);

strcpy(p,argv[1]);

char key = argv[2][0];

char *temp = p;

while (*temp != 0 ) {
*temp = *temp ^ key;
temp++;
}

fprintf(stdout,"Encrypted string is now ... %s\n",p);

temp = p;

while (*temp != 0 ) {
*temp = *temp ^ key;
temp++;
}

fprintf(stdout,"Encrypted string is now ... %s\n",p);

free(p);
return 0;

}


Wednesday, February 10, 2010

Microsoft SilverLight - my hunch

In the Community Tech days event held at Kochi, SilverLight was the "hot" thing. As far as i am concerned , Silverlight might replace Winforms some day and has already made WPF redundant.

The Primary use cases are

a ) Corporate Intranet applications and portals
b) Extranets ( where a big company can force their vendors to use certain browsers/platform )

For a front facing web site on the internet , i do not think Silverlight is of much use. The emphasis on using hardware acceleration can create compatibility problem and we might be returning to an era where browser/platform specifics will plague the applications.

IMHO , Silverlight is an attempt by M$ to stall the incursion of Flash like technologies to Microsoft's Platform business. ASP.net is a good platform for writing line of business applications. But, for the internet PHP and other open source technologies has already "won" the war with the Microsoft.

A nice Podcast site

Thanks to my erstwhile colleague , i discovered a site with 500+ Podcasts on .net . I think , most of them are very informative.

Pls. check the link @ http://www.dotnetrocks.com/archives.aspx

The Valentine's day - The 'Rape day' of middle class girls

Last year , Valentine's day celebration was marred by controversy surrounding the Mangalore pub incident and Pramod Muthalik's rhetoric.

This day was unknown uptil mid 90s. Later , some clever business people who invent occassions for people to celebrate brought this to the limelight. Nothing is wrong with that. Business people will bring new schemes to make money and it is for each individuals to decide whether they want to be part of the scheme or not.

For me February 14 (1990 ,a Maha Shivrathri day. i am from Aluva where the festival is celebrated on the banks of River Periyar) which i spend Rs. 35 to purchase a book to learn Differential And Integral Calculus. Being a college drop out , that was one of the smartest decision I made in life. The knowledge I gained from that book has helped me to gain a career in Computer Programming.

In those times , this "festival" was unheard off. Later , when the "Hindu" outfits began to make noise on this , who are opposed to those groups began to support this "Festival".

In the late 90s, opposing Valentine's day is equated to hearsay by a group who profits from these "festivals".

In the past two weeks , i have seen lot of people (which belongs to all sections of the society ) who are tensed about this event and they are keeping an eye on their daughters and sisters. ( I have taken samples by inducing discussion on this whenever i happen to get an opportunity )

I have come across people who packs the bag and goes to Bangalore around February 14. I see a special "spark" on their eyes before they make the journey.

I do not know , what is going to happen this February 14th. As a fall out of this one thing is clear for me.

(I suspect ) "Abortion rate in the month of April and May will be more than other months".

Tuesday, February 09, 2010

Dale Steyn's Bowling

I really enjoyed the run up,action and bowling of South African Pacer Dale Steyn. The Ball which took Tendulkar's wicket in the first innings was a real beauty. Another notable wicket was that of Murali Vijay's in the first innings.

He can generate enough pace on a flat wicket , more than the pace, movement of the ball once it has pitched can put any batsman in trouble. I would like to see how he will bowl in Perth. It will be a treat to watch.

Now Let us look forward to Calcutta Test

India Lost the first test to South Africa Today. Rather than blaming the players , we should look forward to a better performance in the next test match. The match against SA was lost on the day one itself. Once SA scored 300 + without loosing much wickets , only thing which we could look forward was a Draw or a Win for South Africa.

Indian strategy has always been ,

a) if India bats first , Score 450+ and spinners has to do the trick
b) if others bat first , bowl them out for less than 350 .., get a lead of 100+ and spinners has to do the trick...

if both strategies do not work , India looses the match. The test becomes Draw in the case where spinners cannot do the trick.

It is ridiculous to ask the curator to prepare a turning wicket to maintain the world #1 ranking. Do not focus on rankings , positions and averages. Focus one game at a time.

"Look Poor" Remark - a good suggestion ?

A Suggestion to the Indians in Oz ("to look Poor" ) by Victorian Police Chief has brought smiles to some residents in my locality. All seems to appreciate the remark as when these "Australians" ( all across Kerala ) come back for vacation, they show the pomp and a kind of snobbery ( "you bloody Indians" ) which you should come across in person to realize.

When you emigrate to a nation , you should not destroy the social structure of the society out there. The kind of support Indian cricket team gets in Australia , New Zea land and England can trigger these kinds of racist attack.

Western society is organized around individual person. Every person is an economic unit. By saving money as we do in India , these "Australians" are ruining Australian economy and even the social fabric. Obviously "Natives" will hate these Economic migrants.

Some time back , when a friend of mine was about to emigrate to New Zea land , i told following words to him , "When you go there , do not live the kind of life you live here. Allow your daughters to mix with the people out there... and spend all the money out there and live like a Westerner"

When he asked , " What is wrong with Indian way of Life ?"

What i said was , "You will bring recession to New Zealand...."

That is what we Indians , Pakistanis , North African immigrants do to the Australian economy.

Based on my conversation with people across the state , at least in private, some Keralites do support these Racist attack. "This is the only way to silence the "incursion" of these ugly "Australians" to their lives" , remarked a young guy. Our conversation had to terminate when
Father of an "Australian" came in between us.

Sunday, February 07, 2010

Making a Living

One day Prem and Tilak were discussing about the effectiveness of Discussion Forums in solving Programming Problems.

Tilak => "Now a days , there is no need to learn anything ...."

Prem =>"Why did u say so ?"

Tilak => "Everything is just a search away ..."

Prem => "What about involved topics like Graphics Programming , Numerical computing ,Data structures , Compilers etc ?"

Tilak =>"I am not going to program such things... , why would you like to live in a hard way when easier ways like bug fixing , java script tweaking or search engine optimization available to make a living "

Prem =>"To fix bugs , you need to understand the concepts ..r8?"

Tilak =>"You just write some code and check in to the source code vault. Testers may or might find errors ...that means potential for more work...when someone in the team gets fed up ..he will fix it ...!!!!"

A chance encounter and the birth of a new learning tool (for my wife )

Last week , i went for a marriage of a friend (and ex-colleague) of mine ( of Blogswara fame ) at Trichur,Kerala. There,I happen to meet an erstwhile colleague of mine (http://technikhil.wordpress.com/) and began to talk about various things. Since he has to travel at least six hours to go back to Trivandrum, i asked him why he has not taken any book. He opened his wallet and took out a small mp3 player and told me that he listened to some podcast when he traveled from Trivandrum to Trichur. He plans to do the same when he goes back.

My wife has a commute time of two hours and i thought buying a MP3 player for her will enable her to listen to podcasts. Luckily , her sister gave a slick mp3 player and now i am downloading some podcasts from Software engineering Radio.

Compression - a special form of encryption ?

In the year 1995 , i purchased "Data Compression Book" written by Mark Nelson. In the book , Author covers Huffman encoding , statistical encoding , arithmetic coding , Dictionary based algorithms , Audio and Discrete Cosine Transform (DCT/JPEG) compression. One of the nice feature about the book is it contained well documented source code implementation of all the algorithms discussed. Moreover , Code worked as well.

In those days , i was using a language called Clipper from Computer Associates. The Clipper language had a library ( Extend.lib ) which aids you in interfacing with C .OBJ files. So, if you reach the limit of Clipper , you can switch to C and interface with Clipper.

One grocery merchant need a encryption program to store some sensitive information regarding his inventory. I took the assignment and interfaced LZ77 ( decompression is fast ..Winhelp used it ) code from the book ( i need to do some tweak and even had to write a assembler routine ) with Clipper ( i keyed in the whole code and even wrote clipper interfacable support system). The Compressed file appears to be full of gibberish. That solved the problem for him ( or at least he had some nice sleep after my program )

Years later (after learning about cryptography) , i used to laugh about my naivety in those days .

Saturday, February 06, 2010

The Notion of Computationally Secure

Rather than giving a definition of the term "Computationally Secure" in it's strict sense , it is better to give an instance where this notion can be handy...

Imagine that Day after tomorrow , you want to bid for a tender and the amount is encrypted in a file. if a cryptologist will take three days to break the code , for all practical purpose you are secured. Available computing power is not enough to break the code in a reasonable time (which will depend upon the context )

Kerckhoffs' principle on Security

One of the central maxim of Cryptography is Kerchkhoff's principle formulated by Dr. Auguste Kerckhoffs. The Principle in essence says that "Only Cryptographic Key should be secret. Other things like Key size , Algorithm , File format should be open". To really make sense of this read Security through Obscurity on Wiki.

The Code Book - A good book on Cryptography

If some one asks me which is the best book on Crpytography , without hesitation i will name Simon Singh's Code Book is the one. In the year 2001,i had attended a one day pre-conference tutorial on Free Software held at Technopark , Trivandrum. A duo from Chennai suggested this book as a good introduction to Cryptography. I got hold of a copy when i had gone for Teched 2001 at Bangalore. I purchased the book from Gangaram Books, M.G. Road , Bangalore.

Mr. Singh ( a Producer for BBC horizon program ) starts with the story of "Bloody Mary" and ends up with a alternate history of Public Key Cryptography.

The url for the book is http://www.simonsingh.net/The_Code_Book.html

The Amazon url is http://www.amazon.com/Code-Book-Science-Secrecy-Cryptography/dp/0385495323



if love this , Pls. take a look at Singh's Fermat's Enigma , a book which Chronicles the attempt to prove Fermat's Last theorem and how Tony Wiles succeeded in Proving Fermat's assertion being true.

Indian edition of Fermat's Enigma is available as Fermat's Last Theorem.

CryptoGraphy - OWASP presentation

I am going to present a session on Cryptography at the next OWASP meetup to be held in Kochi on
14th February ,2010. The session will discuss the lingo , some number theoretic results , symmetric/asymmetric cryptography , various APIs ( in Java and C# and Open source libraries ) to incorporate cryptographic protocols in your enterprise application.

At the end of the session , a programmer will be able to choose protocols , cryptographic mode which suits their application.

I will scribble some of my notes in the coming days in this tag.

Friday, February 05, 2010

Who said domestic cricket matches are not interesting ?

From yesterday onwards , i am pinned before the TV watching Duleep trophy final between West zone and South zone. Dinesh Karthik's century in each innings and Ganapathy's spirited bowling gave South a commanding position. When West came to bat , i did not have any hope for them as chasing 500 + in the fourth innings is a tough ask.

CR Pathak began to blast from the word go. He gave west a brilliant start yesterday. A good innings by Wasim jaffer and Pathan brothers has made the match interestingly poised at the close of the fourth day's play.

West requires 157 runs in a day (90 overs ) with four wicket to spare. Tomorrow , it will be an interesting match. Thanking Neo sports for excellent coverage of the match.

For full scorecard ..visit this page

Thursday, February 04, 2010

Why Shah Rukh is batting for Pakistani Cricketers ?

I do not read newspapers for the last ten years or so (regularly). Even if i happen to read one , i make sure that i read it in the evening. The Problem with the modern information age is unnecessary information percolates to your mind through some medium nonetheless.

When ever i log on to my yahoo home page (my browser home page is set to it ) , occasionally i read some stories whose link are put out there.

To day it was Shah Rukh Khan stories and how that "mad man" Thackeray is dividing the country etc etc....

I think people are confusing two issues as one here as person on the other side is the same ("Sena Nayak")

The two issues are
a) Mumbai for Mumbaites
b) Shah Rukh "batting" for Pakistani Cricketers.

In the heat of the event , Pro- Pakistan elements in India ( Leftist ,the People who preach secularism [but who do not mean it ],People who make pro-pakistani staements to boost their secular credentials, "JNU educated" media ) and people who are not happy with Thackeray's anti -North Indian tirade are getting together to support the Actor.

It is unfortunate that his film's release in trouble because of this controversy.

Let us look the core issue as far as i am concerned, The support for Pakistani cricketers.

My central question here are

For all the terrorist activities which has originated from that land (Pakistan ) , what is wrong in keeping people from there out of a Domestic Cricket Tournament In India ?

Isn't it audacious that Pakistanis ( Politicians included ) think it is their birth right to play in India Premier League ?


Will a single Indian Player be selected for Pakistan Premier League (if it is there )?


Shah Rukh Khan , being a celebrity should have avoided supporting Pakistani Cricketers in the open after the auction controversy became news. The actor's statement was indirect confession
of "ostracization" of Pakistani Cricketers. Rather than raking a controversy , he should have selected some players from Pakistan during the auction. By going to Media and giving statement on this is "Cowardice".

Shah Rukh , not to affect his commercial interest ( success of his film ) world wide made a statement to appease Pakistani diaspora world wide.

How to Cage your kid ?

My kid who is going to be eight at the end of this month uses stealth to evade me. Since i stay in a big compound (no walls between houses ) with my relatives , it is hard to trace him as he will hide in one of the house.

Today , i instructed (with threat ) him to be in his undies. This has forced him to stay inside the home. He is sleeping now.

Wednesday, February 03, 2010

Do Math book writers know How to Calculate Limit ?

I have decided to become a no nonsense Applied Mathematician...!! I have not set a dead line when it is going to be a reality. In the past sixteen years , i have been applying mathematical techniques for my work in Computer Graphics , Compilers , CAD etc..

To transform myself to a "Mathematician" , i need to be really good at solving a large problem set in each topic. ( At least core of Mathematical Analysis ) I have always suspected that with brute force attack we can become really competent in mathematics.

To start the ball rolling , i accumulated all my Math books in one shelf. I started (re)learning Limits (of functions ) and how to calculate it. I was able to solve many a problems from standard text books ( even from soviet days ) . When i hit the wall , i will search for similar problem solved in some other text book. After a while , i began to notice a curious pattern. There are only some 250 limit problems in this world. These Text books borrow from each other.

Now i wonder , Do these people really know to Calculate Limit ( or detect whether limit exists for some functions ) of functions? I suspect majority of them compile books from other standard books ( which are themselves compilation of some earlier work ).

(Re)Learn math while learning Economics

Barring a few universities up north , most universities in India do not teach much math as part of their economics syllabus. Where as if you want to read current economic literature , one need to be good at Analytical Geometry , Single and MultiVariable Calculus including Optimization ,Linear Algebra and Probability theory to name a few. They emphasize representational aspect of Mathematics as much as the computational aspects. ( I have blogged about Representational aspect of mathematics in the past )

Just now , i was flipping through "Fundamental methods of Mathematical Economics" by Appa Chiang and Kevin Wainright. That is a good book not only for anyone serious about Economics, it is a good book about Mathematical modeling as well.

One reason for effectiveness of Mathematical Economics book to teach good math is due to the familiarity of the student with the underlying phenomena ( Money , Rate of interest , Consumption are more familiar that Specific heat capacity , Brownian motion , turbulence and periodicity ). Take a fresh look at Math with Economics and Finance case studies. May be , your mathophobia will go away.

Monday, February 01, 2010

Teaching my Kid - Defenition of Patience understood..!

For the last couple of days , i have been teaching my kid to prepare for his examination. He is in 2nd standard. The stupid problem with the school which he studies is they do not use punishment as a deterrence. The Problem is Parents has to take care of teaching the kids as well or rely on a tuition teacher. We outsource our worries to them and they are looping it back. The end result is Kids end up hating their parents and teachers will be in the good books.

The CBSE syllabus was conceived by Bureaucrats ( IAS people!) for their own benifit. The implicit goal is to make their future generation better prepare for the IAS examination. That might be suitable for a metro. For a sleepy town like Aluva .... , i think a liberal education meant for the social context ( read State Syllabus ) is more appropriate. The Problem is my Wife would not allow him to be moved to a State syllabus school. Besides , the grading system complicates the matter. They judge students not based on the threshold marks. How well he performs relative to other kids.

He does not fear his teachers. I have not seen any kid learning without incentives (be it +ve or -ve ) . So , you need to take the role of teachers of yesteryear.

Teaching your kid on the Eve of his exam requires Patience. ( I did not have it , that is why i dropped out...but..God seems to teach me that too )
As Ambrose Bierce noted ... "Patience is Agony Portrayed as a Virtue "