Você está na página 1de 19

Data uploading and Encryption:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace ASPEncryptDecryptFile
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateUploadedFiles();
}
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Download")
{
string filePath = e.CommandArgument.ToString();
// key for decryption
byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");

//UnicodeEncoding ue = new UnicodeEncoding();


FileStream fs = new FileStream(filePath, FileMode.Open);
RijndaelManaged rmCryp = new RijndaelManaged();
CryptoStreamMode cs = new CryptoStream(fs, rmCryp.CreateDecryptor(Key, Key),
CryptoStreamMode.Read);

{
// Decrypt & Download Here
Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition","attachment; filename=" +
Path.GetFileName(filePath) + Path.GetExtension(filePath));
Response.AddHeader("Content-Disposition", "attachment; filename=myfile" +
Path.GetExtension(filePath));
int data;
while ((data = cs.ReadByte()) != -1)
{
Response.OutputStream.WriteByte((byte)data);
Response.Flush();

}
cs.Close();
fs.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cs.Close();
fs.Close();
}
}
}

protected void btnUpload_Click(object sender, EventArgs e)


{
// Add code to upload file with encryption

byte[] file = new byte[FileUpload1.PostedFile.ContentLength];


FileUpload1.PostedFile.InputStream.Read(file, 0,
FileUpload1.PostedFile.ContentLength);

string fileName = FileUpload1.PostedFile.FileName;

// key for encryption


byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");
try
{
string outputFile = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
if (File.Exists(outputFile))
{
// Show Already exist Message
}
else
{
FileStream fs = new FileStream(outputFile, FileMode.Create);
RijndaelManaged rmCryp = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key),
CryptoStreamMode.Write);

foreach (var data in file)


{
cs.WriteByte((byte)data);
}
cs.Close();
fs.Close();
}

PopulateUploadedFiles();
}
catch
{
Response.Write("Encryption Failed! Please try again.");
}
}

private void PopulateUploadedFiles()


{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/UploadedFiles"));
List<UploadFile> uploadedFiles = new List<UploadFile>();
foreach (var file in di.GetFiles())
{
uploadedFiles.Add
(
new UploadFile
{
FileName = file.Name,
FileExtention = Path.GetExtension(file.Name),
FilePath = file.FullName,
Size = (file.Length / 1024), // For get size in KB
ICon = GetIconPath(Path.GetExtension(file.FullName)) // Need to Get Icon...
}
);
}

DataList1.DataSource = uploadedFiles;
DataList1.DataBind();
}
private string GetIconPath(string fileExtention)
{
string Iconpath = "/Images";
string ext = fileExtention.ToLower();
switch (ext)
{
case ".txt":
Iconpath += "/txt.png";
break;
case ".doc":
case ".docx":
Iconpath += "/word.png";
break;
case ".xls":
case ".xlsx":
Iconpath += "/xls.png";
break;
case ".pdf":
Iconpath += "/pdf.png";
break;
case ".rar":
Iconpath += "/rar.png";
break;
case ".zip":
case ".7z":
Iconpath += "/zip.png";
break;
default:
break;
}
return Iconpath;
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASPEncryptDecryptFile
{
public class UploadFile
{
public string FileName { get; set; }
public string FileExtention { get; set; }
public long Size { get; set; }
public string FilePath { get; set; }
public string ICon { get; set; }

}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="AspEncrptDecrpt1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>File Upload with encryption and Download with decryption using ASP.NET C#. </h3>
<div>
<table>
<tr>
<td>Select File : </td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload & Encrypt"
OnClick="btnUpload_Click" /></td>
</tr>
</table>
<div>
<%-- Add Datalist for Show Uploaded Files --%>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4"
RepeatDirection="Horizontal" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td>
<img src='<%#Eval("ICon") %>' width="60px" />
</td>
</tr>
<tr>
<td>
<%#Eval("FileName") %>
</td>
</tr>
<tr>
<td>
<%#Eval("Size","{0} KB") %>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="Download" CommandArgument='<%#Eval("FilePath")
%>'>Download</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</div>

</div>
</form>
</body>
</html>

}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{

}
public void Auto()
{
int r;
cmd1 = new SqlCommand("Select max(Clientid) from ClientDetails", con);
dr1 = cmd1.ExecuteReader();

if (dr1.Read())
{

string d = dr1[0].ToString();
if (d == "")
{

txtUid.Text = "1001";

}
else
{

r = Convert.ToInt32(dr1[0].ToString());
r = r + 1;
txtUid.Text = r.ToString();
}
}
}

protected void SendEmail(object sender, EventArgs e)


{

}
protected void txtEmail_TextChanged(object sender, EventArgs e)
{

File Upload :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public partial class UploadFiles : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
txtuserid.Text = Request.QueryString["Clientid"];
}

String connectionString =
ConfigurationManager.ConnectionStrings["SECURE"].ConnectionString;
con = new SqlConnection(connectionString);

Auto();

}
private void PopulateUploadedFiles()
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/UploadedFiles"));
List<UploadFile> uploadedFiles = new List<UploadFile>();
foreach (var file in di.GetFiles())
{
uploadedFiles.Add
(
new UploadFile
{
FileName = file.Name,
FileExtention = Path.GetExtension(file.Name),
FilePath = file.FullName,
Size = (file.Length / 1024), // For get size in KB
Icon = GetIconPath(Path.GetExtension(file.FullName)) // Need to Get Icon...
}
);
}

