Milind's Alley Posts

The RSA is a standard algorithm in public key cryptography. I will not bore you with the theoretical details of algorithm that can be found here.What we are gonna talk about today is a visual studio 2010 vc++ project discussing the algorithms used. The code defines the key size which defaults to 512 right now. As we know standard processors don’t have word sizes as big as that so first problem that we face is how to represent this number.

To represent this number we use a byte array of 512/8 = 64. Then we implement all the math functions for it.

    1.  Add: This was implemented using the simple addition bit by bit as in electronics.
      carryi= ai & bi; & is logical AND
      sumi=ai ^ bi; ^ is Exclusive Or
    2. 2’s complement:
    3. Subtract: This is implemented by calculating the twos complement and subsequently calling add. Lets follow the logic with a smaller bit count example. Let’s consider how we would solve our problem of subtracting 110 from 710 using 2’s complement.
      1. First, we need to convert 00012 to its negative equivalent in 2’s complement.
          0111    (7)
        - 0001  - (1)
      1. To do this we change all the 1’s to 0’s and 0’s to 1’s and add one to the number. Notice that the most-significant digit is now 1 since the number is negative.
        0001 -> 1110
      1. Next, we add the negative value we computed to 01112. This gives us a result of 101102.
          0111    (7)
        + 1111  +(-1)
         10110    (?)
      1. Notice that our addition caused an overflow bit. Whenever we have an overflow bit in 2’s complement, we discard the extra bit. This gives us a final answer of 01102 (or 610).
          0111    (7)
        - 0001  - (1)
          0110    (6)
    4. Multiply: We are using normal shift left multiplication and addition. Eg:BinaryMultiplicationExample
    5. Div: This is implemented is using binary search. We start with the divisor and multiply it with the mid where mid = (divisor+dividend)/2. We then call multiply (mid, mid). Then we collapse onto the size that is closer to the dividend.
    6. Greatest Common Divisor: We are using Euclidean algorithm for calculating gcd.
      function gcd(a, b)
          while b ≠ 0
             t := b; 
             b := a mod b; 
             a := t; 
          return a;

RSA Implementation

