S.NO 1.
CHAPTERS INTRODUCTION
PAGE NO
1.1 Project Overview 1.2 Module Description SYSTEM ANALYSIS AND STUDY
2.
2.1 Existing System 2.2 Proposed System SYSTEM CONFIGURATION
3.
3.1 Hardware Requirement 3.2 Software Requirement ABOUT SOFTWARE
4. 5.
4.1 Front End:Vb.Net 2010 4.2 Back End:Sql Server 2008 SYSTEM DESIGN 5.1 Input Design 5.2 Output Design 5.3 Data Flow Diagram SYSTEM TESTING
6.
7. 8. 9. 10.
6.1 Unit Testing 6.2 Integration Testing 6.3 Validation testing SYSTEM IMPLEMENTATION CONCLUSION BIBLIOGRAPHY APPENDIX A. Screen Shot B. Source Code
ABSTRACT Network based intruders seldom attack their victims directly from their own computer. Often, they stage their attacks through intermediate “stepping stones” in order to conceal their identity and origin. To identify the source of the attack behind the stepping stone(s), it is necessary to correlate the incoming and outgoing flows or connections of a
stepping stone. To resist attempts at correlation, the attacker may encrypt or otherwise manipulate the connection traffic. Timing based correlation approaches have been shown to be quite effective in correlating encrypted connections. However, timing based correlation approaches are subject to timing perturbations that may be deliberately introduced by the attacker at stepping stones. In this project, our watermark-based approach is “active” in that It embeds a unique watermark into the encrypted flows by slightly adjusting the timing of selected packets. The unique watermark that is embedded in the encrypted flow gives us a number of advantages over passive timing based correlation in resisting timing perturbations by the attacker. A two-fold monotonically increasing compound mapping is created and proved to yield more distinctive visible watermarks in the watermarked image. Security protection measures by parameter and mapping randomizations have also been proposed to deter attackers from illicit image recoveries.
1.1.MODULE DESCRIPTION No of Modules 1)Watermark Bit Embedding and Decoding 2)Correlation Analysis
3)Watermark Tracing Model 4)Parameter & Mapping Randomization
Module Description: 1).Watermark Bit Embedding and Decoding:
Generally, watermarking involves the selection of a watermark carrier, and the design of two complementary processes: embedding and decoding.
In the registration, we collect the watermark signature… The watermark embedding process inserts the information by a slight modification of some property of the carrier.
The watermark decoding process detects and extracts the watermark (equivalently, determines the existence of a given watermark).
To correlate encrypted connections, we propose to use the inter-packet timing as the watermark carrier property of interest.
The embedded watermark bit is guaranteed to be not corrupted by the timing perturbation. If the perturbation is outside this range, the embedded watermark bit may be altered by the attacker.
2) Correlation Analysis:
In practice, the number of packets available is the fundamental. Limiting factor to the achievable effectiveness of our watermark based correlation.
This set of experiments aim to compare and evaluate the correlation effectiveness of our proposed active watermark based correlation and previous passive timing-based correlation under various timing perturbations. B
y embedding a unique watermark into the inter-packet timing, with sufficient redundancy, we can make the correlation of encrypted flows substantially more robust against random timing perturbations.
We can correlate the watermark signatures and identify it’s the positive or negative correlation, if positive occurs it detect it is the authenticated user otherwise, if negative occurs it detect it is an Intruder.
3) Watermark Tracing Model:
The watermark tracing approach exploits the observation that interactive connections are bidirectional. The idea is to watermark the backward traffic (from victim back to the attacker) of the bidirectional attack connections by slightly adjusting the timing of selected packets.
If the embedded watermark is both robust and unique, the watermarked back traffic can be effectively correlated and traced across stepping stones, from the victim all the way back to the attacker, assuming the attacker has not gained full control on the attack target, the attack Target will initiate the attack tracing after it has detected the attack.
Specifically, the attack target will watermark the backward traffic of the attack connection, and inform across the network about the watermark.
The stepping stone across the network will scan all traffic for the presence of the indicated watermark, and report To the target if any occurrences of the watermark are detected.
4) Parameter & Mapping Randomization:
One simple technique to achieve this is to use a secret key to generate a pseudorandom sequence of numerical values and add them to either or both of and for the pixels in the watermarking area. This technique is hereinafter referred to as parameter randomization.
This parameter exchange does not affect the effectiveness of lossless recoverability, because we can now recover the original pixel values by the compound mappings. We will refer to this technique in the sequel as mapping randomization.
We may also combine this technique with the parameter randomization technique to enhance the security. Finally, the Authenticated user take the file in zip format with proper password.
2.1.SYSTEM ANALYSIS AND STUDY Systems analysis is the study of sets of interacting entities, including computer systems analysis. This field is closely related to requirements analysis or operation research. It is also "an explicit formal inquiry carried out to help someone (referred to as the decision maker) identify a better course of action and make a better decision than he might otherwise have made.
Another view outlines a phased approach to the process. This approach breaks systems analysis into 5 phases: Scope Definition Problem analysis Requirements analysis Logical design Decision analysis
Scope Definition A project management term for the combined objectives and requirements necessary to complete a project. Properly defining the scope of a project allows a manager to estimate costs and the time required to finish the project.
Problem Analysis Problem analysis is a set of analytic tasks meant to increase the designers' understanding of an unbalanced situation, for the sake of designing a change to the situation that will have better balance. It is important to note that we are not designing at this stage.
We are not looking at potential solutions.
We are looking the current situation and determining which other situation would be preferred. As engineers, we focus only on the technical aspects of resolving imbalances, but
recognize that there are other non-technical aspects that are equally important.
Requirement Analysis Requirements analysis in systems engineering and software engineering, encompasses those tasks that go into determining the needs or conditions to meet for a new or altered product, taking account of the possibly conflicting requirements of the
various stakeholders, analyzing, documenting, validating and managing software or system requirements. Requirements analysis is critical to the success of a systems or software project. The requirements should be documented, actionable, measurable, testable, traceable, related to identified business needs or opportunities, and defined to a level of detail sufficient for system design.
Logical Design The logical design of a system pertains to an abstract representation of the data flows, inputs and outputs of the system. This is often conducted via modeling, using an over-abstract (and sometimes graphical) model of the actual system. In the context of systems design are included.
Design Analysis In its simplest terms, design analysis is a powerful software technology for simulating physical behavior on the computer. Will it break? Will it deform? Will it get too hot? These are the types of questions for which design analysis provides accurate answers. Instead of building a prototype and developing elaborate testing regimens to analyze the physical behavior of a product, engineers can elicit this information quickly and accurately on the computer. Because design analysis can minimize or even eliminate the need for physical prototyping and testing, the technology has gone main stream in the manufacturing world over the past decade as a valuable product development tool and has become omnipresent in almost all fields of engineering
SYSTEM STUDY FEASIBILITY STUDY The feasibility of the project is analyzed in this phase and business proposal is put forth with a very general plan for the project and some cost estimates. During system analysis the feasibility study of the proposed system is to be carried out. This is to ensure that the proposed system is not a burden to the company. For feasibility analysis, some understanding of the major requirements for the system is essential.
Three key considerations involved in the feasibility analysis are
ECONOMICAL FEASIBILITY
TECHNICAL FEASIBILITY
SOCIAL FEASIBILITY
ECONOMICAL FEASIBILITY This study is carried out to check the economic impact that the system will have on the organization. The amount of fund that the company can pour into the research and development of the system is limited. The expenditures must be justified. Thus the developed system as well within the budget and this was achieved because most of the technologies used are freely available. Only the customized products had to be purchased. TECHNICAL FEASIBILITY This study is carried out to check the technical feasibility, that is, the technical requirements of the system. Any system developed must not have a high demand on the available technical resources. This will lead to high demands on the available technical resources. This will lead to high demands being placed on the client. The developed system must have a modest requirement, as only minimal or null changes are required for implementing this system.
SOCIAL FEASIBILITY The aspect of study is to check the level of acceptance of the system by the user. This includes the process of training the user to use the system efficiently. The user must not feel threatened by the system, instead must accept it as a necessity. The level of acceptance by the users solely depends on the methods that are employed to educate the user about the system and to make him familiar with it. His level of confidence must be raised so that he is also able to make some constructive criticism, which is welcomed, as he is the final user of the
2.1.EXISTING SYSTEM: Existing connection correlation approaches are based on three Different characteristics:
host activity; connection content (i.e. packet payload) inter-packet timing characteristics. The host activity based approach collects and tracks users’ login activity at each stepping stone.
Disadvantages of Existing System: The major drawback of host activity based methods is that the host activity collected from each stepping stone is generally not trustworthy. Since the attacker is assumed to have full control over each stepping stone, he/she can easily modify, delete or forge user login information. This defeat the ability to correlate based on Host activity.
2.2.PROPOSED SYSTEM:
The objective of watermark-based correlation is to make the correlation of encrypted connections probabilistically robust against random timing perturbations by the adversary.
Unlike existing timing-based correlation schemes, our watermark-based correlation is active in that it embeds a unique watermark into the encrypted flows, by slightly adjusting the timing of selected packets.
If the embedded watermark is both unique and robust, the watermarked flows can be effectively identified and thus correlated at each stepping stone.
Advantages of Proposed System: 1) While the attacker can add the secret key in watermarking, we can easily analysis and identify the intruder. 2) All packets in the original flow are kept. No packets are dropped from or added to the flow by the stepping stone. 3) While the watermarking scheme is public knowledge, the watermarking embedding and decoding parameters are secrets known only to the watermark embedder and the watermark detector(s)
3.SYSTEM CONFIGURATION 3.1.Hardware Requirements •
SYSTEM
: Pentium IV 2.4 GHz
•
HARD DISK
•
FLOPPY DRIVE
: 1.44 MB
•
MONITOR
: 15 VGA colour
•
MOUSE
: Logitech.
•
RAM
: 256 MB
•
KEYBOARD
: 110 keys enhanced.
: 40 GB
3.2.Software Requirements •
Operating system
:- Windows XP Professional
•
Front End
:- Microsoft Visual Studio .Net 2010
•
Coding Language
:- C# 2.0
•
Database
:- SQL SERVER 2008
4.ABOUT SOFTWARE
4.1. SOFTWARE DESCRIPTION The Microsoft .Net Framework is a platform that provides tools and technologies you need to build Networked Applications as well as Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL). How to Microsoft .Net Framework?
Net Framework is a platform that provides tools and technologies to develop Windows, Web and Enterprise applications. It mainly contains two components, 1. Common Language Runtime (CLR) 2. .Net Framework Class Library. 1. Common Language Runtime (CLR) .Net Framework provides runtime environment called Common Language Runtime (CLR).It provides an environment to run all the .Net Programs. The code which runs under the CLR is called as Managed Code. Programmers need not to worry on managing the memory if the programs are running under the CLR as it provides memory management and thread management.
Programmatically, when our program needs
memory, CLR allocates the memory for scope and de-allocates the memory if the scope is completed. Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language (MSIL) intern this will be converted to Native Code by CLR. See the below Fig.
2.
.Net Framework Class Library (FCL)
This is also called as Base Class Library and it is common for all types of applications i.e. the way you access the Library Classes and Methods in VB.NET will be the same in C#, and it is common for all other languages in .NET. The following are different types of applications that can make use of .net class library. 1. Windows Application. 2. Console Application 3. Web Application. 4. XML Web Services. 5. Windows Services. In short, developers just need to import the BCL in their language code and use its predefined methods and properties to implement common and complex functions like reading and writing to file, graphic rendering, database interaction, and XML document manipulation. Below are the few more concepts that we need to know and understand as part of this .Net framework.
3. Common Type System (CTS) It describes set of data types that can be used in different .Net languages in common. (i.e), CTS ensures that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level. The common type system supports two general categories of types: Value types: Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations. Reference types: Reference types store a reference to the value’s memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Selfdescribing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates. 4. Common Language Specification (CLS)
It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by all language compilers targeting CLR. It helps in cross language inheritance and cross language debugging. Common language specification Rules: It describes the minimal and complete set of features to produce code that can be hosted by CLR. It ensures that products of compilers will work properly in .NET environment. INTRODUCTION TO THE C# LANGUAGE C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on the C# language and the .NET Framework. C# syntax is highly expressive, yet it is also simple and easy to learn. The curly-brace syntax of C# will be instantly recognizable to anyone familiar with C, C++ or Java. Developers who know any of these languages are typically able to begin to work productively in C# within a very short time. C# syntax simplifies many of the complexities of C++ and provides powerful features such as nullable value types, enumerations, delegates, lambda expressions and direct memory access, which are not found in Java. C# supports generic methods and types, which provide increased type safety and performance, and iterators, which enable implementers of collection classes to define custom iteration behaviors that are simple to use by client code. Language-Integrated Query (LINQ) expressions make the strongly-typed query a first-class language construct. As an object-oriented language, C# supports the concepts of encapsulation, inheritance, and polymorphism. All variables and methods, including the Main method, the application's entry point, are encapsulated within class definitions. A class may inherit directly from one parent class, but it may implement any number of interfaces. Methods that override virtual methods in a parent class require the override keyword as a way to avoid
accidental redefinition. In C#, a struct is like a lightweight class; it is a stack-allocated type that can implement interfaces but does not support inheritance. In addition to these basic object-oriented principles, C# makes it easy to develop software components through several innovative language constructs, including the following:
Encapsulated method signatures called delegates, which enable type-safe event notifications.
Properties, which serve as accessors for private member variables.
Attributes, which provide declarative metadata about types at run time.
Inline XML documentation comments.
Language-Integrated Query (LINQ) which provides built-in query capabilities across a variety of data sources.
If you have to interact with other Windows software such as COM objects or native Win32 DLLs, you can do this in C# through a process called "Interop." Interop enables C# programs to do almost anything that a native C++ application can do. C# even supports pointers and the concept of "unsafe" code for those cases in which direct memory access is absolutely critical. The C# build process is simple compared to C and C++ and more flexible than in Java. There are no separate header files, and no requirement that methods and types be declared in a particular order. A C# source file may define any number of classes, structs, interfaces, and events. The following are additional C# resources:
For a good general introduction to the language, see Chapter 1 of the C# Language Specification.
For detailed information about specific aspects of the C# language, see the C# Reference.
For more information about LINQ, see LINQ (Language-Integrated Query).
To find the latest articles and resources from the Visual C# team, see the Visual C# Developer Center.
C# programs run on the .NET Framework, an integral component of Windows that includes a virtual execution system called the common language runtime (CLR) and a unified set of class libraries. The CLR is the commercial implementation by Microsoft of the common language infrastructure (CLI), an international standard that is the basis for creating execution and development environments in which languages and libraries work together seamlessly. Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI specification. The IL code and resources, such as bitmaps and strings, are stored on disk in an executable file called an assembly, typically with an extension of .exe or .dll. An assembly contains a manifest that provides information about the assembly's types, version, culture, and security requirements. When the C# program is executed, the assembly is loaded into the CLR, which might take various actions based on the information in the manifest. Then, if the security requirements are met, the CLR performs just in time (JIT) compilation to convert the IL code to native machine instructions. The CLR also provides other services related to automatic garbage collection, exception handling, and resource management.
WHAT IS ASP.NET? ASP.NET is part of the .NET framework. ASP.NET programs are centralized applications hosted on one or more Web servers that respond dynamically to client requests. The responses are dynamic because ASP.NET intercepts requests for pages with a specific extension (.aspx or .ascx) and hands off the responsibility for answering those requests to just-in-time (JIT) compiled code files that can build a response “on-the-fly.” ASP.NET deals specifically with configuration (web.config and machine.config) files, Web Services (ASMX) files, and Web Forms (ASPX) files. The server doesn’t “serve” any of these file types—it returns the appropriate content type to the client. The configuration file types contain initialization and settings for a specific application or portion of an application. Another configuration file, called machine.web, contains machinelevel initialization and settings. The server ignores requests for web files, because serving them might constitute a security breach.
Client requests for these file types cause the server to load, parse, and execute code to return a dynamic response. For Web Forms, the response usually consists of HTML or WML. Web Forms maintain state by round-tripping user interface and other persistent values between the client and the server automatically for each request. A request for a Web Form can use View State, Session State, or Application State to maintain values between requests. Both Web Forms and Web Services requests can take advantage of ASP. Net’s integrated security and data access through ADO.NET, and can run code that uses system services to construct the response. So the major difference between a static request and a dynamic request is that a typical Web request references a static file. The server reads the file and responds with the contents of the requested file. ASP.NET uses .NET languages. ASP.NET code exists in multithreaded JIT compiled DLL assemblies, which can be loaded on demand. Once loaded, the ASP.NET DLLs can service multiple requests from a single in-memory copy. ASP.NET EVENTS Every time an ASP.NET page is viewed, many tasks are being performed behind the scenes. Tasks are performed at key points ("events") of the page's execution lifecycle. The most common events are: OnInit The first event in our list to be raised is OnInit. When this event is raised, all of the page's server controls are initialized with their property values. Post Back values are not applied to the controls at this time. On Load The next event to be raised is On Load, which is the most important event of them all as all the pages server controls will have their Post Back values now. Post Back Events Next all the Post Back events are raised. These events are only raised when the page view is the result of a Post Back. The order that these events are raised can't be defined or
relied upon; the only consistency with the order that Post Back events are raised is that they are all raised between the Unload and OnPreRender events. OnPreRender This event is raised just prior to the page or server control's html output being written into the response stream that's sent to the client web browser. This is last chance you have to make any modifications. By this point, all the server controls on the page have the final data applied. On Unload This is the last event in our list to be raised and you should destroy any un-managed objects and close any currently open database connection at this point. It is not possible to modify any controls on the page at this point as the response stream has already been sent to the client web browser. TYPES OF CONTROLS ASP.NET has two basic types of controls: HTML server controls and Web server controls.HTML Server Controls are generated around specific HTML elements and the ASP.NET engine changes the attributes of the elements based on server-side code that you provide. Web server controls revolve more around the functional you need on the page. The ASP.NET engine takes the extra steps to decide based upon the container of the requester, what HTML to output.
WEB SERVER CONTROLS:
Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements. The syntax for creating a Web server control is: Web Server Control AdRotator Button Calendar CheckBox CheckBoxList DataGrid DataList DropDownList HyperLink Image ImageButton Label
Description Displays a sequence of images Displays a push button Displays a calendar Displays a check box Creates a multi-selection check box group Displays fields of a data source in a grid Displays items from a data source by using templates Creates a drop-down list Creates a hyperlink Displays an image Displays a clickable image Displays static content which is programmable (lets you apply
LinkButton ListBox Literal
styles to its content) Creates a hyperlink button Creates a single- or multi-selection drop-down list Displays static content which is programmable (does not let you
Panel PlaceHolder RadioButton RadioButtonList Repeater Table TableCell TableRow TextBox Xml
apply styles to its content) Provides a container for other controls Reserves space for controls added by code Creates a radio button Creates a group of radio buttons Displays a repeated list of items bound to the control Creates a table Creates a table cell Creates a table row Creates a text box Displays an XML file or the results of an XSL transform
ADO .NET: Most applications need data access at one point of time making it a crucial component when working with applications. Data access is making the application interact with a database, where all the data is stored. Different applications have different requirements for database access. VB .NET uses ADO .NET (Active X Data Object) as it's data access and
manipulation protocol which also enables us to work with data on the Internet. Let's take a look why ADO .NET came into picture replacing ADO. The first data access model, DAO (data access model) was created for local databases with the built-in Jet engine which had performance and functionality issues. Next RDO (Remote Data Object) and ADO (Active Data Object) which were designed for Client Server architectures but soon ADO took over RDO. ADO was a good architecture but as the language changes so is the technology. With ADO, all the data is contained in a record set object which had problems when implemented on the network and penetrating firewalls. ADO was a connected data access, which means that when a connection to the database is established the connection remains open until the application is closed. Leaving the connection open for the lifetime of the application raises concerns about database security and network traffic. Also, as databases are becoming increasingly important and as they are serving more people, a connected data access model makes us think about its productivity. For example, an application with connected data access may do well when connected to two clients, the same may do poorly when connected to 10 and might be unusable when connected to 100 or more. DATASET: The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The Dataset is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in Dataset can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database. DATA PROVIDER: The Data Provider is responsible for providing and maintaining the connection to the database. A Data Provider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two Data Providers: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OLEDB Data Provider which allows us to connect to other types of databases like Access and Oracle. Each Data Provider consists of the following component classes:
The Connection object which provides a connection to the database The Command object which is used to execute a command The Data Reader object which provides a forward-only, read only, connected record set The Data Adapter object which populates a disconnected Data Set with data and performs update .Data access with ADO.NET can be summarized as follows: A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a Data Reader to provide the data. Alternatively, the Data Adapter can be used to fill the Dataset object. The database can be updated using the command object or the Data Adapter.
THE CONNECTION OBJECT: The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database.
THE COMMAND OBJECT: The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute commands to a database across a data connection. The Command objects can be used to execute stored procedures on the database, SQL commands, or return complete tables directly. Command objects provide three methods that are used to execute commands on the database. EXECUTENONQUERY: Executes commands that have no return values such as INSERT, UPDATE or DELETE. EXECUTE SCALAR: Returns a Single Value from a Database Query EXECUTEREADER: Returns a Result Set By Way of a Data reader Object THE DATA READER OBJECT: The Data Reader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader. THE DATA ADAPTER OBJECT: The Data Adapter is the class at the core of ADO .NET's disconnected data access. It is essentially the middleman facilitating all communication between the database and a Data Set. The Data Adapter is used either to fill a Data Table or Data Set with data from the database with its Fill method. After the memory-resident data has been manipulated, the Data Adapter can commit the changes to the database by calling the Update method. The Data Adapter provides four properties that represent database commands: Select Command
Insert Command Delete Command Update Command When the Update method is called, changes in the Data Set are copied back to the database and the appropriate Insert Command, Delete Command, or Update Command is executed. ASP.NET is the .NET framework layer that handles Web requests for specific types of files, namely those with (.aspx or .ascx) extensions. The ASP.NET engine provides a robust object model for creating dynamic content and is loosely integrated into the .NET framework. MICROSOFT SQL SERVER: Microsoft's SQL Server is steadily on the rise in the commercial world gaining popularity slowly. This platform has a GUI "Windows" type interface and is also rich with functionality. A free trial version can be downloaded at the Microsoft web site, however it is only available to Windows users. DATABASE: A database is nothing more than an empty shell, like a vacant warehouse. It offers no real functionality what so ever, other than holding a name. Tables are the next tier of our tree offering a wide scope of functionality. If you follow our warehouse example, a SQL table would be the physical shelving inside our vacant warehouse. Each SQL table is capable of housing 1024 columns(shelves). Depending on the situation, your goods may require reorganization, reserving, or removal. SQL tables can be manipulated in this same way or in any fashion the situation calls for. SQL QUERIES: Queries are the backbone of SQL. Query is a loose term that refers to a widely available set of SQL commands called clauses. Each clause (command) performs some sort of function against the database. For instance, the create clause creates tables and databases and the select clause selects rows that have been inserted into your tables. We will dive deeper in detail as this tutorial continues but for now let's take a look at some query structure. DATA STORAGE:
The main unit of data storage is a database, which is a collection of tables with typed columns. SQL Server supports different data types, including primary types such as Integer, Float, Decimal, Char (including character strings), Varchar (variable length character strings), binary (for unstructured blobs of data), Text (for textual data) among others. It also allows user-defined composite types (UDTs) to be defined and used. SQL Server also makes server statistics available as virtual tables and views (called Dynamic Management Views or DMVs). A database can also contain other objects including views, stored procedures, indexes and constraints, in addition to tables, along with a transaction log. A SQL Server database can contain a maximum of 231 objects, and can span multiple OS-level files with a maximum file size of 220 TB. The data in the database are stored in primary data files with an extension .mdf. Secondary data files, identified with an .ndf extension, are used to store optional metadata. Log files are identified with the .ldf extension. BUFFER MANAGEMENT: SQL Server buffers pages in RAM to minimize disc I/O. Any 8 KB page can be buffered in-memory, and the set of all pages currently buffered is called the buffer cache. The amount of memory available to SQL Server decides how many pages will be cached in memory. The buffer cache is managed by the Buffer Manager. Either reading from or writing to any page copies it to the buffer cache. Subsequent reads or writes are redirected to the inmemory copy, rather than the on-disc version. CONCURRENCY AND LOCKING: SQL Server allows multiple clients to use the same database concurrently. As such, it needs to control concurrent access to shared data, to ensure data integrity - when multiple clients update the same data, or clients attempt to read data that is in the process of being changed by another client. SQL Server provides two modes of concurrency control: pessimistic concurrency and optimistic concurrency. When pessimistic concurrency control is being used, SQL Server controls concurrent access by using locks. Locks can be either shared or exclusive. Exclusive lock grants the user exclusive access to the data - no other user can access the data as long as the lock is held. Shared locks are used when some data is being read - multiple users can read from data locked with a shared lock, but not acquire an exclusive lock. The latter would have to wait for all shared locks to be released. Locks can be
applied on different levels of granularity - on entire tables, pages, or even on a per-row basis on tables. For indexes, it can either be on the entire index or on index leaves.
5. SYSTEM DESIGN 5.1.INPUT DESIGN: Input design is the process of converting a user-oriented description of the inputs to a computer based business system into a program-oriented specification. The objectives in the input design:
To produce a cost-effective method of input.
To achieve a highest possible level of accuracy.
To ensure that input is acceptable to and understood by the user staff.
INPUT STAGES: Several activities have to be carried out as a part of the overall input process. They include
Data Recording – Collection of data at its source.
Data Description – Transfer of data to an input form
Data Conversion – Conversion of the input data to a computer acceptable medium.
Data Verification – Checking the conversion
Data Control – Checking the accuracy and controlling the flow of data to the computer.
Data Transmission – Transmission or transferring the data to the computer.
Data Validation – Checking the input data by program when it enters the computer system.
Data Correction – Correction the errors that are found at any early stages
5.2.OUTPUT DESIGN: The output design is an ongoing activity almost from the beginning of the project, and follows the principles of form design. Effects and well define an output design improves the relationship of system and the user, thus facilitating decision-making. A major form of output is a hard copy from the printer, however soft copies available. The Types of output used in the system are:
Internal outputs: Whose destination is within the organization and is the user’s main interface with the computer.
Interactive outputs: Which involves the user in communicating directly with the computer.
External outputs: Whose destination is outside the organization and which require special attention since they project the image of the organization.
DATABASE DESIGN: The database design is a must for any developed especially more for the data store projects, since the chatting method involves storing the message in the table and produced to the sender and receiver, proper handling of the table is a must.In the project, admin table is designed to be unique in accepting the username and the length of the username and password should be greater than zero.
5.3. DATA FLOW DIAGRAM Data Flow Diagram (DFD) specifies data sources and data sinks ,data stores, transformation to be performed on the flow of data between sources, sinks, transformation and stores. A data store is a conceptual data structure in the sense that physical implementation details are suppressed only the logical characteristics of data are emphasized on a DFD.
-
Data sinks /Data sources
- Transformation, process
- Data Stores
- Data flow DFD follows a top down approach. An initial overview model is “exploded” into more detailed, lower level diagrams that show additional features of the system. Each process can be broken into a yet more detailed is describe to allow the analyst to understand the portion of the system under investigation. Thus DFD concentrate on the data moving through the system not on devices or equipment.
Module diagram
Start
Login
Embedded the Images
Embedded the document
Encryption &Decryption perform
Send request to Admin Admin view the request &detection verification perform
Encryption & Decryption perform
Stop
UML Diagrams
Use case diagram
Split the packet
User
Files & images Encryption & Decrption
Network System
Class diagram
Files& images. Documne name Image size Image type
Encrypt Image name Image size Image type
Make_encrypt()
Send_request()
Login. user_ name password login()
Send request File name File Size Decrypt()
Decrypt Image type Image size detection & verification 1
Object diagram
Login
Embedded image& Embedded document E
Encryption perform
Send Request to admin
Finally Create Zip file with password
Verify the request &detection verification perform
Activity diagram
New User
Yes
Finds file
Login.
Metadata Search System
CreateMetada ta
Meatadata
Search File
Complete Search
Sequence diagram
User
Login
embedded n Request
User Info
Verify Detection Request
Login Info
Image&document
File Info
File Details
File
Create zip file
Collaboration Diagram
6: original Detection & Create zip file File verification process with password
User
1: User Info
Login
5: File Details
Verify Request
2: Login Info
Encryption 3.Image&document
4: File Info
Send request to admin
Component Diagram
Encryption
Verify Request File User
Decryption Perform
File Name info Encryption&Decrypti on File Size Info
E-R diagram HAS
User Login Details
Dataflow diagram
Login
Login User
Encryption
Request Verification
Detection perform Compete the process
Image& document
6. SYSTEM TESTING
Software Testing is the process used to help identify the correctness, completeness, security, and quality of developed computer software. Testing is a process of technical investigation, performed on behalf of stakeholders, that is intended to reveal quality-related information about the product with respect to the context in which it is intended to operate. This includes, but is not limited to, the process of executing a program or application with the intent of finding errors. Quality is not an absolute; it is value to some person. With that in mind, testing can never completely establish the correctness of arbitrary computer software; testing furnishes a criticism or comparison that compares the state and behaviour of the product against a specification. An important point is that software testing should be distinguished from the separate discipline of Software Quality Assurance (SQA), which encompasses all business process areas, not just testing. In general, software engineers distinguish software faults from software failures. In case of a failure, the software does not do what the user expects. A fault is a programming error that may or may not actually manifest as a failure. A fault can also be described as an error in the correctness of the semantic of a computer program. A fault will become a failure if the exact computation conditions are met, one of them being that the faulty portion of computer software executes on the CPU. A fault can also turn into a failure when the software is ported to a different hardware platform or a different compiler, or when the software gets extended. Software testing is the technical investigation of the product under test to provide stakeholders with quality related information. A problem with software testing is that the number of defects in a software product can be very large, and the number of configurations of the product larger still. Bugs that occur infrequently are difficult to find in testing. A rule of thumb is that a system that is expected to function without faults for a certain length of time must have already been tested
for at least that length of time. This has severe consequences for projects to write long-lived reliable software.
WHITE-BOX AND BLACK-BOX TESTING White box and black box testing are terms used to describe the point of view a test engineer takes when designing test cases. Black box being an external view of the test object and white box being an internal view. Software testing is partly intuitive, but largely systematic. Good testing involves much more than just running the program a few times to see whether it works. Thorough analysis of the program under test, backed by a broad knowledge of testing techniques and tools are prerequisites to systematic testing. Software Testing is the process of executing software in a controlled manner; in order to answer the question “Does this software behave as specified?” Software testing is used in association with Verification and Validation. Verification is the checking of or testing of items, including software, for conformance and consistency with an associated specification. Software testing is just one kind of verification, which also uses techniques as reviews, inspections, walkthrough. Validation is the process of checking what has been specified is what the user actually wanted.
Validation: Are we doing the right job?
Verification: Are we doing the job right?
A further level of testing is also done, in accordance with requirements:
Acceptance testing: upon which the acceptance of the complete software is based. The clients often do this.
Regression testing: is used to refer the repetition of the earlier successful tests to ensure that changes made in the software have not introduced new bugs/side effects.
TEST LEVELS
Unit testing tests the minimal software component and sub-component or module
s by the programmers.
Integration testing exposes defects in the interfaces and interaction between integrated components (modules).
Functional testing tests the product according to programmable work.
System testing tests an integrated system to verify/validate that it meets its requirements.
Acceptance testing testing can be conducted by the client. It allows the end-user or customer or client to decide whether or not to accept the product. Acceptance testing may be performed after the testing and before the implementation phase.
TESTING CYCLE Although testing varies between organizations, there is a cycle to testing: 1. Requirements Analysis: Testing should begin in the requirements phase of the software development life cycle. During the design phase, testers work with developers in determining what aspects of a design are testable and under what parameter those tests work.
2. Test Planning: Test Strategy, Test Plan(s), Test Bed creation. 3. Test Development: Test Procedures, Test Scenarios, Test Cases, Test Scripts to use in testing software. 4. Test Execution: Testers execute the software based on the plans and tests and report any errors found to the development team. 5. Test Reporting: Once testing is completed, testers generate metrics and make final reports on their test effort and whether or not the software tested is ready for release. 6. Retesting the Defects
Different Phases of Testing Life Cycle The life cycle of testing process intersects the software development lifecycle. When would testing start varies from one company to another. In some companies, testing start simultaneously with development, while in others, it starts after the software has been built. Both these methods have their own advantages and disadvantages. Whatever be the method adopted for testing the software, the steps followed are more or less as mentioned below.
Planning Phase The process of software testing life cycle phase starts with the test planning stage. It is recommended that one spend a lot of time in this phase, to minimize headaches in the other software testing phases. It is in this phase that the 'Test Plan' is created. It is a document, where the items to be tested along with the features to be tested, pass/fail criteria of a test, exit criteria, environment to be created, risks and contingencies are mentioned. This gives the testing team refined specifications. Analysis Phase An analysis of the requirements is carried out, so that the testing team can be well versed with the software that has been developed. It is in this phase that the types of testing to be carried out in the different phases of the testing life cycle are decided upon. In some cases, the test may have to be automated and in others, manual tests would have to be carried out. Functional validation matrix, which is based on business requirements is made. It is normally based on one or more than one test cases. This matrix helps in analyzing, which of the test cases will have to be automated and which will have to be tested manually.
Designing Phase In the software testing life cycle, this phase has an important role to play. Here the test plan, functional validation matrix, test cases, etc. are all revised. This ensures there are no problems existing in any of them. If the test cases have to be automated, the suitable scripts for the same are designed at this stage. Test data for both manual as well as automated test cases is also generated. Development Phase Based on the test plan and test cases the entire scripting takes place in this phase. If the testing activity starts along with the development activity of the software, the unit tests will also have been implemented in the development phase. Often along with the unit tests, stress and performance test plans are generated in this phase. Execution Phase After the test scripts have been made, they are executed. Initially, unit tests are executed, followed by functionality tests. In the initial phase testing is carried out on the superficial level, i.e. on the top level. This helps in identifying bugs on the top level, which are then reported to the development team. Then the software is tested in depth. The test reports are created and bugs are reported. Retest and Regression Testing Phase Once the bugs have been identified, they are sent to the development team. Depending on the nature of the bug, the bug may be rejected, deferred or fixed. If the bug has been accepted and fixed immediately, the software has to be retested to check if the bug has indeed been fixed. Regression testing is carried out to ensure that no new bugs have been created in the software, while fixing of the bug.
7. SYSTEM IMPLEMENTATION There are a number of factors to consider when putting a new system into production. They are even more important if the new system is replacing or upgrading an old one. It is also important that all of these items are considered and included in the project plan.
Once a technology system has been built it should be thoroughly tested before being put into production. In most cases it is more difficult and time consuming to fix a problem in a production system than it is in a QA or staging system.
Good documentation is essential. Most developers don't like writing documentation and many organizations don't like the time and cost involved in creating it, so many projects end up with little more than the system diagrams and object models created during system design and sparse code comments saved in text files as their documentation. While these are important the most critical documentation is that which described the relationships between the various system components, any assumptions upon which the operation of the components or their relationships depend, and any complex, creative, unorthodox, or other unusual design and programming techniques used with the reason they were needed.
System upgrades and maintenance should be part of the initial project plan and well documented. Even the designers and developers who built the system may have to spend time refreshing their memories if a change needs to be made months or years after the system is first put into production and good documentation can substantially reduce the time and risk required to make such a change. Training of internal staff is essential - not only of the people who use the system but of the technical staff that must maintain it. While we are always available to help with maintenance and upgrades, it is usually more cost effective for internal staff to be adequately trained on how to administer, configure, and make minor updates to the system.
For large or complex systems you may find that you need additional staff, particularly if you want to handle major modifications and functionality upgrades internally. You may even want to hire these people towards the beginning of the project to reduce the initial development costs and ease the transition to full internal control of the system. If this is the case we can assist you with finding well qualified personnel. The difference between our recruiting services and those of many other staffing agencies is the quality of the resumes you can expect. Most agencies provide you with a stack of resumes for people who have some level of experience with the major skills defined in your job description. It is then up to you to sift through these resumes and pick the ones that seem well enough qualified to be worth interviewing. We first work with you to clearly develop a detailed job description and then find candidates whose skills and experience fit that description very closely. We interview them ourselves and then send you the resumes of the two or three that are best qualified for you to interview, saving you a substantial amount of time.
8.CONCLUSION The random timing permutation greatly reduce the effectiveness of passive timing approaches.in this paper we analyzed the active water marking scheme for tracing through stepping stones. our active watermark based correlation requires fewer packets than a passive timing based correlation method to achieve a given level of robustness. Here we identified the provable upper bounds on the number of packets needed to achieve desire correlation effectiveness under given level of permutation. One interesting area of future work is to investigate how to make the flow watermarking more robust with fewer packets
9. BIBLOGRAPHY A list of source materials that are used or consulted in the preparation of a work or that are referred to in the text. Books Referred
Title: Pro ASP.NET MVC 3 Framework, Third Edition By: Adam Freeman; Steven Sanderson Publisher: Apress
Title: Professional ASP.NET MVC 3 By: Jon Galloway; Phil Haack; Brad Wilson; K. Scott Allen Publisher: Wrox
Title: Pro ASP.NET 4 in C# 2010 By: Matthew MacDonald; Adam Freeman; Mario Szpuszta Publisher: Apress
Network programming in .NET: C# & Visual Basic .NET by Fiach Reid.
Microsoft Visual C# 2012 Step by Step (Microsoft) paperback by John Sharp.
C# to create innovative Window 8 applications By Matthew Baxter-Reynolds, Iris Classon.
Sites Referred
http://www.tutorialspoint.com/csharp/
http://www.csharp-station.com/tutorial.aspx
10.APPENDICES A.Screen short Home page
User login
Choose image directory
Preview the images
Give signature
Encrypt images
Packet splitting
Admin
Verify the request
View detection
Encrypt the file
Secure file sending
Create the secure zip file
B).CODING
Home using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class Home : Form { string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); string p1, p2, p3 = "", whoislog = "", p4; public Home() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("Enter LoginID.", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } else { if (textBox2.Text == "") { MessageBox.Show("Enter Password.", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } else { if (comboBox1.SelectedIndex == 0) { MessageBox.Show("Select LoginType.", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); } else { SqlConnection con1 = new SqlConnection(constring);
con1.Open(); SqlDataAdapter adp1 = new SqlDataAdapter("Select whoislogin from Registration", con1); DataSet ds1 = new DataSet(); adp1.Fill(ds1); for (int i = 0; i < ds1.Tables[0].Rows.Count; i++) { SqlCommand cmd1 = new SqlCommand("Update Registration set whoislogin='" + whoislog + "'", con1); cmd1.ExecuteNonQuery(); } SqlDataAdapter adp = new SqlDataAdapter("Select ID,LoginID,LPassword,LoginType from Registration where LoginID='" + textBox1.Text + "'and LPassword='" + textBox2.Text + "'and LoginType='" + comboBox1.SelectedItem.ToString() + "'", con1); DataSet ds = new DataSet(); adp.Fill(ds); if (textBox1.Text == "Admin" && textBox2.Text == "Admin" && comboBox1.Text == "Admin") { Admin adm = new Admin(); adm.ShowDialog(); goto Outer; } for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { p1 = ds.Tables[0].Rows[i]["LoginID"].ToString(); p2 = ds.Tables[0].Rows[i]["LPassword"].ToString(); p3 = ds.Tables[0].Rows[i]["LoginType"].ToString(); p4 = ds.Tables[0].Rows[i]["ID"].ToString(); frmMain usr1 = new frmMain(p4); if (p1 == textBox1.Text && p2 == textBox2.Text && p3 == "User") { SqlCommand cmd = new SqlCommand("Update Registration set whoislogin='" + p1 + "'where LoginID='" + p1 + "'", con1); cmd.ExecuteNonQuery(); frmMain usr = new frmMain(p4); usr.ShowDialog(); goto Outer; }
} p1 = ""; p2 = ""; p3 = ""; } MessageBox.Show("Enter Correct LoginID/Password.", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Warning); Outer: p1 = ""; p2 = ""; p3 = ""; } } } private void button2_Click(object sender, EventArgs e) { textBox1.Text = ""; textBox2.Text = ""; comboBox1.SelectedIndex = 0; } private void Home_Load(object sender, EventArgs e) { comboBox1.Items.Insert(0, "--Select--"); comboBox1.Items.Insert(1, "User"); comboBox1.Items.Insert(2, "Admin"); comboBox1.SelectedIndex = 0; } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Register Rf = new Register(); Rf.Show(); } } } File sending using System; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; using System.Configuration;
namespace WaterMark { public partial class File_sending: Form { string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); Class2 cs = new Class2(); public File_sending() { InitializeComponent(); } string loadedTrueImagePath, loadedFilePath, saveToImage, DLoadImagePath, DSaveFilePath; int height, width; long fileSize, fileNameSize; Image loadedTrueImage, DecryptedImage, AfterEncryption; Bitmap loadedTrueBitmap, DecryptedBitmap; Rectangle previewImage = new Rectangle(20, 160, 490, 470); bool canPaint = false, EncriptionDone = false; byte[] fileContainer; string int2,auid1; private void EnImageBrowse_btn_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { loadedTrueImagePath = openFileDialog1.FileName; EnImage_tbx.Text = loadedTrueImagePath; loadedTrueImage = Image.FromFile(loadedTrueImagePath); height = loadedTrueImage.Height; width = loadedTrueImage.Width; loadedTrueBitmap = new Bitmap(loadedTrueImage); FileInfo imginf = new FileInfo(loadedTrueImagePath); float fs = (float)imginf.Length / 1024; ImageSize_lbl.Text = smalldecimal(fs.ToString(), 2) + " KB"; ImageHeight_lbl.Text = loadedTrueImage.Height.ToString() + " Pixel"; ImageWidth_lbl.Text = loadedTrueImage.Width.ToString() + " Pixel"; double cansave = (8.0 * ((height * (width / 3) * 3) / 3 - 1)) / 1024; CanSave_lbl.Text = smalldecimal(cansave.ToString(), 2) + " KB"; canPaint = true; this.Invalidate(); } } public File_sending(string strtextbox, string strtextbox1) { InitializeComponent(); int2 = strtextbox; auid1=strtextbox1;
} private void Form1_Paint(object sender, PaintEventArgs e) { if (canPaint) try { if (!EncriptionDone) e.Graphics.DrawImage(loadedTrueImage, previewImage); else e.Graphics.DrawImage(AfterEncryption, previewImage); } catch { e.Graphics.DrawImage(DecryptedImage, previewImage); } } private string smalldecimal(string inp, int dec) { int i; for (i = inp.Length - 1; i > 0; i--) if (inp[i] == '.') break; try { return inp.Substring(0, i + dec + 1); } catch { return inp; } } private void EnFileBrowse_btn_Click(object sender, EventArgs e) { if (openFileDialog2.ShowDialog() == DialogResult.OK) { loadedFilePath = openFileDialog2.FileName; EnFile_tbx.Text = loadedFilePath; FileInfo finfo = new FileInfo(loadedFilePath); fileSize = finfo.Length; fileNameSize = justFName(loadedFilePath).Length; } } private void Encrypt_btn_Click(object sender, EventArgs e) { pictureBox1.Image = Image.FromFile(EnImage_tbx.Text);
if (saveFileDialog1.ShowDialog() == DialogResult.OK) { saveToImage = saveFileDialog1.FileName; } else return; if (EnImage_tbx.Text == String.Empty || EnFile_tbx.Text == String.Empty) { MessageBox.Show("Encrypton information is incomplete!\nPlease complete them frist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (8 * ((height * (width / 3) * 3) / 3 - 1) < fileSize + fileNameSize) { //MessageBox.Show("File size is too large!\nPlease use a larger image to hide this file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //return; } fileContainer = File.ReadAllBytes(loadedFilePath); //EncryptLayer(); SqlConnection con = new SqlConnection(constring); con.Open(); SqlCommand cmd2 = new SqlCommand("update Embedding set saveimagepath='" + saveToImage + "' where id1='" + int2 + "' and autid='" + auid1 + "'", con); cmd2.ExecuteNonQuery(); SqlCommand cmd1 = new SqlCommand("update Embedding set loadimagepath='" + EnImage_tbx.Text + "',loadfilepath='" + EnFile_tbx.Text + "' where id1='" + int2 + "' and autid='" + auid1 + "'", con); cmd1.ExecuteNonQuery(); con.Close(); MessageBox.Show("your file is ready to split the packets ,click packets sending!!!"); } private void EncryptLayer() { toolStripStatusLabel1.Text = "Encrypting... Please wait"; Application.DoEvents(); long FSize = fileSize; Bitmap changedBitmap = EncryptLayer(8, loadedTrueBitmap, 0, (height * (width / 3) * 3) / 3 - fileNameSize - 1, true); FSize -= (height * (width / 3) * 3) / 3 - fileNameSize - 1; if (FSize > 0) { for (int i = 7; i >= 0 && FSize > 0; i--) { changedBitmap = EncryptLayer(i, changedBitmap, (((8 - i) * height * (width / 3) * 3) / 3 - fileNameSize - (8 - i)), (((9 - i) * height * (width / 3) * 3) / 3 - fileNameSize - (9 i)), false);
FSize -= (height * (width / 3) * 3) / 3 - 1; } } changedBitmap.Save(saveToImage); toolStripStatusLabel1.Text = "Encrypted image has been successfully saved."; EncriptionDone = true; AfterEncryption = Image.FromFile(saveToImage); this.Invalidate(); } private Bitmap EncryptLayer(int layer, Bitmap inputBitmap, long startPosition, long endPosition, bool writeFileName) { Bitmap outputBitmap = inputBitmap; layer--; int i = 0, j = 0; long FNSize = 0; bool[] t = new bool[8]; bool[] rb = new bool[8]; bool[] gb = new bool[8]; bool[] bb = new bool[8]; Color pixel = new Color(); byte r, g, b; if (writeFileName) { FNSize = fileNameSize; string fileName = justFName(loadedFilePath); //write fileName: for (i = 0; i < height && i * (height / 3) < fileNameSize; i++) for (j = 0; j < (width / 3) * 3 && i * (height / 3) + (j / 3) < fileNameSize; j++) { byte2bool((byte)fileName[i * (height / 3) + j / 3], ref t); pixel = inputBitmap.GetPixel(j, i); r = pixel.R; g = pixel.G; b = pixel.B; byte2bool(r, ref rb); byte2bool(g, ref gb); byte2bool(b, ref bb); if (j % 3 == 0) { rb[7] = t[0]; gb[7] = t[1]; bb[7] = t[2]; } else if (j % 3 == 1) { rb[7] = t[3]; gb[7] = t[4];
bb[7] = t[5]; } else { rb[7] = t[6]; gb[7] = t[7]; } Color result = Color.FromArgb((int)bool2byte(rb), (int)bool2byte(gb), (int)bool2byte(bb)); outputBitmap.SetPixel(j, i, result); } i--; } //write file (after file name): int tempj = j; for (; i < height && i * (height / 3) < endPosition - startPosition + FNSize && startPosition + i * (height / 3) < fileSize + FNSize; i++) for (j = 0; j < (width / 3) * 3 && i * (height / 3) + (j / 3) < endPosition startPosition + FNSize && startPosition + i * (height / 3) + (j / 3) < fileSize + FNSize; j++) { if (tempj != 0) { j = tempj; tempj = 0; } byte2bool((byte)fileContainer[startPosition + i * (height / 3) + j / 3 - FNSize], ref t); pixel = inputBitmap.GetPixel(j, i); r = pixel.R; g = pixel.G; b = pixel.B; byte2bool(r, ref rb); byte2bool(g, ref gb); byte2bool(b, ref bb); if (j % 3 == 0) { rb[layer] = t[0]; gb[layer] = t[1]; bb[layer] = t[2]; } else if (j % 3 == 1) { rb[layer] = t[3]; gb[layer] = t[4]; bb[layer] = t[5]; } else { rb[layer] = t[6];
gb[layer] = t[7]; } Color result = Color.FromArgb((int)bool2byte(rb), (int)bool2byte(gb), (int)bool2byte(bb)); outputBitmap.SetPixel(j, i, result); } long tempFS = fileSize, tempFNS = fileNameSize; r = (byte)(tempFS % 100); tempFS /= 100; g = (byte)(tempFS % 100); tempFS /= 100; b = (byte)(tempFS % 100); Color flenColor = Color.FromArgb(r, g, b); outputBitmap.SetPixel(width - 1, height - 1, flenColor); r = (byte)(tempFNS % 100); tempFNS /= 100; g = (byte)(tempFNS % 100); tempFNS /= 100; b = (byte)(tempFNS % 100); Color fnlenColor = Color.FromArgb(r, g, b); outputBitmap.SetPixel(width - 2, height - 1, fnlenColor); return outputBitmap; } private void byte2bool(byte inp, ref bool[] outp) { if (inp >= 0 && inp <= 255) for (short i = 7; i >= 0; i--) { if (inp % 2 == 1) outp[i] = true; else outp[i] = false; inp /= 2; } else throw new Exception("Input number is illegal."); } private byte bool2byte(bool[] inp) { byte outp = 0; for (short i = 7; i >= 0; i--) { if (inp[i]) outp += (byte)Math.Pow(2.0, (double)(7 - i)); } return outp;
} private string justFName(string path) { string output; int i; if (path.Length == 3) // i.e: "C:\\" return path.Substring(0, 1); for (i = path.Length - 1; i > 0; i--) if (path[i] == '\\') break; output = path.Substring(i + 1); return output; } private string justEx(string fName) { string output; int i; for (i = fName.Length - 1; i > 0; i--) if (fName[i] == '.') break; output = fName.Substring(i + 1); return output; } private void packetSendingToolStripMenuItem_Click(object sender, EventArgs e) { packet pc = new packet(EnFile_tbx.Text); pc.Show(); } } } Send request using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark {
public partial class Sendrequest : Form { string id2; string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public Sendrequest() { InitializeComponent(); } public Sendrequest(string strtextbox) { InitializeComponent(); id2 = strtextbox; } private void Sendrequest_Load(object sender, EventArgs e) { button1.Visible = true; dataGridView2.Visible = false; SqlConnection con = new SqlConnection(constring); con.Open(); SqlDataAdapter da = new SqlDataAdapter("Select id1 as Userid,autid as Fileid,loadfilepath as FilePath from Embedding where id1='"+id2+"' and status='' ", con); DataSet ds = new DataSet(); BindingSource bsourse = new BindingSource(); SqlCommandBuilder cmd = new SqlCommandBuilder(da); da.Fill(ds, "Embedding"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse.DataSource = ds.Tables["Embedding"]; if (ds.Tables[0].Rows.Count > 0) { dataGridView1.DataSource = bsourse; dataGridView1.Visible = true; } else { MessageBox.Show("No New files are uploaded"); } con.Close(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { int curRow = int.Parse(e.RowIndex.ToString()); string currentrow, uid, auid1; uid = dataGridView1.Rows[curRow].Cells[1].Value.ToString();
auid1 = dataGridView1.Rows[curRow].Cells[2].Value.ToString(); currentrow = dataGridView1.Rows[curRow].Cells[3].Value.ToString(); SqlConnection con = new SqlConnection(constring); con.Open(); SqlCommand cmd = new SqlCommand("Update Embedding set status='Not Verified' where id1='"+uid+"' and autid='"+auid1+"'", con); cmd.ExecuteNonQuery(); MessageBox.Show("Request sent Successfully!!!");
con.Close(); } private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) { int curRow1 = int.Parse(e.RowIndex.ToString()); string currentrow1, uid1, auid2; uid1 = dataGridView2.Rows[curRow1].Cells[1].Value.ToString(); auid2 = dataGridView2.Rows[curRow1].Cells[2].Value.ToString(); currentrow1 = dataGridView2.Rows[curRow1].Cells[3].Value.ToString(); SqlConnection con1 = new SqlConnection(constring); con1.Open(); SqlCommand cmd2 = new SqlCommand("Update Embedding set status='Not Verified' where id1='" + uid1 + "' and autid='" + auid2 + "'", con1); cmd2.ExecuteNonQuery(); MessageBox.Show("Request sent Successfully!!!");
con1.Close(); } private void button1_Click(object sender, EventArgs e) { button1.Visible = false; SqlConnection con1 = new SqlConnection(constring); con1.Open(); SqlDataAdapter da1 = new SqlDataAdapter("Select id1 as Userid,autid as Fileid,loadfilepath as FilePath from Embedding where id1='" + id2 + "' and status !='' ", con1); DataSet ds1 = new DataSet(); BindingSource bsourse1 = new BindingSource(); SqlCommandBuilder cmd1 = new SqlCommandBuilder(da1);
da1.Fill(ds1, "Embedding"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse1.DataSource = ds1.Tables["Embedding"]; dataGridView2.DataSource = bsourse1; dataGridView2.Visible = true; con1.Close(); } } } View profile using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class View_profile : Form { string id1; string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public View_profile(string strtextbox) { InitializeComponent(); id1 = strtextbox; } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(constring); con.Open(); SqlCommand cmd = new SqlCommand(("Update Registration set LName='" + textBox1.Text + "',Date='" + textBox3.Text + "',Mobile='" + textBox4.Text + "',Email='" + textBox5.Text + "'where ID='" + id1 + "' "), con); cmd.ExecuteNonQuery(); con.Close(); DialogResult dlgResult = MessageBox.Show("Updated Successfully..", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (dlgResult == DialogResult.OK) { View_profile_Load(null, EventArgs.Empty); } } private void button3_Click(object sender, EventArgs e) { textBox1.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; } private void View_profile_Load(object sender, EventArgs e) { SqlConnection con = new SqlConnection(constring); con.Open(); SqlDataAdapter adp = new SqlDataAdapter("Select * from Registration where ID='" + id1 + "'", con); DataSet ds = new DataSet(); adp.Fill(ds); label65.Text = ds.Tables[0].Rows[0]["ID"].ToString(); label51.Text = ds.Tables[0].Rows[0]["LName"].ToString(); label50.Text = ds.Tables[0].Rows[0]["LoginID"].ToString(); label49.Text = ds.Tables[0].Rows[0]["Date"].ToString(); label48.Text = ds.Tables[0].Rows[0]["Mobile"].ToString(); label47.Text = ds.Tables[0].Rows[0]["Email"].ToString(); label46.Text = ds.Tables[0].Rows[0]["LoginType"].ToString(); label70.Text = ds.Tables[0].Rows[0]["ID"].ToString(); textBox1.Text = ds.Tables[0].Rows[0]["LName"].ToString(); label67.Text = ds.Tables[0].Rows[0]["LoginID"].ToString(); textBox3.Text = ds.Tables[0].Rows[0]["Date"].ToString(); textBox4.Text = ds.Tables[0].Rows[0]["Mobile"].ToString(); textBox5.Text = ds.Tables[0].Rows[0]["Email"].ToString(); } private void label47_Click(object sender, EventArgs e) { } } } User details using System; using System.Collections.Generic;
using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class usermaintain : Form { string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public usermaintain() { InitializeComponent(); } private void usermaintain_Load(object sender, EventArgs e) { //dataGridView2.Visible = false; SqlConnection con = new SqlConnection(constring); con.Open(); SqlDataAdapter da = new SqlDataAdapter("Select ID as Userid,LName as Name,LoginID as LoginID,LPassword as Password,Date as RegisteredDate,Mobile as Contactno,Email as Emailid,Signature as WatermarkSignature from Registration where LoginType='User' ", con); DataSet ds = new DataSet(); BindingSource bsourse = new BindingSource(); SqlCommandBuilder cmd = new SqlCommandBuilder(da); da.Fill(ds, "Registration"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse.DataSource = ds.Tables["Registration"]; if (ds.Tables[0].Rows.Count > 0) { dataGridView1.DataSource = bsourse; dataGridView1.Visible = true; } else { dataGridView1.Visible = false; MessageBox.Show("No Userdetails found"); }
SqlDataAdapter da1 = new SqlDataAdapter("Select userid as Userid,fileid as Fileid,secrtno as Secrectkey,filnam as Userfiles,savpath as DownloadingLocation from download ", con); DataSet ds1 = new DataSet(); BindingSource bsourse1 = new BindingSource(); SqlCommandBuilder cmd1 = new SqlCommandBuilder(da1); da1.Fill(ds1, "download"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse1.DataSource = ds1.Tables["download"]; if (ds1.Tables[0].Rows.Count > 0) { dataGridView2.DataSource = bsourse1; dataGridView2.Visible = true; } else { dataGridView2.Visible = false; MessageBox.Show("No Sending details found"); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } } Admin verift request using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class Admin : Form { string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public Admin() { InitializeComponent();
} private void Admin_Load(object sender, EventArgs e) { SqlConnection con = new SqlConnection(constring); con.Open(); SqlDataAdapter da = new SqlDataAdapter("Select id1 as Userid,autid as Fileid,sign as Signature,path as WatermarkingPath,loadfilepath as FilePath,status as Status from Embedding where status='Not Verified' ", con); DataSet ds = new DataSet(); BindingSource bsourse = new BindingSource(); SqlCommandBuilder cmd = new SqlCommandBuilder(da); da.Fill(ds, "Embedding"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse.DataSource = ds.Tables["Embedding"]; if (ds.Tables[0].Rows.Count > 0) { dataGridView1.DataSource = bsourse; dataGridView1.Visible = true; } else { dataGridView1.Visible = false; MessageBox.Show("No New Request Come"); } con.Close(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { int curRow = int.Parse(e.RowIndex.ToString()); string watrimgpath, filpath, uid, auid1, sign; uid = dataGridView1.Rows[curRow].Cells[1].Value.ToString(); auid1 = dataGridView1.Rows[curRow].Cells[2].Value.ToString(); sign = dataGridView1.Rows[curRow].Cells[3].Value.ToString(); watrimgpath = dataGridView1.Rows[curRow].Cells[4].Value.ToString(); filpath = dataGridView1.Rows[curRow].Cells[5].Value.ToString(); Edgedetection sc1 = new Edgedetection(uid, auid1, watrimgpath, sign, filpath); sc1.ShowDialog();
} private void userMaintenanceToolStripMenuItem_Click(object sender, EventArgs e) {
usermaintain um = new usermaintain(); um.Show(); } private void pictureBox2_Click(object sender, EventArgs e) { } } Admin response using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class AdminResponse : Form { string uid,aid,fid; string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public AdminResponse() { InitializeComponent(); } public AdminResponse(string strtextbox) { InitializeComponent(); uid = strtextbox; //aid=strtextbox1; } private void AdminResponse_Load(object sender, EventArgs e) { //dataGridView2.Visible = false; SqlConnection con = new SqlConnection(constring); con.Open(); SqlDataAdapter da = new SqlDataAdapter("Select userid as Userid,fileid as Fileid,secrtno as Secrectkey,filnam as Yourfile,savpath as DownloadingLocation from download where status='Sent' and userid='"+uid+"' ", con);
DataSet ds = new DataSet(); BindingSource bsourse = new BindingSource(); SqlCommandBuilder cmd = new SqlCommandBuilder(da); da.Fill(ds, "download"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse.DataSource = ds.Tables["download"]; if (ds.Tables[0].Rows.Count > 0) { fid = ds.Tables[0].Rows[0]["fileid"].ToString(); dataGridView1.DataSource = bsourse; dataGridView1.Visible = true; } else { dataGridView1.Visible = false; MessageBox.Show("No New Responses come"); } SqlDataAdapter da1 = new SqlDataAdapter("Select userid as Userid,fileid as Fileid,secrtno as Secrectkey,filnam as Yourfile,savpath as DownloadingLocation from download where status='Viewed' and userid='" + uid + "' ", con); DataSet ds1 = new DataSet(); BindingSource bsourse1 = new BindingSource(); SqlCommandBuilder cmd1 = new SqlCommandBuilder(da1); da1.Fill(ds1, "download"); //ds.Tables[0].Constraints.Add("CReqTo", ds.Tables[0].Columns[0], true); bsourse1.DataSource = ds1.Tables["download"]; if (ds1.Tables[0].Rows.Count > 0) { dataGridView2.DataSource = bsourse1; dataGridView2.Visible = true; } else { dataGridView2.Visible = false; MessageBox.Show("No Old Responses come"); }
SqlCommand cmd2 = new SqlCommand("update download set status='Viewed' where userid='" + uid + "' and fileid='" + fid + "'", con); cmd2.ExecuteNonQuery(); con.Close(); }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } } Intruder alert using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class Alerts : Form { string d,er,f,g; string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public Alerts() { InitializeComponent(); } public Alerts(string strtextbox, string strtextbox1, string strtextbox2, string strtextbox3) { InitializeComponent(); d = strtextbox; er = strtextbox1; f = strtextbox2; g = strtextbox3; } private void Alerts_Load(object sender, EventArgs e) { label6.Text = d; label7.Text = er; label8.Text = f; SqlConnection con2 = new SqlConnection(constring); con2.Open();
SqlCommand cmd1 = new SqlCommand("select Signature from Registration where ID='"+g+"'", con2); label11.Text = Convert.ToString(cmd1.ExecuteScalar()); con2.Close(); SqlConnection con3 = new SqlConnection(constring); con3.Open(); SqlCommand cmd3 = new SqlCommand("update Alerts set status='Viewed' where uid='" + g + "' and aid='"+d+"'", con3); cmd3.ExecuteNonQuery(); con3.Close(); } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == textBox2.Text) { SqlConnection con1 = new SqlConnection(constring); con1.Open(); SqlCommand cmd2 = new SqlCommand("update Registration set Signature='" + textBox2.Text + "' where ID='" + g + "'", con1); cmd2.ExecuteNonQuery(); MessageBox.Show("Successfully changed your watermarking signature"); con1.Close(); } else { MessageBox.Show("Retype Signature"); } } private void label1_Click(object sender, EventArgs e) { } } } Encrypt & Decrypt the image using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace EncryptDecrypt { public class MyEncryptor
{ // Internal value of the phrase used to generate the secret key private string _Phrase = ""; //contains input file path and name private string _inputFile = ""; //contains output file path and name private string _outputFile = ""; enum TransformType { ENCRYPT = 0, DECRYPT = 1 } /// Set the phrase used to generate the secret key. public string Phrase { set { this._Phrase = value; this.GenerateKey(this._Phrase); } } // Internal initialization vector value to // encrypt/decrypt the first block private byte[] _IV; // Internal secret key value private byte[] _Key; /// <summary> /// Constructor /// /// <param name="SecretPhrase">Secret phrase to generate key public MyEncryptor(string SecretPhrase) { this.Phrase = SecretPhrase; } /// <summary> /// Encrypt the given value with the Rijndael algorithm. /// /// <param name="EncryptValue">Value to encrypt /// Encrypted value. public string Encrypt(string EncryptValue) { try { if (EncryptValue.Length > 0) { // Write the encrypted value into memory byte[] input = Encoding.UTF8.GetBytes(EncryptValue); // Retrieve the encrypted value and return it
return (Convert.ToBase64String(Transform(input,TransformType.ENCRYPT))); } else { return ""; } } catch (Exception ex) { throw ex; } } /// <summary> /// Decrypt the given value with the Rijndael algorithm. /// /// <param name="DecryptValue">Value to decrypt /// Decrypted value. public string Decrypt(string DecryptValue) { try { if (DecryptValue.Length > 0) { // Write the encrypted value into memory byte[] input = Convert.FromBase64String(DecryptValue); // Retrieve the decrypted value and return it return (Encoding.UTF8.GetString(Transform(input,TransformType.DECRYPT))); } else { return ""; } } catch (Exception ex) { throw ex; } } /// <summary> /// Encrypt the given value with the Rijndael algorithm. /// /// <param name="EncryptValue">Value to encrypt /// Encrypted value.
public void Encrypt(string InputFile, string OutputFile) { try { if ((InputFile != null) && (InputFile.Length > 0)) { _inputFile = InputFile; } if ((OutputFile != null) && (OutputFile.Length > 0)) { _outputFile = OutputFile; } Transform(null, TransformType.ENCRYPT); } catch (Exception ex) { throw ex; } } /// <summary> /// Decrypt the given value with the Rijndael algorithm. /// /// <param name="DecryptValue">Value to decrypt /// Decrypted value. public void Decrypt(string InputFile, string OutputFile) { try { if ((InputFile != null) && (InputFile.Length > 0)) { _inputFile = InputFile; } if ((OutputFile != null) && (OutputFile.Length > 0)) { _outputFile = OutputFile; } Transform(null, TransformType.DECRYPT); } catch (Exception ex) { throw ex; } }
private void GenerateKey(string SecretPhrase)
{ // Initialize internal values this._Key = new byte[24]; this._IV = new byte[16]; // Perform a hash operation using the phrase. This will // generate a unique 32 character value to be used as the key. byte[] bytePhrase = Encoding.ASCII.GetBytes(SecretPhrase); SHA384Managed sha384 = new SHA384Managed(); sha384.ComputeHash(bytePhrase); byte[] result = sha384.Hash; // Transfer the first 24 characters of the hashed value to the key // and the remaining 8 characters to the intialization vector. for (int loop = 0; loop < 24; loop++) this._Key[loop] = result[loop]; for (int loop = 24; loop < 40; loop++) this._IV[loop - 24] = result[loop]; } private byte[] Transform(byte[] input, TransformType transformType) { CryptoStream cryptoStream = null; // Stream used to encrypt RijndaelManaged rijndael = null; // Rijndael provider ICryptoTransform rijndaelTransform = null;// Encrypting object FileStream fsIn = null; //input file FileStream fsOut = null; //output file MemoryStream memStream = null; // Stream to contain data try { // Create the crypto objects rijndael = new RijndaelManaged(); rijndael.Key = this._Key; rijndael.IV = this._IV; if (transformType == TransformType.ENCRYPT) { rijndaelTransform = rijndael.CreateEncryptor(); } else { rijndaelTransform = rijndael.CreateDecryptor(); } if ((input != null) && (input.Length > 0)) { memStream = new MemoryStream(); cryptoStream = new CryptoStream( memStream, rijndaelTransform, CryptoStreamMode.Write); cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock(); return memStream.ToArray(); } else if ((_inputFile.Length > 0) && (_outputFile.Length > 0)) { // First we are going to open the file streams fsIn = new FileStream(_inputFile, FileMode.Open, FileAccess.Read); fsOut = new FileStream(_outputFile, FileMode.OpenOrCreate, FileAccess.Write); cryptoStream = new CryptoStream( fsOut, rijndaelTransform, CryptoStreamMode.Write); // Now will will initialize a buffer and will be // processing the input file in chunks. // This is done to avoid reading the whole file (which can be // huge) into memory. int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // Encrypt it cryptoStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); cryptoStream.FlushFinalBlock(); } return null; } catch (CryptographicException) { throw new CryptographicException("Password is invalid. Please verify once again."); } finally { if (rijndael != null) rijndael.Clear(); if (rijndaelTransform != null) rijndaelTransform.Dispose(); if (cryptoStream != null) cryptoStream.Close(); if (memStream != null) memStream.Close(); if (fsOut != null) fsOut.Close(); if (fsIn != null) fsIn.Close();
} } } } Secure file sending using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; using System.Configuration; namespace WaterMark { public partial class Mainform : Form { string uid, auid, fpath; private bool hasNewFiles; string constring = Convert.ToString(ConfigurationSettings.AppSettings["ConnectionString"]); public Mainform() { InitializeComponent(); } public Mainform(string strtextbox, string strtextbox1, string strtextbox2) { InitializeComponent(); uid = strtextbox; auid = strtextbox1; fpath = strtextbox2; } private void UnZipFiles(string destinationDirectoryName) { ICSharpCode.WaterMark.Zip.ZipFile zipFile = new ICSharpCode.WaterMark.Zip.ZipFile(txtZipFileName.Text); if (chkDecrypt.Checked) { //decrypt zip file zipFile.Password = txtOpenPassword.Text; } foreach (ListViewItem viewItem in lvAll.SelectedItems) {
ICSharpCode.WaterMark.Zip.ZipEntry zipEntry = viewItem.Tag as ICSharpCode.WaterMark.Zip.ZipEntry; if (zipEntry != null) { Stream inputStream = zipFile.GetInputStream(zipEntry); FileStream fileStream = new FileStream( Path.Combine(destinationDirectoryName, zipEntry.Name), FileMode.Create); CopyStream(inputStream, fileStream); fileStream.Close(); inputStream.Close(); } } zipFile.Close(); } private void ZipFiles(string destinationFileName, string password) { FileStream outputFileStream = new FileStream(destinationFileName, FileMode.Create); ICSharpCode.WaterMark.Zip.ZipOutputStream zipStream = new ICSharpCode.WaterMark.Zip.ZipOutputStream(outputFileStream); ICSharpCode.WaterMark.Zip.ZipFile zipFile = null; if (txtZipFileName.Text.Length > 0) { //there may be files to copy from annother archive zipFile = new ICSharpCode.WaterMark.Zip.ZipFile(txtZipFileName.Text); if (txtOpenPassword.Text.Length > 0) { zipFile.Password = txtOpenPassword.Text; } } bool isCrypted = false; if (password != null && password.Length > 0) { //encrypt the zip file, if password != null zipStream.Password = password; isCrypted = true; } foreach (ListViewItem viewItem in lvAll.Items) { ICSharpCode.WaterMark.Zip.ZipEntry zipEntry = viewItem.Tag as ICSharpCode.WaterMark.Zip.ZipEntry; Stream inputStream; if (zipEntry == null) { inputStream = new FileStream(viewItem.Text, FileMode.Open); zipEntry = new ICSharpCode.WaterMark.Zip.ZipEntry(Path.GetFileName(viewItem.Text));
} else { inputStream = zipFile.GetInputStream(zipEntry); } zipEntry.IsVisible = viewItem.Checked; zipEntry.IsCrypted = isCrypted; zipEntry.CompressionMethod = ICSharpCode.WaterMark.Zip.CompressionMethod.Deflated; zipStream.PutNextEntry(zipEntry); CopyStream(inputStream, zipStream); inputStream.Close(); zipStream.CloseEntry(); } if (zipFile != null) { zipFile.Close(); } zipStream.Finish(); zipStream.Close(); } private void CopyStream(Stream source, Stream destination) { byte[] buffer = new byte[4096]; int countBytesRead; while ((countBytesRead = source.Read(buffer, 0, buffer.Length)) > 0) { destination.Write(buffer, 0, countBytesRead); } } private String GetFileName(String filter) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = filter; dlg.RestoreDirectory = true; if (dlg.ShowDialog(this) == DialogResult.OK) { return dlg.FileName; } else { return null; } }
private void AddListViewItem(ICSharpCode.WaterMark.Zip.ZipEntry zipEntry, ListView listView) { ListViewItem viewItem = new ListViewItem(zipEntry.Name); viewItem.SubItems.Add(zipEntry.CompressedSize.ToString()); viewItem.Checked = zipEntry.IsVisible; viewItem.Tag = zipEntry; listView.Items.Add(viewItem); } private void ExtractSelectedFiles() { FolderBrowserDialog dlg = new FolderBrowserDialog(); if (dlg.ShowDialog(this) == DialogResult.OK) { UnZipFiles(dlg.SelectedPath); } } private void Open() { this.HasNewFiles = false; lvAll.Items.Clear(); lvVisible.Items.Clear(); if (txtZipFileName.Text.Length > 0) { ICSharpCode.WaterMark.Zip.ZipEntry zipEntry; ICSharpCode.WaterMark.Zip.ZipFile zipFile = new ICSharpCode.WaterMark.Zip.ZipFile(txtZipFileName.Text); if (chkDecrypt.Checked) { //decrypt zip file zipFile.Password = txtOpenPassword.Text; } // list visible files for (int n = 0; n < zipFile.Size; n++) { zipEntry = zipFile[n]; AddListViewItem(zipFile[n], lvVisible); } // list all files zipEntry = zipFile[0]; AddListViewItem(zipEntry, lvAll); int entryIndex = 0; while (zipFile.HasSuccessor(zipEntry)) {
zipEntry = zipFile.GetAttachedEntry(zipEntry); AddListViewItem(zipEntry, lvAll); entryIndex++; } zipFile.Close(); } } private void btnSelectFile_Click(object sender, EventArgs e) { string fileName = GetFileName("Zip-Archive (*.zip)|*.zip"); if (fileName != null) { txtZipFileName.Text = fileName; } } private void btnSelectNewFile_Click(object sender, EventArgs e) { string fileName = GetFileName(string.Empty); if (fileName != null) { txtNewFileName.Text = fileName; } } private void btnOpenZipFile_Click(object sender, EventArgs e) { Open(); } private void btnAdd_Click(object sender, EventArgs e) { if (label6.Text == txtNewFileName.Text) { ListViewItem viewItem = new ListViewItem(txtNewFileName.Text); lvAll.Items.Add(viewItem); viewItem.Checked = chkAddVisible.Checked; this.HasNewFiles = true; } else { MessageBox.Show("Choose the mentioned file path"); } } private void btnSave_Click(object sender, EventArgs e) { if (!lvAll.Items[0].Checked)
{ MessageBox.Show("The first file has to be visible, because it's our only anchor in the central directory."); } else { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Zip-Archive (*.zip)|*.zip"; dlg.RestoreDirectory = true; if (dlg.ShowDialog(this) == DialogResult.OK) { ZipFiles(dlg.FileName, (chkEncrypt.Checked ? txtSavePassword.Text : null)); txtZipFileName.Text = dlg.FileName; txtOpenPassword.Text = txtSavePassword.Text; chkDecrypt.Checked = chkEncrypt.Checked; Open(); } } SqlConnection con = new SqlConnection(constring); con.Open(); SqlCommand cmd1 = new SqlCommand("Insert into download values ('" + uid + "','" + auid + "','" + fpath + "','" + txtSavePassword.Text + "','"+txtZipFileName.Text+"','Sent')", con); cmd1.ExecuteNonQuery(); con.Close(); MessageBox.Show("Successfully sent the authenticated user Requested file"); } private void lvAll_ItemChecked(object sender, ItemCheckedEventArgs e) { if (e.Item.Checked) { //add to visible list lvVisible.Items.Add(e.Item.Clone() as ListViewItem); } else { //remove from visible list foreach (ListViewItem viewItem in lvVisible.Items) { if (viewItem.Text == e.Item.Text) { lvVisible.Items.Remove(viewItem); break; } } } } private void lvAll_DoubleClick(object sender, EventArgs e)
{ ExtractSelectedFiles(); } private void btnExtract_Click(object sender, EventArgs e) { ExtractSelectedFiles(); } private void lvAll_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { ListViewItem[] deletedItems = new ListViewItem[lvAll.SelectedItems.Count]; lvAll.SelectedItems.CopyTo(deletedItems, 0); foreach (ListViewItem viewItem in deletedItems) { lvAll.Items.Remove(viewItem); } } } private void btnUp_Click(object sender, EventArgs e) { if (lvAll.SelectedItems.Count > 0) { ListViewItem selectedItem = lvAll.SelectedItems[0]; if (selectedItem.Index > 0) { int index = selectedItem.Index; ListViewItem upperItem = lvAll.Items[selectedItem.Index - 1]; upperItem.Remove(); lvAll.Items.Insert(index, upperItem); selectedItem.Selected = true; } } } private void btnDown_Click(object sender, EventArgs e) { if (lvAll.SelectedItems.Count > 0) { ListViewItem selectedItem = lvAll.SelectedItems[0]; if (selectedItem.Index < lvAll.Items.Count - 1) { int index = selectedItem.Index; ListViewItem lowerItem = lvAll.Items[selectedItem.Index + 1]; lowerItem.Remove(); lvAll.Items.Insert(index, lowerItem); selectedItem.Selected = true;
} } } private void chkEncrypt_CheckedChanged(object sender, EventArgs e) { txtSavePassword.Enabled = chkEncrypt.Checked; } private void chkDecrypt_CheckedChanged(object sender, EventArgs e) { txtOpenPassword.Enabled = chkDecrypt.Checked; } private void btnCreate_Click(object sender, EventArgs e) { this.HasNewFiles = true; txtZipFileName.Text = string.Empty; lvAll.Items.Clear(); lvVisible.Items.Clear(); } private bool HasNewFiles { //encryption of new files doesn't work for unknown reasons set { this.hasNewFiles = value; chkEncrypt.Enabled = !value; } get { return hasNewFiles; } } private void Mainform_Load(object sender, EventArgs e) { label6.Text = fpath; } } }