Search This Blog

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, 14 July 2011

WAV file player in C

WAV file player in C

/****************************************************************
 WARNING: You need a HUGE memory model to run this.
****************************************************************/

//Include files
#include "ALLOC.H"
#include "DOS.H"
#include "CONIO.H"
#include "STDIO.H"


void main()
{
 char *name;
 printf("
 Enter the file name...:");
 scanf("%s",name);


 playwav(name,1.0);

}


void playwav(char wavefile[14],float delaytime);
struct WaveData {
  unsigned int SoundLength, Frequency;
  char *Sample;
};


struct HeaderType {
  long         RIFF;      //RIFF header
  char         NI1 [18];  //not important

  unsigned int Channels;  //channels 1 = mono; 2 = stereo
  long         Frequency; //sample frequency
  char         NI2 [6];   //not important
  char         BitRes;    //bit resolution 8/16 bit
  char         NI3 [12];  //not important
} Header;





struct WaveData Voice;         //Pointer to wave file


unsigned int    Base;          //Sound Blaster base address


char            WaveFile [25]; //File name for the wave file to be played


/****************************************************************
Checks to see if a Sound Blaster exists at a given address, returns true if Sound Blaster found, false if not.
****************************************************************/

int ResetDSP(unsigned int Test)
{
  //Reset the DSP
  outportb (Test + 0x6, 1);
  delay(10);
  outportb (Test + 0x6, 0);
  delay(10);
  //Check if (reset was succesfull
  if ((inportb(Test + 0xE) & 0x80 == 0x80) && (inportb(Test + 0xA) ==
0xAA))
  {
    //DSP was found
    Base = Test;
    return (1);
  }
  else
    //No DSP was found
    return (0);
}

/****************************************************************
Send a byte to the DSP (Digital Signal Processor) on the Sound Blaster
****************************************************************/

void WriteDSP(unsigned char Value)
{
  //Wait for the DSP to be ready to accept data
  while ((inportb(Base + 0xC) & 0x80) == 0x80);
  //Send byte

  outportb (Base + 0xC, Value);
}


/****************************************************************
Plays a part of the memory
****************************************************************/

void PlayBack (struct WaveData *Wave)
{
  long          LinearAddress;
  unsigned int  Page, OffSet;
  unsigned char TimeConstant;


  TimeConstant = (65536 - (256000000 / Wave->Frequency)) >> 8;
  WriteDSP(0x40);                  //DSP-command 40h - Set sample
frequency
  WriteDSP(TimeConstant);          //Write time constant


  //Convert pointer to linear address
  LinearAddress = FP_SEG (Wave->Sample);
  LinearAddress = (LinearAddress << 4) + FP_OFF (Wave->Sample);
  Page = LinearAddress >> 16;      //Calculate page
  OffSet = LinearAddress & 0xFFFF; //Calculate offset in the page

  /****************
      Note - this procedure only works with DMA channel 1
  ****************/

  outportb (0x0A, 5);              //Mask DMA channel 1
  outportb (0x0C, 0);              //Clear byte pointer
  outportb (0x0B, 0x49);           //Set mode

  /****************
      The mode consists of the following:
      0x49 = binary 01 00 10 01
                    |  |  |  |
                    |  |  |  +- DMA channel 01
                    |  |  +---- Read operation (the DSP reads from memory)
                    |  +------- Single cycle mode
                    +---------- Block mode
  ****************/


  outportb (0x02, OffSet & 0x100); //Write the offset to the DMA controller
  outportb (0x02, OffSet >> 8);


  outportb (0x83, Page);           //Write the page to the DMA controller


  outportb (0x03, Wave->SoundLength & 0x100);
  outportb (0x03, Wave->SoundLength >> 8);


  outportb (0x0A, 1);              //Unmask DMA channel



  WriteDSP(0x14);                  // DSP-command 14h - Single cycle
playback
  WriteDSP(Wave->SoundLength & 0xFF);
  WriteDSP(Wave->SoundLength >> 8);
}


/**************************************************************
Loads a wave file into memory. This procedure expects a _very_ standard wave header. It doesn't perform much error checking.
**************************************************************/

int LoadVoice (struct WaveData *Voice, char *FileName)
{
  FILE *WAVFile;


  //If it can't be opened...
  WAVFile = fopen(FileName, "rb");
  if (WAVFile == NULL) {
    //..display error message


    return (0);
  }


  //Return length of file for sound length minus 48 bytes for .WAV header
  fseek(WAVFile, 0L, SEEK_END);
  Voice->SoundLength = ftell (WAVFile) - 48;
  fseek(WAVFile, 0L, SEEK_SET);


  //Check RIFF header
  if (Voice->SoundLength > 32000) {




    if (Voice->SoundLength > 64000) {


      Voice->SoundLength = 64000;
    }
  }
  free(Voice->Sample);
  Voice->Sample = (char *)malloc(Voice->SoundLength); //Assign memory
  if (!Voice->Sample) {

    return (0);
  }


  //Load the sample data
  fread(&Header, 46, 1, WAVFile);


  //Check RIFF header
  if (Header.RIFF != 0x46464952) {
    printf ("Not a wave file
");
    return (0);
  }


  //Check channels
  if (Header.Channels != 1) {
    printf ("Not a mono wave file
");
    return (0);
  }


  //Check bit resolution
  if (Header.BitRes != 8) {
    printf ("Not an 8-bit wave file
");
    return (0);
  }


  Voice->Frequency = Header.Frequency;


  //Load the sample data
  fread(Voice->Sample, Voice->SoundLength + 2, 1, WAVFile);


  fclose (WAVFile); //Close the file


  return (1);
}


void playwav (char wavefile[14], float delaytime  )
{
  delaytime=1.0;
  if (ResetDSP (0x220)) {
    //at 220h
    printf ("");
  } else {
    if (ResetDSP (0x240)) {

      //at 240h
      printf ("");
    } else {
      //or none at all
      printf ("");
      return;
    }
  }




  //Load wave file
  if (LoadVoice (&Voice, wavefile)) {


    //Start playback
    PlayBack (&Voice);


    delay(delaytime*1000);


    //Stops DMA-transfer
    WriteDSP (0xD0);
  }
}

Read more: http://cmagical.blogspot.com/2011/03/wav-file-player-in-c.html#ixzz1S6BOnfaA 
Under Creative Commons License: Attribution Non-Commercial No Derivatives

Thursday, 30 June 2011

How CAPTCHA Works? And a Simple Script in PHP

How CAPTCHA Works? And a Simple Script in PHP

[Note : For this post I'm presuming that you are familiar with CAPTCHA, if not please read this Introduction to CAPTCHA]
CAPTCHA
Today we are going to see how CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) works and how it minimizes automatic sign-up of forms. We will also be creating a simple CAPTCHA script in PHP to illustrate this.
CAPTCHA Example

CAPTCHA Example

Basically CAPTCHA works in the following manner:

1) Create Random Value : Some random string is generated, random values are often hard to guess and predict.

2) Generate an Image : Images are used as these are generally a lot harder to read for computers while being nice and readable to humans. This is also the most important step as simple text in images can be read (and CAPTCHA cracked) quite easily. To make it difficult for them, developers employ different techniques so that the text in the image becomes hard to read for computers. Some create zig-zag lines for background while others twist-and-turn individual characters in the image. Possibilities are many and new techniques are being developed all the time as crackers are always into finding ways to break them.

3) Store it : The random string generated (which is also in the image) is stored for matching the user input. The easiest way to do so is to use the Session variables.

4) Matching : After the above step, the CAPTCHA image is generated and shown on some form which we want to protect from being abused. The users fills in the form along with the CAPTCHA text and submits it. Now we have the following:

  1. All submitted form data.
  2. CAPTCHA string (from form), input by user.
  3. CAPTCHA string (real one, generated by us), from session variable. Session variable is generally used as it can keep stored values across page requests. Here, we needed to preserve stored values from one page (form page) to another (action page-that receives form data).