Now that we have the math functions defined above, we are using the following algorithm:

    function rsa:
        // generate values
        p = random_prime(), // 512 bit
        q = random_prime(), // 512 bit
        n = p * q,
        t = (p - 1) * (q - 1), // totient as φ(n) = (p − 1)(q − 1)
        e = random_prime(1, t),
        d = modular_multiplicative_inverse(e, t);
    return {
    	n: n, // public key (part I)
        e: e, // public key (part II)
        d: d  // private key

   function modular_multiplicative_inverse(a, m)
       g = gcd(a, m);
       assert (g != 1) // inverse does not exist as a and m are not coprime
       x0 = 0, x1 = 1, m0 = m;
       while (a > 1):
           q = a / m; // quotient
           t = m;    
           m = a % m;
           a = t;
           t = x0;
           x0 = x1 - q *x0;
           x1 = t;
       // make x1 +ve
       if (x1 < 0):
           x1 += m0;
       return x1;

The visual studio solution along with the entire code can be found here.

algorithm c++

I was just wondering on how to send SMS from your computer via a mobile device (or GPRS modem). I dug it up and created a small application using c++ (Netbeans IDE) which you can extend and use as per your free will.

The How??

There is a great guide here which you can use to telnet your mobile device and test sending a SMS manually. To do it via a program: read on.

Quick Start

To incorporate this library into your project all you have to do is to include the “ATCommands.h” file. This exports the following functions:
void initPort(int n);
void pokeDevice();
int getMsgIndex();
void sendSMS(char *TargetNo,char *Msg);
void closePort();
Lets dicuss their roles one at a time:
  • initPort(int n): It initializes and sets up the port for communication. The device string should be of the form /dev/ttS<n> where n is the port number (like mostly if you have only one device attached then it will be /dev/ttyS1).
  • pokeDevice(): To be used only under debug mode(explained later). It is analogous to a ping.
  • getMsgIndex(): It is a helper function for sendSMS and returns the index for the new message to be written.
  • sendSMS(char *TargetNo,char *Msg): It is the function you want to call most often and is responsible for actual sending of SMS.
  • closePort(): performs cleanup and closes open port.
Putting it all together, we have a sample test program as:
initPort(n); // Open Port and set params;
#ifdef DEBUG
pokeDevice(); // To test if connection can be made
sendSMS(argv[2],argv[3]); // actual procedure that sends message
// argv[2] is no. and argv[3] is MSG
closePort(); // Cleanup

Try running it and …. guess what… you’ve got SMS (You’ve got mail sounds more catchy or is it just me :P).

Under The Hood

The code I have written supports a DEBUG flag. All you’ve got to do is to include “Debug.h” which defines a macro Debug and enables logging of debug messages to stdout. If you are extending the library then you might want to use the DbgPrint( char *format, … ) function to maintain uniformity of the debug flag.

click download link below to download the complete netbeans project and have a go at it yourself.


The above code was compiled using g++4.3.2/cygwin and tested with mobile handsets of Nokia, Sony Ericsson and Sigmatel. It should also work with most GPRS modems. 

Further Improvements

  • Support for handling multiple mobile devices at once.
  • Error handling can be better.
  • Support for Queueing/Scheduling of messages.


news appeared on the 15th feb 2011 the famous (HBGary)
attacked and all the data in its mysql db and emails were stolen and
posted online. Being a huge fan of the book Rootkits: subverting the
windows kernel
by Hoguland and Butler, I was an active member of the
community there.
It is believed that the site
had published the username and password of all accounts in clear text
(And yes mine toooo!!). As many users are in a habit of keeping the
same password for all accounts like their mail or facebook etc, this
posed a great risk.
The good thing is that the site has now removed the cleartext passwords
stating that it has the potential to compromise people’s social
networking or mailing accounts. But the download to the backup of the
mysql db still is available at :
Moreover, the password field in the database is hashed.
So, can you see your password (clear text) in here… Yes, it is now a
DIY thing.
You will have to use the JTR (John the ripper password cracker) tool.
The hash used is a vulnerable MD5 hash which can be broken given JTR
has the right dictionary (
JTR is available at :
  • Step 1: Download backup, JTR, dictionary (john is in synaptic for
    ubuntu users).
  • Step 2: Extract the .gz file and open the extracted file as text,
    search for your login name and get your password’s hash (I used nano to
    open the file and searched for my login name. Hash is the field next to
    your login name). Note only the first occurence of your username as
    rest may be entries for comments and other stuff.
  • Step 3: Create a text file test.txt with content
    “mypassword:<hash>” without the “” and replace <hash> with
    the hash you found in step 2.
  • Step 4: Open terminal and ask jtr to do its magic using the
    following command :
-wordlist=passwords.txt -format=raw-MD5 test.txt
That was easy.. funny part is that it took 0.00 secs to crack my
password. Am thinking of increasing my password strength….
Now what???
If you or someone you know is a user then you must
immediately change
your password for all site accounts that have the same password. Go Go
With all that being said and done, I feel that it is really unethical
of someone to post such stuff online and posing a threat to other
sites.However, It is our duty to stay vigilant enough and act on it as soon as possible. I am also the kind of person who likes to keep one password for
all accounts (I know its not recommended but its just easier this way)
and hence had to go through a lot of settings and change
password pages. Thankfully, none of my accounts were compromised before
I changed my password. Hope it is the same for you.:)


Hey Ppl!! I am glad to finally get the time to post on my blog again…..

As a part of my curriculum I had to create an online shopping cart. Since I thought of doing it in JSP where in I could some AJAX to make it fancier :).  Well the choice of  IDE for me was to go for RAD (Rational Application Developer) 7.5 with WAS (Websphere Application Server)  CE and DB2 as the back end.This is a basic project but is a good learner for those who are new to JSP, servlets or AJAX. This is also be useful if you are looking to get familiarized with the IDE.

Overview :

Lets draw an outline of the project. We have 2 use cases to the project viz Administrator and Customer. We take them one by one.
ADMIN end:

  • Ability to add products
  • Managing the categories that these products belong to
  • Search Transaction
  • Search Customer
  • Search for product and ability to edit product inf

Next, On the Customer End:

  • View product and its details
  • Register
  • Login
  • Add product to cart and checkout
  • Viewing transaction records