//DataList1.DataSource = uploadedFiles;
//DataList1.DataBind();
}
public void uploadsave()
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Files/" + filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into
FileInfo(Userid,Fileid,FileName,FileDesc,FilePath,Approved)
values(@Userid,@Fileid,@Name,@FileDesc,@Path,@Approved)", con);
cmd.Parameters.AddWithValue("@userid", txtuserid.Text);
cmd.Parameters.AddWithValue("@Fileid",txtfileid.Text);
cmd.Parameters.AddWithValue("@Name", filename);
cmd.Parameters.AddWithValue("@FileDesc", txtFileDescription.Text);
cmd.Parameters.AddWithValue("@Path", "Files/" + filename);
cmd.Parameters.AddWithValue("@Approved","False");
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('Upload success')</script>");
con.Close();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{

}
public void Auto()
{
con.Open();
int r;
cmd = new SqlCommand("Select max(Fileid) from FileInfo", con);
dr = cmd.ExecuteReader();

if (dr.Read())
{

string d = dr[0].ToString();
if (d == "")
{

txtfileid.Text = "01";

}
else
{

r = Convert.ToInt32(dr[0].ToString());
r = r + 1;
txtfileid.Text = r.ToString();
}
}
con.Close();
}
protected void btnUpload_Click(object sender, EventArgs e)
{

byte[] file = new byte[FileUpload1.PostedFile.ContentLength];


FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength);

string fileName = FileUpload1.PostedFile.FileName;

// key for encryption


byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");
try
{
string outputFile = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
// string outputFile = Path.Combine(Server.MapPath("D:"), fileName);
if (File.Exists(outputFile))
{
// Show Already exist Message
}
else
{
FileStream fs = new FileStream(outputFile, FileMode.Create);
RijndaelManaged rmCryp = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key),
CryptoStreamMode.Write);
foreach (var data in file)
{
cs.WriteByte((byte)data);
}
cs.Close();
fs.Close();
}

PopulateUploadedFiles();
}
catch
{
Response.Write("Encryption Failed! Please try again.");
}
uploadsave();
}

private string GetIconPath(string fileExtention)


{
string Iconpath = "/Images";
string ext = fileExtention.ToLower();
switch (ext)
{
case ".txt":
Iconpath += "/txt.png";
break;
case ".doc":
case ".docx":
Iconpath += "/word.png";
break;
case ".xls":
case ".xlsx":
Iconpath += "/xls.png";
break;
case ".pdf":
Iconpath += "/pdf.png";
break;
case ".rar":
Iconpath += "/rar.png";
break;
case ".zip":
case ".7z":
Iconpath += "/zip.png";
break;
default:
break;
}
return Iconpath;
}

protected void btnCreate_Click(object sender, EventArgs e)


{
{
string strpath = @"D:\" + txtName.Text;
//Condition to check if any directory exists with same name
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
}
}

File Details Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class Default17 : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
String connectionString =
ConfigurationManager.ConnectionStrings["SECURE"].ConnectionString;
con = new SqlConnection(connectionString);