5) If both match, it's okay otherwise not, in that case we can give the user a message that the CAPTCHA they had entered was wrong and their form could not be submitted. You could also ask them to verify it again.

The following image might illustrates this better:
How CAPTCHA works?
From the above image it's quite clear that when someone requests the form page, the CAPTCHA text is generated and sent back to requesting user, but only in the form of an image. If the requester is a human he'd not have much difficulty reading the image and inputting the text when asked but if it's a bot it might face difficulties guessing whats in the image. In the next step when we match the string generated and the one the user had input, we can restrict automated form submissions.


The following is the code that does this, it'll just output the CAPTCHA image to the browser when the script is requested:

<?php


// The number of characters you
// want your CAPTCHA text to have
define('CAPTCHA_STRENGTH', 5);


/****************************
 *        INITIALISE        *
 ****************************/
// Tell PHP we're going to use
// Session vars
session_start();


// Md5 to generate the random string
$random_str = md5(microtime());


// Trim required number of characters
$captcha_str = substr($random_str, 0, CAPTCHA_STRENGTH);


// Allocate new image
$width = (CAPTCHA_STRENGTH * 10)+10;
$height = 20;


$captcha_img =ImageCreate($width, $height);


// ALLOCATE COLORS
// Background color-black
$back_color = ImageColorAllocate($captcha_img, 0, 0, 0);