Lets take up the database for such a system. I have taken the snapshot right out of DB2 listing the tables there in (click to expand).

Snapshots :

Lets look at the snapshots of the project first and then we will discuss the problems faced and their solutions.

Hurdles :

Creating & calling stored procedures on DB2.

With RAD thats very easy!! Follow the steps:

  1. Switch to Data Perspective.
  2. If haven’t already create a new project data development proj say
    ‘ShopDev’. While doing so you will be asked to connect to the DB2
    database please make sure you enter the DB2 credentials correctly and
    dont forget to test the connection.
  3. Right click on the ShopDev in the project navigator and select
    new stored procedure. 
  4. Make sure you choose java as the language (unless you want to use
    sqlj) and create the query, set up I/O parameters and you will have a
    stored procedure created for you. This might not be exactly you want so
    you can edit it now. (for eg look in folder
  5. Once done, you can right click on the procedure and select the
    option generate JavaBean class to get the .java file in your dynamic
    web project. (these can be found in 
    /workspace/ShoppingCart/src/genbeans/ )
  6. Now you can use this class to instantiate it in JSP or as Beans..

Image/File Uploads for products

I have seen a lot of posts over the internet for this. But it was
difficult to find one good solution. Our objective was to upload the
file to database
so the approach that we follow is to first upload the file to a
temporary folder on the server then onto the database.

Uploading To FileSystem On Server:
To do so the Apache Commons FileUpload package will do the work
for us.
Just include the library in your path or add it as a reference.
First lets see the jsp page with form that is going to submit both
variables and upload data. (important to note enctype)

<form id="addProduct" enctype="multipart/form-data"
action="AddProduct" method="post">

The code snippet shows the use we make of it in a servlet. Here the
form sends some variables and 3 image files:

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


 * Servlet implementation class AddProduct


public class AddProduct extends HttpServlet {

    private static final long serialVersionUID = 1L;



     * @see HttpServlet#HttpServlet()


    public AddProduct() {


        // TODO Auto-generated constructor stub



     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Create a factory for disk-based file items


        DiskFileItemFactory factory = new DiskFileItemFactory();

        String SUBCAT = null,Name = null,BRAND = null,Description = null;

        int Price = 0,Qty = 0;

        byte[][] Image=new byte[3][5*1024*1024];

        // Set factory constraints


        factory.setRepository(new File("/tmp"));


        // Create a new file upload handler

        ServletFileUpload upload = new ServletFileUpload(factory);

        int cnt=0;

        // Parse the request

        List items;

        try {

            items = upload.parseRequest(request);


        Iterator iter = items.iterator();


        while (iter.hasNext()) 


            FileItem item = (FileItem);

            // Process a file upload

            if (item.isFormField()) {

                String name = item.getFieldName();


                    SUBCAT = item.getString();

                else if(name.equals("PName"))

                    Name= item.getString();

                else if(name.equals("Brand"))

                    BRAND = item.getString();

                else if(name.equals("Quantity"))

                    Qty = Integer.parseInt(item.getString());      

                else if(name.equals("Price"))

                    Price= Integer.parseInt(item.getString());        

                else if(name.equals("Description"))

                    Description = item.getString();


            if (!item.isFormField()) 


                String fieldName = item.getFieldName();

                String fileName = item.getName();

                String contentType = item.getContentType();

                boolean isInMemory = item.isInMemory();

                long sizeInBytes = item.getSize();

                if (sizeInBytes<=10)


                File uploadedFile = new File("/tmp/up" + ++cnt +".jpg");

                try {



                } catch (Exception e) {

                    // TODO Auto-generated catch block






        } catch (FileUploadException e1) {

            // TODO Auto-generated catch block




        AddProductBean apb=new AddProductBean();

        System.out.println("CNT= " + cnt);

        FileInputStream[] fis=new FileInputStream[3];

        for(int i=1;i<=cnt;i++)


            File f=new File("/tmp/up" + i +".jpg");

            fis[i-1]=new FileInputStream("/tmp/up" + i +".jpg");

            Image[i-1]=new byte[(int) f.length()];

            System.out.println(fis[i-1].read(Image[i-1], 0, (int)f.length()));


        String str="khali";

        byte[] n=str.getBytes();

        System.out.println("Len= " + Image[0].length + " "+ Image[1].length + " "+ Image[2].length + " ");

        try {


                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], Image[1], Image[2]);

            else if(cnt==2)

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], Image[1], n);

            else if(cnt==1)

                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, Image[0], n, n);


                apb.execute(SUBCAT, Name, BRAND, Price, Qty, Description, n, n, n);

            for(int i=0;i<3;i++)









        } catch (SQLException e) {

            // TODO Auto-generated catch block




A very common question was getting servlets to work. The error is that
httpservlet is not found.

To correct that you need to add
reference to j2ee.jar that can be found here

Extensions :

  1. Add provision for product offers or discount offers.
  2. Support for preview of multimedia products and downloadable
    products like
  3. Recommended products can be evaluated via Apriori algorithm.

Download :

Finally, here you can download the complete workspace for the project.
Download Workspace

java Web

I undertook a project on digital image processing (DIP) during May-June 2009
at Indian Space And Research Organization (ISRO).
We learned a lot about the working of the great organization and also understood
the concepts behind remote sensing and Geographical Information Systems (GIS).
We also learnt the implementation of image processing algorithms and were
planning to tweak them a little to align them with our project.

The Project:

I was to lead a team of 6 responsible
for creating a project on the various techniques of image processing viz
Classification, Enhancement & Filtering. We used Visual Studio 2008 as the IDE
and created a MFC based project that provided a wide variety of DIP functions.
We used the IGIS SDK to achieve our goal.

The next question that arises is :
Q) What is the IGIS SDK ?
Well it is a under construction project that is a join venture of ISRO and a
company named Scanpoint Geomatics. So we were provided a dll that was exporting functions to do the processing in the background. Our task was massively reduced due to the high level of abstraction provided by the dll. But then again, since all this was under development (hence poorly documented) we had to write our own interface and handle
events and a GUI (Graphical User Interface) which could make the image
processing tasks easy.

Q) Is this IGIS SDK available as a free download and can anyone use it?
Well it is a proprietary software and has to be bought (obviously we were
provided with keys for the development of project).