if (!IsPostBack)
{
BindGridviewData();
}

}
private void BindGridviewData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from FileInfo ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
protected void chk_Click(object sender, EventArgs e)
{
CheckBox chkbox = sender as CheckBox;
GridViewRow gvrow = chkbox.NamingContainer as GridViewRow;
if (chkbox.Checked == true)
{

}
protected void gvDetails_SelectedIndexChanged(object sender, EventArgs e)
{

}
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;

string Uid = row.Cells[0].Text;


string Fid = row.Cells[1].Text;
string FileName = row.Cells[2].Text;
string FileDesc = row.Cells[3].Text;
string FilePath = row.Cells[4].Text;

string Approved = row.Cells[5].Text;


bool status = chkStatus.Checked;

string query = "UPDATE FileInfo SET Approved = @Approved WHERE Fileid =


@Fileid";

SqlCommand com = new SqlCommand(query, con);

com.Parameters.Add("@Approved", SqlDbType.Bit).Value = status;

com.Parameters.Add("@Userid", SqlDbType.Int).Value = Uid;


com.Parameters.Add("@Fileid", SqlDbType.VarChar).Value = Fid;
com.Parameters.Add("@FileName", SqlDbType.VarChar).Value = FileName;
com.Parameters.Add("@FileDesc", SqlDbType.VarChar).Value = FileDesc;

con.Open();
com.ExecuteNonQuery();
con.Close();

BindGridviewData();
}
}

Renewal Account:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class Renewal : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
String connectionString =
ConfigurationManager.ConnectionStrings["SECURE"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
lblSecurityKey.Visible = false;
if (!IsPostBack)
{
txtUid.Text = Request.QueryString["userid"];
txtUserName.Text = Request.QueryString["username"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{

cmd = new SqlCommand("update UserReg set Mode='Active' where Userid='"


+txtUid.Text + "'", con);
cmd.ExecuteNonQuery();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('Renewal success')</script>");

txtUid.Text = "";
txtUserName.Text = "";
txtPassword.Text = "";

txtTo.Text = "";
txtSecurityAns.Text = "";
lblSecurityKey.Text = "";
}
protected void Button2_Click1(object sender, EventArgs e)
{
txtUid.Text = "";
txtUserName.Text = "";
txtPassword.Text = "";
txtTo.Text = "";
txtSecurityAns.Text = "";
lblSecurityKey.Text = "";
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{

}
}

Send File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Net.Mail;

public partial class UploadFiles : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd, cmd1;
SqlDataReader dr, dr1;

protected void Page_Load(object sender, EventArgs e)


{
lblsendermail.Visible = false;
lblsenderpass.Visible = false;
lblsendermail.Text = "nasurudeenid@gmail.com";
lblsenderpass.Text = "8807503727";
String connectionString =
ConfigurationManager.ConnectionStrings["SECURE"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
}
protected void btnForward_Click(object sender, EventArgs e)
{
string to = txtReceivemail.Text;
string from = lblsendermail.Text;
string subject = txtFileDesc.Text;
// string body = txtBody.Text;
using (MailMessage mm = new MailMessage(lblsendermail.Text, txtReceivemail.Text))
{
mm.Subject = txtFileDesc.Text;
// mm.Body = txtBody.Text;
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream,
FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(lblsendermail.Text,
lblsenderpass.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);

txtuserid.Text = "";
txtReceivemail.Text = "";
txtFileDesc.Text = "";

protected void txtuserid_Leave(object sender, EventArgs e)


{
}
protected void ddlreceiver_SelectedIndexChanged(object sender, EventArgs e)
{

txtReceivemail.Text = string.Empty;
cmd1 = new SqlCommand("Select * From UserDetails WHERE Userid = " +
ddlreceiver.SelectedItem.Text, con);
dr1 = cmd1.ExecuteReader();
if (dr1.HasRows)
{
while (dr1.Read())
{
txtReceivemail.Text =dr1.GetString(4);

}
}
dr1.Close();

}
}

Receive File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public partial class Receivemsg : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd1;
SqlDataReader dr;

protected void Page_Load(object sender, EventArgs e)


{
lblDate.Text = System.DateTime.Now.ToString();
btnDecrypt.Visible = false;
String connectionString =
ConfigurationManager.ConnectionStrings["SECURE"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
btnDecrypt.Visible = true;

lblEncryptedText.Text = string.Empty;
cmd1 = new SqlCommand("Select * From msgdetails WHERE securekey
='"+txtkey.Text+"' and receiverid = " + txtuserid.Text, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{

lblEncryptedText.Text = dr.GetString(5);

dr.Close();
}

else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert(' Access Denined , Invaild Security Key')</script>");
}

}
protected void Decrypt(object sender, EventArgs e)
{
lblDecryptedText.Text = this.Decrypt(lblEncryptedText.Text.Trim());
}

private string Decrypt(string cipherText)


{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{ 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(),
CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
protected void Button1_Click(object sender, EventArgs e)
{

}
}

Você também pode gostar