// Text color-white
$text_color = ImageColorAllocate($captcha_img, 255, 255, 255);


// Line color-red
$line_color = ImageColorAllocate($captcha_img, 255, 0, 0);


/****************************
 *     DRAW BACKGROUND &    *
 *           LINES          *
 ****************************/
// Fill background color
ImageFill($captcha_img, 0, 0, $back_color);


// Draw lines accross the x-axis
for($i = 0; $i < $width; $i += 5)
    ImageLine($captcha_img, $i, 0, $i, 20, $line_color);


// Draw lines accross the y-axis
for($i = 0; $i < 20; $i += 5)
    ImageLine($captcha_img, 0, $i, $width, $i , $line_color);


/****************************
 *      DRAW AND OUTPUT     *
 *          IMAGE           *
 ****************************/
// Draw the random string
ImageString($captcha_img, 5, 5, 2, $captcha_str, $text_color);


// Carry the data (KEY) through session
$_SESSION['key'] = $captcha_str;


// Send data type
header("Content-type: image/jpeg");


// Output image to browser
ImageJPEG($captcha_img);


// Free-Up resources
ImageDestroy($captcha_img);


?>


*********************

Sunday, 19 June 2011

What is an Applet ??


What is an Applet ??


Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document. After an applet arrives on the client, it has limited access to resources so that it can produce a graphical user interface and run complex computations without introducing the risk of viruses or breaching data integrity.



Two Types of Applets :-
It is important to state at the outset that there are two varieties of applets. The first are those based directly on the Applet class described in this chapter. These applets use the Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no GUI at all). This style of applet has been available since Java was first created.

The second type of applets are those based on the Swing class JApplet. Swing applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface than does the AWT. Thus, Swing-based applets are now the most popular.

However, traditional AWT-based applets are still used, especially when only a very simple user interface is required.Thus, both AWT- and Swing-based applets are valid. Because JApplet inherits Applet, all the features of Applet are also available in JApplet


(Note : I will only discuss AWT-Based applets here.)

The HTML APPLET Tag :-

To use an applet, it is specified in an HTMLfile. One way to do this is by using the APPLET tag. (The OBJECT tag can also be used, but Sun currently recommends the APPLET tag). The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTMLfile.
For example:

<html>
<body>
<applet code="MyApplet.class" width=200 height=60>
</applet>
</body>
</html>

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

Full Syntax of APPLET Tag :-

The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are
optional.

< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
</APPLET>

Let’s take a look at each part now.

CODEBASE : CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on the host from which the HTML document was read.

CODE : CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set.

ALT : The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets. This is distinct from the alternate HTML you provide for browsers that don’t support applets.

NAME : NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface.

WIDTH and HEIGHT : WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.

ALIGN : ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