There are a lot of dimensions to the project…. its better that we read the
complete documentation of the project.
Well I was asked to present my project at both ISRO and my college. So
here is
the ppt I used.

As always,
are the sources to the project. But then again, you would
require IGIS to be preinstalled for this to run.

On the whole, I can say that it was a great learning experience at ISRO. I
am grateful to our project guide Mr. Vinod Bothale and would like to thank him
for being there whenever needed.

Here for a quick preview of the project


I was just browsing the Internet yesterday and I happened to stumble upon this beautiful peice of software named Dragon NaturallySpeaking 10.0. It is a text-to-speech and speech to text conversion software. The best part of it is the speech to text conversion. It is different from the others and takes much less in training. In fact it has different options for different kind of people. It is specialized for Indians who speak in Indian accent and for Americans who speak in American English and so on and so forth. Well most of us think that these are just games to play with. But Dragon NaturallySpeaking is truly different.
It can control windows command buttons, mouse clicks and type in keyboard shortcuts as and when you say. This makes up for a great feature as you can use this to speed up your work. You could be writing an e-mail to a friend or you could be typing in your text editor, you might be needing to align your text, capitalize or even italicize it while you might be busy with something else.
I have composed the video of me using the software and I totally feel it is worth the money. It is common thinking that you can type too fast and typing is the best way to do it. But to those who think so I say you’ve seen nothing until you’ve seen this software.
And guess what this post has been created using the same. Enjoy.


