Sunday, May 20, 2012

Public Key Infrastructure Fundamental (Part 2)

This post is a continuation (par 2) of my post that can be found here. In this post, I am going to discuss about Public Key and Private Key.



Public Key

Public key can be defined as a value provided by some designated authority as an encryption key that, combined with a private key derived from the public key, can be used to effectively encrypt messages and digital signatures. Private key will be discussed below.


Private Key

Private key can be defined as an encryption/decryption key known only to the party or parties that exchange secret messages.

Public-key Encryption
Source: Globus
As you can see from the above image, the public-key and private-key are both used in the encryption process in the PKI. One think you need to remember, we use the receiver's public-key as the key to encrypt the message. On the other side, the receiver, will decrypt the message using the private-key that he has.

To simplify things:
  • Think of a public key as being the lock. It’s not actually a key, it’s a padlock you can make lots of copies of and distribute wherever you want.
  • Think of a private key as being the actual key. This is what you use to open the padlock that is stored on the other machine. Just like a regular key you keep it secret, safe, and out of the wrong hands.

Public-key Encryption
Source: Wikimedia

In an asymmetric key encryption scheme, anyone can encrypt messages using the public key, but only the holder of the paired private key can decrypt. Security depends on the secrecy of that private key.

Thursday, May 17, 2012

Simple Paging

Paging literally means making data displayed in multiple pages. Paging is used specially for website, where displaying large amount of data can be so troublesome by making the downloaded data bigger and thus increasing the response time.

Paging can be done in many ways. In this tutorial, I would like to show you a very simple method we can use to do the paging. Here, we just need to enable the user to move to the next page (if any) and back to the previous page (if any). Also, for the sake of simplicity, I will use dummy data stored hard-codedly into an array. However, the concept is similar. OK, let's start !!!

    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
First of all, we define the maximum number of items to show per page. In this tutorial, I set the maximum number of items to show per page to 10 items. This value can be changed according to your need. However, sometimes, this value can also be changed by users as to accommodate his preferences. Sometimes, users' screen is big enough to show large count of data per page. After that, I created dummy data. Please not that in reality, mostly data stored in the database.

    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
The next step, I created a helper function to ease the retrieval of data. All the retrieval data logic put into that function. Also note that the content of that function must be changed according to the way you retrieve the data. If you use SQL to retrieve the data, you can use the SQL Query to do the paging automatically. Here, I will show you an example of how to filter data retrieved using MySQL SQL command. Please refer to your DBMS documentation for command supported in your own DBMS.
SELECT <columns> FROM <table> LIMIT <limit>, <offset>

    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
One part we need to handle is to get the requested page number sent by the user. We can easily pass it using query string passed into the server. Note that, for security sake, you should always check for the validity of values passed by the user, in case they want to inject something bad into your server by using the weakness or security hole you created unintentionally by your bad code. For this tutorial, I omit that checking.

As you can see, I use "p" variable that is sent to server using HTTP GET method to store the requested page number. If, the "p" variable is empty, I assume that the user is requesting data in the first page. So, all required data is ready, I now just need to display the data to the user.
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page since the minimum page is 1 and we are currently not at page 1 */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page since the current page is still less than the maximum page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>
I think the printing process is very common. I don't really need to explain it a bit deeper, I suppose. The logic you need to have a look is actually the checking whether we need to display the "Prev. Page" link and "Next Page" link or not. The inline documentation should explain better. See below for the full source code.
<?php
    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
    
    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
        
    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
    
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>


That's it. Hope you enjoy the tutorial and can gain benefit from it. Remember, this is a very simple one. You can also use another way to do paging by enabling user to go to certain page directly. Or, if you are a professional programmer wannabe, don't worry, there are many frameworks out there that handle all the nifty-gritty in doing beautiful paging mechanism.

Happy code fellas....

Tuesday, May 1, 2012

Faster Prime Number Checker Algorithm

Checking for prime number is actually a simple one, but can sometimes be very tricky for big number. Though there exists more powerful algorithm to check for prime number, here I want to show you one simple algorithm that is proved to be fast enough.


//
//  main.cpp
//  Prime Number Checker
//
//  Created by Handra on 5/1/12.
//  Copyright (c) 2012 Handra. All rights reserved.
//

#include <iostream>
#include <cmath>

using namespace std ;

/* Function prototype */
int isPrime ( int number ) ;

int main ( int argc , const char * argv [ ] )
{
    int number = 12 ;
    
    cout << "Is Prime: " << isPrime ( number ) << endl ;
    
    return 0 ;
}

int isPrime ( int number )
{
    /* Every number below 2 is not prime */
    if ( number < 2 )
        return 0 ;
    
    /* Calculating the limit for denominator */
    int limit = ( int ) sqrt ( number ) ;
    
    /* Start the denominator from 2. We know that every number divided by 1 must have 0 carrier */
    for ( int i = 2 ; i <= limit ; i ++ )
        if ( number % i == 0 )
            return 0 ;
    
    return 1 ;
}

The above code is written using C++. Of course you can implement it using any other programming language.


So, as you can see within the function "isPrime", we first check whether the number is less than 2 or not. We know, by common sense and definition, that numbers below 2 are not considered as prime. Hence, we check that if the number is less that 2, then return 0, or false.


If the number is 2 or higher, then we need to check for it's primeness. First of all, we need to calculate the limit of the number we should use to divide the to-check-for-primeness-number. From the mathematical theorem, we know that the maximum factor value, that is not the same with the number, is the square root of the number. Proving of this theorem is beyond this post though. In C++, we use function sqrt that is defined in header cmath.


After that, the rest we need to do is loop starting from 2 to the limit to check whether there is another factor (besides 1 and the number itself). If any is found, then just return 0 (false) since there should be no other factor within 2 and the limit (inclusive). Otherwise, return 1 (true).


Hope this helps and happy coding.. :)