VSPACE and HSPACE : These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet. They’re treated the same as the IMG tag’s VSPACE and HSPACE attributes.

PARAM NAME and VALUE : The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.



Applet Architecture :-
An applet is a window-based program. As such, its architecture is different from the console-based
programs. If you are familiar withWindows programming, you will be right at home writing applets. If not, then there are a few key concepts you must understand.

First, applets are event driven. An applet resembles a set of interrupt serviceroutines. Here is how the process works. An applet waits until an event occurs. The run-time system notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return. This is a crucial point. For the most part, your applet should not enter a “mode” of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the run-time system. In those situations in which your applet needs to perform a repetitive task on its own (for example,
displaying a scrolling message across its window), you must start an additional thread of execution.

Second, the user initiates interaction with an applet—not the other way around. As you know, in a nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. When the user interacts with one of the controls(buttons,checkboxes,radiobuttons,etc.), an event is generated. While the architecture of an applet is not as easy to understand as that of a console-based program, Java makes it as simple as possible.



An Applet Skeleton (of AWT-based applets) :-
All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them.

AWT-based applets will also override the paint( ) method, which is defined by the AWT Component class. This method is called when the applet’s output must be redisplayed.

(Note : Swing-based applets use a different mechanism to accomplish this task.).

The five methods can be assembled into the skeleton shown here:

