There are two types of Encryption:
1- One way Encryption:
take input data and encrypt it, and there is no way to decrypt it again to get the source data and the good sample for one way encryption is MD5.
also the good sample for one way encryption (SQL Server Membership), it's store passwords encrypted and there is nno way to get the original Password.
only we can compare between the source you enterd and the hashed data.
2- Two way Encryption:
take input data and encrypt it, and in another side we can take encrypted data and decrypt it again using the same algorithm.
Sample:
http://waleedelkot.blogspot.com/2009/02/encryption-and-decryption-using-c.html
today I'll talk about MD5 and SHA1 and I'll Present a sample code.
Namespace: System.Security.Cryptography
the below method will return MD5 hashed string:
private string GetMD5HashData(string data)
{
MD5 md5 = MD5.Create();
byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i <>
{
returnValue.Append(hashData[i].ToString());
}
return returnValue.ToString();
}
the below method will return MD5 hashed string:
private string GetSHA1HashData(string data)
{
SHA1 sha1 = SHA1.Create();
byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i <>
{
returnValue.Append(hashData[i].ToString());
}
return returnValue.ToString();
}
you can save the return value in Database and check it in the another side like SQL Server Membership.
that's great, but How can I Validate input Data and stored hashed data in Database?
the below method will validate MD5 hashed string:
private bool ValidateMD5HashData(string inputData, string storedHashData)
{
string getHashInputData = GetMD5HashData(inputData);
if (string.Compare(getHashInputData, storedHashData) == 0)
{
return true;
}
else
{
return false;
}
}
the below method will validate SHA1 hashed string:
private bool ValidateSHA1HashData(string inputData, string storedHashData)
{
string getHashInputData = GetSHA1HashData(inputData);
if (string.Compare(getHashInputData, storedHashData) == 0)
{
return true;
}
else
{
return false;
}
}
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Wednesday, August 12, 2009
How To: Convert Text to Image Using C#
I'll show you how to convert any string to image and save it in your hard disk drive.
also you can use this sample code to prevent your website content from spiders.
there are many benfits.
1- Create Windows Forms Application.
2- Add Button Control on Form.
3- Add TextBox Control on Form and set Multiline to TRUE.
Sample Code:
public Color FontColor { get; set; }
public Color FontBackColor { get; set; }
public string FontName { get; set; }
public string ImagePath { get; set; }
public int FontSize { get; set; }
public int ImageHeight { get; set; }
public int ImageWidth { get; set; }
public Bitmap ImageText { get; set; }
public Graphics ImageGraphics { get; set; }
public Font ImageFont { get; set; }
public SolidBrush BrushForeColor { get; set; }
public SolidBrush BrushBackColor { get; set; }
public PointF ImagePointF { get; set; }
private void DrawText(string text)
{
FontColor = Color.Red;
FontBackColor = Color.Yellow;
FontName = "Arial";
FontSize = 10;
ImageHeight = textBox1.Height;
ImageWidth = textBox1.Width;
ImagePath = @"C:\WaleedImageTest.JPEG";
ImageText = new Bitmap(ImageWidth, ImageHeight);
ImageGraphics = Graphics.FromImage(ImageText);
ImageFont = new Font(FontName, FontSize);
ImagePointF = new PointF(5, 5);
BrushForeColor = new SolidBrush(FontColor);
BrushBackColor = new SolidBrush(FontBackColor);
ImageGraphics.FillRectangle(BrushBackColor, 0, 0, ImageWidth, ImageHeight);
ImageGraphics.DrawString(text, ImageFont, BrushForeColor, ImagePointF);
ImageText.Save(ImagePath, ImageFormat.Jpeg);
}
private void button1_Click(object sender, EventArgs e)
{
DrawText(textBox1.Text);
}
Then Run Your Application.
also you can use this sample code to prevent your website content from spiders.
there are many benfits.
1- Create Windows Forms Application.
2- Add Button Control on Form.
3- Add TextBox Control on Form and set Multiline to TRUE.
Sample Code:
public Color FontColor { get; set; }
public Color FontBackColor { get; set; }
public string FontName { get; set; }
public string ImagePath { get; set; }
public int FontSize { get; set; }
public int ImageHeight { get; set; }
public int ImageWidth { get; set; }
public Bitmap ImageText { get; set; }
public Graphics ImageGraphics { get; set; }
public Font ImageFont { get; set; }
public SolidBrush BrushForeColor { get; set; }
public SolidBrush BrushBackColor { get; set; }
public PointF ImagePointF { get; set; }
private void DrawText(string text)
{
FontColor = Color.Red;
FontBackColor = Color.Yellow;
FontName = "Arial";
FontSize = 10;
ImageHeight = textBox1.Height;
ImageWidth = textBox1.Width;
ImagePath = @"C:\WaleedImageTest.JPEG";
ImageText = new Bitmap(ImageWidth, ImageHeight);
ImageGraphics = Graphics.FromImage(ImageText);
ImageFont = new Font(FontName, FontSize);
ImagePointF = new PointF(5, 5);
BrushForeColor = new SolidBrush(FontColor);
BrushBackColor = new SolidBrush(FontBackColor);
ImageGraphics.FillRectangle(BrushBackColor, 0, 0, ImageWidth, ImageHeight);
ImageGraphics.DrawString(text, ImageFont, BrushForeColor, ImagePointF);
ImageText.Save(ImagePath, ImageFormat.Jpeg);
}
private void button1_Click(object sender, EventArgs e)
{
DrawText(textBox1.Text);
}
Then Run Your Application.
Tuesday, August 11, 2009
How To: Convert Image to String Using C#
the easy way to convert any image to string is :
1- Convert Image to Memory Stream.
2- Convert Memory Stream to Base64String.
so in this sample code I will convert the image to string and I'll save this string in text file.
private string ConvertImage(Bitmap sBit)
{
MemoryStream imageStream = new MemoryStream();
sBit.Save(imageStream, ImageFormat.Jpeg);
return Convert.ToBase64String(imageStream.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap sBit = new Bitmap(@"C:\bmw.jpg");
string imageString = ConvertImage(sBit);
StreamWriter sw = new StreamWriter(@"C:\waleedelkot.text", false);
sw.Write(imageString);
sw.Close();
}
1- Convert Image to Memory Stream.
2- Convert Memory Stream to Base64String.
so in this sample code I will convert the image to string and I'll save this string in text file.
private string ConvertImage(Bitmap sBit)
{
MemoryStream imageStream = new MemoryStream();
sBit.Save(imageStream, ImageFormat.Jpeg);
return Convert.ToBase64String(imageStream.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap sBit = new Bitmap(@"C:\bmw.jpg");
string imageString = ConvertImage(sBit);
StreamWriter sw = new StreamWriter(@"C:\waleedelkot.text", false);
sw.Write(imageString);
sw.Close();
}
Sunday, May 31, 2009
How To: Enable Allow Paging in Repeater Using C#
1- I'll Show You how to make a repeater that allow paging.
2- I'll Make a web user control and anyone Can use it in his project.
Steps:
1- Create A web user control using C# and rename it to RepeaterPager.
2- add four Buttons and one label:
Control Name Text
Button btnNext >
Button btnPrevious <
Button btnLastRecord >>
Button btnFirstRecord <<
3- Create property for Object Data Source:
public ObjectDataSource Ods { get; set; }
4- Create Property for Repeater Control Or DataList As you like:
public Repeater Rep { get; set; }
5- Create Property Get Current Page:
public int CurrentPage
{
get
{
object obj = this.ViewState["_CurrentPage"];
if (obj == null)
{
return 0;
}
else
{
return (int)obj;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
6- Bind Data in Repeater Control and Return number of Pages:
public int ItemsGet()
{
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = Ods.Select();
int x = objPds.Count;
objPds.AllowPaging = true;
objPds.PageSize = 1;
objPds.CurrentPageIndex = CurrentPage;
if (objPds.Count > 0)
{
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLastRecord.Visible = true;
btnFirstRecord.Visible = true;
lblCurrentPage.Visible = true;
lblCurrentPage.Text = "Page: " + Convert.ToString(CurrentPage + 1) + " of " + Convert.ToString(objPds.PageCount);
}
else
{
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLastRecord.Visible = false;
btnFirstRecord.Visible = false;
lblCurrentPage.Visible = false;
}
btnPrevious.Enabled = !objPds.IsFirstPage;
btnNext.Enabled = !objPds.IsLastPage;
btnLastRecord.Enabled = !objPds.IsLastPage;
btnFirstRecord.Enabled = !objPds.IsFirstPage;
Rep.DataSource = objPds;
Rep.DataBind();
return x;
}
7- Buttons Controls Code:
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
ItemsGet();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
ItemsGet();
}
protected void btnLastRecord_Click(object sender, EventArgs e)
{
CurrentPage = ItemsGet() -1;
ItemsGet();
}
protected void btnFirstRecord_Click(object sender, EventArgs e)
{
CurrentPage = 0;
ItemsGet();
}
8- in (Web User Control) Load Event call GetItems Property:
protected void Page_Load(object sender, EventArgs e)
{
ItemsGet();
}
How To Use this Control:
1- Create ASP.Net Page
2- Add Repeater1 and ObjectDataSource1 to your page
3- in Page_load Event Put the following code:
protected void Page_Load(object sender, EventArgs e)
{
RepeaterPager.Ods= Repeater1;
RepeaterPager.Rep= ObjectDataSource1;
}
4- Build and run :)
2- I'll Make a web user control and anyone Can use it in his project.
Steps:
1- Create A web user control using C# and rename it to RepeaterPager.
2- add four Buttons and one label:
Control Name Text
Button btnNext >
Button btnPrevious <
Button btnLastRecord >>
Button btnFirstRecord <<
3- Create property for Object Data Source:
public ObjectDataSource Ods { get; set; }
4- Create Property for Repeater Control Or DataList As you like:
public Repeater Rep { get; set; }
5- Create Property Get Current Page:
public int CurrentPage
{
get
{
object obj = this.ViewState["_CurrentPage"];
if (obj == null)
{
return 0;
}
else
{
return (int)obj;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
6- Bind Data in Repeater Control and Return number of Pages:
public int ItemsGet()
{
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = Ods.Select();
int x = objPds.Count;
objPds.AllowPaging = true;
objPds.PageSize = 1;
objPds.CurrentPageIndex = CurrentPage;
if (objPds.Count > 0)
{
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLastRecord.Visible = true;
btnFirstRecord.Visible = true;
lblCurrentPage.Visible = true;
lblCurrentPage.Text = "Page: " + Convert.ToString(CurrentPage + 1) + " of " + Convert.ToString(objPds.PageCount);
}
else
{
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLastRecord.Visible = false;
btnFirstRecord.Visible = false;
lblCurrentPage.Visible = false;
}
btnPrevious.Enabled = !objPds.IsFirstPage;
btnNext.Enabled = !objPds.IsLastPage;
btnLastRecord.Enabled = !objPds.IsLastPage;
btnFirstRecord.Enabled = !objPds.IsFirstPage;
Rep.DataSource = objPds;
Rep.DataBind();
return x;
}
7- Buttons Controls Code:
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
ItemsGet();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
ItemsGet();
}
protected void btnLastRecord_Click(object sender, EventArgs e)
{
CurrentPage = ItemsGet() -1;
ItemsGet();
}
protected void btnFirstRecord_Click(object sender, EventArgs e)
{
CurrentPage = 0;
ItemsGet();
}
8- in (Web User Control) Load Event call GetItems Property:
protected void Page_Load(object sender, EventArgs e)
{
ItemsGet();
}
How To Use this Control:
1- Create ASP.Net Page
2- Add Repeater1 and ObjectDataSource1 to your page
3- in Page_load Event Put the following code:
protected void Page_Load(object sender, EventArgs e)
{
RepeaterPager.Ods= Repeater1;
RepeaterPager.Rep= ObjectDataSource1;
}
4- Build and run :)
Saturday, May 23, 2009
How To: Use Office 2007 OCR Using C#
I'll Show you how to read text from any image.
If you have Office 2007 installed, the OCR component is available for you to use. The only dependency that's added to your software is Office 2007. Requiring Office 2007 to be installed in order for your software to work may or may not fit a situation. But if your client can guarantee that machines that your software will run on have Office 2007 installed, you're gold. I've encountered many situations where this is the case. I've even encountered a few situations where clients were willing to install Office 2007 in order to use my applications.
Steps:
1- add Reference to Office 2007 Component:
The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed as shown in the figure to the right.
Important Note:The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed.
2- Create Windows Application Using C#:
from Visual Studio Solution Explorer >> right click on refferences>> select com tab>> then select (Microsoft Office Document Imaging 12.0 Type Library)
3- Put Button in your Form then put the following code:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
MODI.Document md = new MODI.Document();
md.Create(openFileDialog.FileName);
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image image = (MODI.Image)md.Images[0];
MessageBox.Show(image.Layout.Text, "The Selected Image Text is:");
4- Run The Application then press the button and select any image has text.
Conclusion:
I made a big sample application for Office OCR, if anyone interested, you can contact me on :
waleed.hussein.eg@gmail.com
If you have Office 2007 installed, the OCR component is available for you to use. The only dependency that's added to your software is Office 2007. Requiring Office 2007 to be installed in order for your software to work may or may not fit a situation. But if your client can guarantee that machines that your software will run on have Office 2007 installed, you're gold. I've encountered many situations where this is the case. I've even encountered a few situations where clients were willing to install Office 2007 in order to use my applications.
Steps:
1- add Reference to Office 2007 Component:
The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed as shown in the figure to the right.
Important Note:The name of the COM object that you need to add as a reference is Microsoft Office Document Imaging 12.0 Type Library. By default, Office 2007 doesn't install it. You'll need to make sure that it's added by using the Office 2007 installation program. Just run the installer, click on the Continue button with the "Add or Remove Features" selection made, and insure that the imaging component is installed.
2- Create Windows Application Using C#:
from Visual Studio Solution Explorer >> right click on refferences>> select com tab>> then select (Microsoft Office Document Imaging 12.0 Type Library)
3- Put Button in your Form then put the following code:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
MODI.Document md = new MODI.Document();
md.Create(openFileDialog.FileName);
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image image = (MODI.Image)md.Images[0];
MessageBox.Show(image.Layout.Text, "The Selected Image Text is:");
4- Run The Application then press the button and select any image has text.
Conclusion:
I made a big sample application for Office OCR, if anyone interested, you can contact me on :
waleed.hussein.eg@gmail.com
Friday, May 22, 2009
How To: Sending Email Using C#
in this article I'll show you how can you send mail using windows application
I'm using gmail becouse it allowed sending and recieving Emails and you need to make some configurations like:
Host Name: smtp.gmail.com
Port Number: 587
Your Email Address: yourEmail@gamil.com
your Password: your Email Password
SSL:true (becouse gmail using ssl)
Let's start...
Create Windows Application using C# :
Create Form Like the Below Form with Controls
Important Note Controls Names Will be Like:
textbox =txt...
label=lbl...
button=btn...

using System.Net;
using System.Net.Mail;
then create some properities :
you can put them in seperated class but I'm putted them in the same form because it's a sample
public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailBody { get; set; }
public string MailSubject { get; set; }
public string AttachmentFile { get; set; }
public string HostName { get; set; }
public int PortNumber { get; set; }
public string EmailAddress { get; set; }
public string EmailPassword { get; set; }
public bool SSL { get; set; }
then create method for sending mail:
public void SendingMail()
{
MailMessage mailMessage = new MailMessage(MailFrom,MailTo,MailSubject,MailBody);
Attachment fileAttachment = new Attachment(AttachmentFile);
mailMessage.Attachments.Add(fileAttachment);
SmtpClient smtpClient = new SmtpClient(HostName,PortNumber);
smtpClient.Credentials = new NetworkCredential(EmailAddress,EmailPassword);
smtpClient.EnableSsl = SSL;
smtpClient.Send(mailMessage);
}
in attachment button put the following code:
private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
lblAttachment.Text = fileDialog.FileName;
}
in Send Mail Button put the following code:
private void btnSendMail_Click(object sender, EventArgs e)
{
try
{
MailFrom = txtMailAddress.Text; ;
MailTo = txtTo.Text;
MailBody = txtBody.Text;
MailSubject = txtSubject.Text;
AttachmentFile = lblAttachment.Text;
HostName = txtHostName.Text;
PortNumber = Convert.ToInt16(txtPortNo.Text);
EmailAddress = txtMailAddress.Text;
EmailPassword = txtMailPassword.Text;
SSL = chkSSL.Checked;
SendingMail();
MessageBox.Show("Sending Mail Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm using gmail becouse it allowed sending and recieving Emails and you need to make some configurations like:
Host Name: smtp.gmail.com
Port Number: 587
Your Email Address: yourEmail@gamil.com
your Password: your Email Password
SSL:true (becouse gmail using ssl)
Let's start...
Create Windows Application using C# :
Create Form Like the Below Form with Controls
Important Note Controls Names Will be Like:
textbox =txt...
label=lbl...
button=btn...
using System.Net;
using System.Net.Mail;
then create some properities :
you can put them in seperated class but I'm putted them in the same form because it's a sample
public string MailFrom { get; set; }
public string MailTo { get; set; }
public string MailBody { get; set; }
public string MailSubject { get; set; }
public string AttachmentFile { get; set; }
public string HostName { get; set; }
public int PortNumber { get; set; }
public string EmailAddress { get; set; }
public string EmailPassword { get; set; }
public bool SSL { get; set; }
then create method for sending mail:
public void SendingMail()
{
MailMessage mailMessage = new MailMessage(MailFrom,MailTo,MailSubject,MailBody);
Attachment fileAttachment = new Attachment(AttachmentFile);
mailMessage.Attachments.Add(fileAttachment);
SmtpClient smtpClient = new SmtpClient(HostName,PortNumber);
smtpClient.Credentials = new NetworkCredential(EmailAddress,EmailPassword);
smtpClient.EnableSsl = SSL;
smtpClient.Send(mailMessage);
}
in attachment button put the following code:
private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
lblAttachment.Text = fileDialog.FileName;
}
in Send Mail Button put the following code:
private void btnSendMail_Click(object sender, EventArgs e)
{
try
{
MailFrom = txtMailAddress.Text; ;
MailTo = txtTo.Text;
MailBody = txtBody.Text;
MailSubject = txtSubject.Text;
AttachmentFile = lblAttachment.Text;
HostName = txtHostName.Text;
PortNumber = Convert.ToInt16(txtPortNo.Text);
EmailAddress = txtMailAddress.Text;
EmailPassword = txtMailPassword.Text;
SSL = chkSSL.Checked;
SendingMail();
MessageBox.Show("Sending Mail Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Wednesday, February 25, 2009
How to Connect to Team Foundation Server Using C#
In this article I will show you how to connect to Team Foundation Server and add work item via code
First thing you must install TFS SDK, you can download the Team Foundation Server SDK from the below link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=7e0fdd66-698a-4e6a-b373-bd0642847ab7&DisplayLang=en
Steps:
1- Create windows or web Application
2- Add References for :
Microsoft.TeamFoundation.Client
Microsoft.TeamFoundation.WorkItemTracking.Client
3- The below code will help you to work with Team Foundation Server
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
// declaration variable
private NetworkCredential networkCredential = new NetworkCredential("enter here User Name", "enter here password", "enter here domian");
private Uri uri = new Uri("enter here TFS URL");
string projectName="enter here TFS prject name";
string worktemType = "enter here Work Item Type";
// Set Authentication To TFS
TeamFoundationServer teamFoundationServer = new TeamFoundationServer(uri.AbsoluteUri, networkCredential);
teamFoundationServer.Authenticate();
//Add Work Item
WorkItemStore wis = (WorkItemStore)teamFoundationServer.GetService(typeof(WorkItemStore));
Project tfsProject = wis.Projects[projectName];
WorkItemType wiType = tfsProject.WorkItemTypes[workItemType];
WorkItem workItem = new WorkItem(wiType);
workItem.Title = "Test Work Item";
workItem.Description = "Work Item Description";
workItem.Save();
First thing you must install TFS SDK, you can download the Team Foundation Server SDK from the below link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=7e0fdd66-698a-4e6a-b373-bd0642847ab7&DisplayLang=en
Steps:
1- Create windows or web Application
2- Add References for :
Microsoft.TeamFoundation.Client
Microsoft.TeamFoundation.WorkItemTracking.Client
3- The below code will help you to work with Team Foundation Server
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
// declaration variable
private NetworkCredential networkCredential = new NetworkCredential("enter here User Name", "enter here password", "enter here domian");
private Uri uri = new Uri("enter here TFS URL");
string projectName="enter here TFS prject name";
string worktemType = "enter here Work Item Type";
// Set Authentication To TFS
TeamFoundationServer teamFoundationServer = new TeamFoundationServer(uri.AbsoluteUri, networkCredential);
teamFoundationServer.Authenticate();
//Add Work Item
WorkItemStore wis = (WorkItemStore)teamFoundationServer.GetService(typeof(WorkItemStore));
Project tfsProject = wis.Projects[projectName];
WorkItemType wiType = tfsProject.WorkItemTypes[workItemType];
WorkItem workItem = new WorkItem(wiType);
workItem.Title = "Test Work Item";
workItem.Description = "Work Item Description";
workItem.Save();
Tuesday, February 3, 2009
How To: Encrypt and Decrypt string Using C#
I think Any Developer need to protect his data from nasty people
Ex. We will assume we have an application (windows application – web application ….etc) will connect to
Active directory or Team Foundation Server or any application need authentication to connect to it
First thing any developer should thinking about how I made my application secured
So when we pass the credentials will pass it Encrypted and from another side will decrypt these credentials.
In this article I’ll show you how to encrypt any string and decrypt it.
Create a new windows application using C# the design will be something like the below image:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
namespace RsaEncryption
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private static string sKey = "UJYHCX783her*&5@$%#(MJCX**38n*#6835ncv56tvbry(&#MX98cn342cn4*&X#&";
public static string Encrypt(string sPainText)
{
if (sPainText.Length == 0)
return (sPainText);
return (EncryptString(sPainText, sKey));
}
public static string Decrypt(string sEncryptText)
{
if (sEncryptText.Length == 0)
return (sEncryptText);
return (DecryptString(sEncryptText, sKey));
}
protected static string EncryptString(string InputText, string Password)
{
// "Password" string variable is nothing but the key(your secret key) value which is sent from the front end.
// "InputText" string variable is the actual password sent from the login page.
// We are now going to create an instance of the
// Rihndael class.
RijndaelManaged RijndaelCipher = new RijndaelManaged();
// First we need to turn the input strings into a byte array.
byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);
// We are using Salt to make it harder to guess our key
// using a dictionary attack.
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
// The (Secret Key) will be generated from the specified
// password and Salt.
//PasswordDeriveBytes -- It Derives a key from a password
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a encryptor from the existing SecretKey bytes.
// We use 32 bytes for the secret key
// (the default Rijndael key length is 256 bit = 32 bytes) and
// then 16 bytes for the IV (initialization vector),
// (the default Rijndael IV length is 128 bit = 16 bytes)
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
// Create a MemoryStream that is going to hold the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Create a CryptoStream through which we are going to be processing our data.
// CryptoStreamMode.Write means that we are going to be writing data
// to the stream and the output will be written in the MemoryStream
// we have provided. (always use write mode for encryption)
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
// Start the encryption process.
cryptoStream.Write(PlainText, 0, PlainText.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memoryStream into a byte array.
byte[] CipherBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
// A common mistake would be to use an Encoding class for that.
// It does not work, because not all byte values can be
// represented by characters. We are going to be using Base64 encoding
// That is designed exactly for what we are trying to do.
string EncryptedData = Convert.ToBase64String(CipherBytes);
// Return encrypted string.
return EncryptedData;
}
protected static string DecryptString(string InputText, string Password)
{
try
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(InputText);
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
// Create a decryptor from the existing SecretKey bytes.
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(EncryptedData);
// Create a CryptoStream. (always use Read mode for decryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold EncryptedData;
// DecryptedData is never longer than EncryptedData.
byte[] PlainText = new byte[EncryptedData.Length];
// Start decrypting.
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
// Return decrypted string.
return DecryptedData;
}
catch (Exception exception)
{
return (exception.Message);
}
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
txtEncryption.Text= Encrypt(txtPassword.Text);
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
MessageBox.Show(Decrypt(txtEncryption.Text));
}
}
}
Subscribe to:
Posts (Atom)