Have you always wanted to get more out of your machine. Wanna see how to boost system speed and in turn speed up your activity over your computer?? Look No further. This is no publicity for a spyware mounted software that i will ask you to install and pay me for it. Instead i will tell you some tweaks that you can try yourself and feel the difference.

  1. Disable Extra Startup Programs

    There are certain programs that Windows will start every time you
    boot up your system, and during the startup phase, they’re all
    competing for a slice of your CPU speed. Extra or unwanted items
    in the startup list will definitely increase your startup time, perhaps
    by several minutes. Some common examples are things related to
    AOL, RealPlayer, Napster, instant messengers, and video managers
    If you’re not sure about an item, no big deal. You can turn it off,
    restart your PC, and see if everything seems to work. If not,
    you can always go back and re-enable an item in the Startup list.

    Here are is what you have to do:

    1. Go to Start button  Run
    2. Type “msconfig”, without quotations
    3. Hit enter key or click the OK button
    4. A System Configuration Utility window will show up
    5. Click the Startup tab
    6. In the Startup tab you will see several boxes and some of them
      will selected (checked). All you have to do is to uncheck
      extra items that are of no use. If you run an antivirus
      program it is not recommended to uncheck it.
    7. After making you choices press the OK button, you will be
      prompted to restart computer to apply changes.
    8. After restarting your computer a dialogue will be displayed.
      You can check the option for not showing this dialogue every
      time your PC reboots.

  2. Optimize Display Settings

    Windows XP can look sexy but displaying all the visual items can
    waste system resources. To optimize:

    1. Click the Start button
    2. Select Control Panel
    3. Double-click the System icon
    4. Click the Advanced tab
    5. In the Performance box click Settings
    6. Leave only the following ticked:
      1. Show shadows under menus
      2. Show shadows under mouse pointer
      3. Show translucent selection rectangle
      4. Use drop shadows for icons labels on the desktop
      5. Use visual styles on windows and buttons
    7. Finally, click Apply and OK

  3. Optimize Folder Switching And File Browsing

    You may have noticed that every time you open “My Computer” to
    browse folders that there is a slight delay. This is because Windows
    XP automatically searches for network files and printers every time
    you open Windows Explorer. To fix this and to increase browsing
    speed significantly:

    1. Double-click on My Computer
    2. Click the Tools menu
    3. Select Folder Options
    4. Click on the View tab.
    5. Uncheck the Automatically search for network folders and
      printers check box
    6. Click Apply
    7. Click OK
    8. Reboot your computer

  4. Disable File Indexing

    Indexing Services is a small little program that uses large amounts
    of memory and can often make a computer endlessly loud and
    noisy. This system process indexes and updates lists of all the files
    that are on your computer. It does this so that when you do a searc
    for something on your computer, it will search faster by scanning th
    index lists. If you don’t search your computer often, this system
    service is completely unnecessary.
    To disable do the following:

    1. Click Start button
    2. Select the Control Panel
    3. Double-click Add/Remove Programs
    4. Click the Add/Remove Window Components icon on the left
      side of the window
    5. This may take a few seconds to load. Be patient.
    6. Look for the “Indexing Services” component in the list
    7. Uncheck the Indexing Services
    8. Click Next
    9. Click Finish

  5. Remove Un-Used Programs
    & Files

    You may have a bunch of software packages on your hard drive that
    are no longer needed, or they were gratuitously installed when you
    downloaded some other package. Toolbars, file-sharing
    programs, free email enhancers, online shopping “companions”
    and download managers are notorious for this practice. These
    uninvited guests can put a big drag on your startup time, cause web
    pages to load slowly, and generally bog down your computer.

    Well we all know how do that… so i’ll pass on that..

I hope that with these tweaks done you’ll certainly feel your computer to be lighter and more responsive as ever. You will soon realize that its better to have more speed than the eye candy of the OS. HAPPY WORKING


: The Rootkit Arsenal: Escape and Evasion in the Dark Corners of the System

  • Pages: 908 pages
  • Publisher: Jones & Bartlett Publishers (May 4, 2009)
  • Language: English
  • Fanatics Like Me : Click Here


Wanna play the all famous game…… Here is the setup for the game that i built. Want a Preview…. Scroll

here are the source files to it.

visual basic

I developed this conference client just for me in my free time….
v Hybrid architecture (Client Server and P2P) based Instant Messenger.
v It has features like text messaging with text formatting inclusive of smiley, audio and video chat.
v It has a Desktop Sharing feature wherein users can view/share their desktop among themselves.
v It is cross platform as it is based on Java and it uses MySql as backend. It is dependent upon JMF (Java Media Framework)

here is a video in which i demonstrate how to go about using my project.

I have also included a log file. Please send me the log file in case you encounter any errors.

Here are the executables.