// An Applet skeleton of AWT-based applets
import java.awt.*;
import java.applet.*;
/*
<html>
<body>
<applet code="AppletSkel.class" width=300 height=100>
</applet>
</body>
</html>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}


/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}


// Called when the applet is stopped.
public void stop() {
// suspends execution
}


/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}


// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}



Applet Initialization and Termination :-
It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the following methods are called, in this sequence:

1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

1. stop( )
2. destroy( )

Let’s look more closely at these methods.

init( )
The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( )
The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.

destroy( )
The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

Overriding update( )
In some situations, your applet may need to override another method defined by the AWT, called update( ). This method is called when your applet has requested that a portion of its window be redrawn. The default version of update( ) simply calls paint( ). However, you can override the update( ) method so that it performs more subtle repainting. In general, overriding update( ) is a specialized technique that is not applicable to all applets.


How to Compile and Execute an Applet ?
1) To compile and execute an applet JDK (Java Development Kit) is required. If you dont have it then Download it from here and install it.

2) Let's take the following example. Java code file where we write the applet code which executes when an applet is started or initiated.

import java.applet.Applet;
import java.awt.*;


// Applet code for the "Hello, world!" example.
// This should be saved in a file named as "HelloWorld.java".


public class HelloWorld extends Applet {

// This method is mandatory, but can be empty (i.e., have no actual code).
   public void init() { }


  // This method is mandatory, but can be empty.(i.e.,have no actual code).
  public void stop() { }


  // Print a message on the screen (x=20, y=10).
  public void paint(Graphics g) {
    g.drawString("Hello, world!", 20,10);


  // Draws a circle on the screen (x=40, y=30).
    g.drawArc(40,30,20,20,0,360);
  }
}

3) Save this file with same name of the class. Here the class is HelloWorld. Change the file extension to .java . So,we save this file as HelloWorld.java . Copy paste this file to the directory " C:\Program Files\Java\jdk1.6.0_21\bin "

4) Now open cmd.exe and type " cd C:\Program Files\Java\jdk1.6.0_21\bin " .

5) Now type " javac HelloWorld.java " and press ENTER.

6) After compiling you java code for an applet you will see a file HelloWorld.class which will be used in the 'code' attribute of the APPLET tag.

7) Now open new notepad and copy paste the following code:

<HTML>
<HEAD>
<TITLE>HelloWorld_example.html</TITLE>
</HEAD>
<BODY>
<H1>A Java applet example</H1>
<P>Here it is: <APPLET code="HelloWorld.class" WIDTH="200" HEIGHT="40">
This is where HelloWorld.class runs.</APPLET></P>
</BODY>
</HTML>

Save this file as HelloWorld.html and also move this file to the same directory " C:\Program Files\Java\jdk1.6.0_21\bin ".

8) Now run this HelloWorld.html file and you will see your applet running.

9) You can also use appletviewer to view your applet running. To do this just open cmd.exe go to the same directory where your HelloWorld is saved ,i.e., " C:\Program Files\Java\jdk1.6.0_21\bin " and then type "appletviewer HelloWorld.html". It will run your applet in an appletviewer.

Advantages :-

  • It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by most web browsers.
  • The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the Java Runtime Environment (JRE) the client will be forced to wait during the large download.
  • Most web browsers cache applets, so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh).
  • It can move the work from the server to the client, making a web solution more scalable with the number of users/clients.
  • If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions.
  • The applet naturally supports the changing user state, such as figure positions on the chessboard.
  • Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions.
  • An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees.
  • Java applets are fast - and can even have similar performance to native installed software.

Disadvantages :-

  • It requires the Java plug-in.
  • Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plug-in.
  • As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals.
  • Some applets require a specific JRE. This is discouraged.
  • If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete.
  • Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy.
  • Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document.

Security :-

There are two applet types with very different security models: unsigned applets and signed applets

Unsigned Applets :-
Limits on unsigned applets are understood as "draconian",they have no access to the local filesystem and web access limited to the applet download site; there are also many other important restrictions. For instance, they cannot access all system properties, use their own class loader, call native code, execute external commands on a local system or redefine classes belonging to core packages included as part of a Java release. While they can run in a standalone frame, such frame contains a header, indicating that this is an untrusted applet. Successful initial call of the forbidden method does not automatically create a security hole as an access controller checks the entire stack of the calling code to be sure the call is not coming from an improper location.
As with any complex system, multiple security problems have been discovered and fixed since Java was first released. Some of these (like the Calendar serialization security bug) persisted for many years with nobody being aware. However it seems that most (if not all) security holes are closed before they can be exploited on a larger scale.
Some studies mention applets crashing the browser or overusing CPU resources but these are classified as nuisances and not as true security flaws. However, unsigned applets may be involved in combined attacks that exploit a combination of multiple severe configuration errors in other parts of the system. An unsigned applet can also be more dangerous to run directly on the server where it is hosted because while code base allows it to talk with the server, running inside it can bypass the firewall. An applet may also try DoS attacks on the server where it is hosted but usually people who manage the web site also manage the applet, making this unreasonable. Communities may solve this problem via source code review or running applets on a dedicated domain.
The unsigned applet can also try to download malware hosted on originating server. However it could only store such file into temporary folder (as its transient data) and has no means to complete the attack by executing it. There were attempts to use applets for spreading Phoenix and Siberia exploits this way, while these exploits do not use Java internally and were also distributed in several other ways.
As of 1999, no real security breaches involving unsigned applets have ever been publicly reported. Using an up-to-date Web browser is usually enough to be safe against the known direct attacks from unsigned applets.

Signed Applets :-
A signed applet contains a signature that the browser should verify through a remotely running, independent certificate authority server. Producing this signature involves specialized tools and interaction with the authority server maintainers. Once the signature is verified, and the user of the current machine also approves, a signed applet can get more rights, becoming equivalent to an ordinary standalone program. The rationale is that the author of the applet is now known and will be responsible for any deliberate damage. This approach allows applets to be used for many tasks that are otherwise not possible by client-side scripting. However, this approach requires more responsibility from the user, deciding whom he or she trusts. The related concerns include a non-responsive authority server, wrong evaluation of the signer identity when issuing certificates, and known applet publishers still doing something that the user would not approve of. Hence signed applets that appeared from Java 1.1 may actually have more security concerns.

Self signed :-
Self-signed applets, which are applets signed by the developer themselves, may potentially pose a security risk; java plugins provide a warning when requesting authorization for a self-signed applet, as the function and safety of the applet is guaranteed only by the developer itself, and has not been independently confirmed. Such self-signed certificates are usually only used during development prior to release where third-party confirmation of security is unimportant, but most applet developers will seek third-party signing to ensure that users trust the applet's safety.

***********************

Sunday, 5 June 2011

Sine Wave and Cosine Wave in C/C++ shown graphically


Sine Wave and Cosine Wave in C/C++ shown graphically:-


#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<process.h>
#include<math.h>
#include<dos.h>
#define PI 3.1416
int main()
{
int gdriver=DETECT,gmode,errorcode;
int x,x1;
double y,y1;
int a;
char ch;
clrscr();
printf("Initiating graphics mode press any key to continue");
initgraph(&gdriver,&gmode,"C:\\TC\\BGI\\");
errorcode=graphresult();
if(errorcode!=0)
{
        printf("ERROR:%s",grapherrormsg(errorcode));
getch();
exit(1);
}


printf("enter the ampiltude:");    /*only enter 1 or -1 otherwise it will go out of the screen*/
scanf("%d",&a);                         //you can also remove this value.


for(x=0,x1=0;!(kbhit());x++,x1++)
{
y=a*sin(x*PI/180);            //sine wave equation used to generate sine wave.
if(y>0)
{
putpixel(x,y*150+200,YELLOW);
}
if(y<0)
{
putpixel(x,y*150+200,YELLOW);
}


y1=a*cos(x1*PI/180);          //cosine wave equation used to generate cosine wave.
if(y1>0)
{
putpixel(x1,y1*150+200,WHITE);
}
if(y1<0)
{
putpixel(x1,y1*150+200,WHITE);
}
delay(10);
}
getch();
closegraph();
return 0;
}

Thursday, 26 May 2011

Procedure Oriented Programming(POP) vs Object Oriented Programming(OOP)

Procedure Oriented Programming (POP) :-

Conventional programming using high level languages such as COBOL,FORTRAN and C, is commonly known as procedure oriented programming(POP). In the procedure oriented approach, the problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. The primary focus is on functions.
Typical structure of procedure oriented programs
Procedure oriented programming basically consists of writing a list of instructions(or actions) for the computer to follow, and organizing these instructions into groups known as functions.While we concentrate on the development , very little attention is given to the data that are bing used by various functions.

In a multi-function program, many important data items are placed as global so that they may be accessed by all functions. Each function may have its own local data. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in.
Relationship of data and functions in procedural programming
Another serious drawback with the procedural approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really correspond to the elements of the problem.

Some characteristics of Procedure Oriented Programming are :-

1) Emphasis is on doing things(algorithms).
2) Large programs are divided into smaller programs known as functions.
3) Most of the functions share global data.
4) Data more openly around the system from function to function.
5) Functions transform data from one form to another.
6) Employs top-down approach in program design.

-----------------------------------------------------------------------------------------------------------

Object Oriented Programming (OOP) :-

The major motivating factor in the invention of object oriented is to remove some of the flaws encountered in the procedural oriented approach. Object oriented programming treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modifications from outside functions.

Object oriented programming allows a decomposition of a problem into a number entities called objects and then builds data and functions around these objects. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects.
Organization of data and functions in object oriented programming
The object oriented programming can be defined as an " approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand ". Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modifications.

Some characteristics of Object Oriented Programming are :-

1) Emphasis is on data rather than procedures or algorithms.
2) Programs are divided into what are known as objects.
3) Data structures are designed such that characterize the objects.
4) Functions that operate on the data are tied together in the data structure.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added whenever necessary.
8) Follows bottom-up approach in program design.

------------------------------------------------------------------------------------------------------------

Benefits of Object Oriented Programming over Procedure Oriented Programming :-

1) Through inheritance, we can eliminate redundant code and extend the use of existing classes which is not possible in procedure oriented approach.

2) We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch which happens procedure oriented approach. This leads to saving of development time and higher productivity.

3) The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.

4) It is possible to have multiple instances of object to co-exist without any interference.

5) It is possible to map objects in the problem domain to those in the program.

6) It is easy to partition the work in a project based on objects .

6) The data-centered design approach enables us to capture more details of a model in implementable from.

7) Object oriented systems can be easily upgraded from small to large systems.

8) Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler.

9) Software complexity can be easily managed.

*************
Related Posts Plugin for WordPress, Blogger...