include name space "using System.Net.Mail;"
make function say sendmail in that,
sendmail()
{
// Details of SMTP server.
SmtpClient MailObj= new SmtpClient(SMTP_Server);
//Define USER ID and Password for SMTP Server Account
NetworkCredential cred = new NetworkCredential(SMTP_Authentication_User, SMTP_Authentication_Password);
//Assign that Credentials to Mail Object
MailObj.Credentials = cred;
//Define the email details as below.
//Note that multiple email address for to can be given by "," sign
MailObj.Send(from, to, subject, body);
}
Tuesday, September 30, 2008
Tuesday, August 19, 2008
Wednesday, August 6, 2008
Grid - Code Approach
This code handle the grid. Manual with code approach Edit,delete records from grid.
Create table with following columns
Eno bigint - autoincrement
name varchar(100)
salary bigint
ASPX.cs Code - default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("cn").ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
bindgrid();
}
}
private void bindgrid()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from emp", cn);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_eno");
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name");
TextBox txtsalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_salary");
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
SqlCommand cmd = new SqlCommand("update emp set name='" + txtname.Text + "',salary=" + txtsalary.Text + " where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_no");
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
SqlCommand cmd = new SqlCommand("delete from emp where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
}
Create table with following columns
Eno bigint - autoincrement
name varchar(100)
salary bigint
ASPX.cs Code - default.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("cn").ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
bindgrid();
}
}
private void bindgrid()
{
SqlDataAdapter ad = new SqlDataAdapter("select * from emp", cn);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_eno");
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name");
TextBox txtsalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_salary");
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
SqlCommand cmd = new SqlCommand("update emp set name='" + txtname.Text + "',salary=" + txtsalary.Text + " where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lbleno = (Label)GridView1.Rows[e.RowIndex].FindControl("lbl_no");
if (cn.State != ConnectionState.Open)
{
cn.Open();
}
SqlCommand cmd = new SqlCommand("delete from emp where eno=" + lbleno.Text, cn);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
bindgrid();
}
}
Monday, July 21, 2008
Thumbnails-Part1
High resolution thumbnails with dynamic width and height
This code will check the image original height and width and accordingly will create the
thumb by setting its suitable thumb height and width. Will give high resolution thumb and
also image will not be blur or squeeze. Name space needed
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
Path - path of original file where located
Width,height - will be supplied as perameter.
Will create new thumbnail on c:\hello.jpg
System.Drawing.Image img = System.Drawing.Image.FromFile(Path);
int srcWidth = img.Width;
int srcHeight = img.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
height = Decimal.ToInt32(sizeRatio * width);
if (height > 250)
height = 250;
Size sz = new Size(width, height);
using (Bitmap bmp = new Bitmap(Path))
{
using (Bitmap bmpThumb = new Bitmap((System.Drawing.Image)bmp, sz))
{
using (Graphics grp = Graphics.FromImage(bmpThumb))
{
grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
grp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
grp.DrawImage(bmp, new Rectangle(0, 0, bmpThumb.Width, bmpThumb.Height));
string strDestPath = "c:\\hello.jpg"; // you can give your path where you want to create file
bmpThumb.Save(strDestPath, codec, eParams);
}
}
}
This code will check the image original height and width and accordingly will create the
thumb by setting its suitable thumb height and width. Will give high resolution thumb and
also image will not be blur or squeeze. Name space needed
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
Path - path of original file where located
Width,height - will be supplied as perameter.
Will create new thumbnail on c:\hello.jpg
System.Drawing.Image img = System.Drawing.Image.FromFile(Path);
int srcWidth = img.Width;
int srcHeight = img.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
height = Decimal.ToInt32(sizeRatio * width);
if (height > 250)
height = 250;
Size sz = new Size(width, height);
using (Bitmap bmp = new Bitmap(Path))
{
using (Bitmap bmpThumb = new Bitmap((System.Drawing.Image)bmp, sz))
{
using (Graphics grp = Graphics.FromImage(bmpThumb))
{
grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
grp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
grp.DrawImage(bmp, new Rectangle(0, 0, bmpThumb.Width, bmpThumb.Height));
string strDestPath = "c:\\hello.jpg"; // you can give your path where you want to create file
bmpThumb.Save(strDestPath, codec, eParams);
}
}
}
Friday, July 18, 2008
Silverlight 2.0 - Part2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Net;
using System.Windows.Media.Imaging;
using System.IO;
using System.Text;
using System.Windows.Threading;
namespace Video_Dialog
{
public partial class Page : UserControl
{
private DispatcherTimer timer;
private bool IsVideoScrubberLocked { get; set; }
OpenFileDialog dlg = new OpenFileDialog();
private double unmutedVolume;
public Page()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(50);
timer.Tick += new EventHandler(timer_Tick);
sliderScrubber.MouseLeftButtonUp += new MouseButtonEventHandler(sliderScrubber_MouseLeftButtonUp);
sliderScrubber.MouseLeftButtonDown += new MouseButtonEventHandler(sliderScrubber_MouseLeftButtonDown);
sliderVolume.ValueChanged += new RoutedPropertyChangedEventHandler(sliderVolume_ValueChanged);
}
void MyVideo_MediaOpened(object sender, RoutedEventArgs e)
{
sliderVolume.Value = MyVideo.Volume;
}
void sliderVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
{
MyVideo.Volume = sliderVolume.Value;
}
void sliderScrubber_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsVideoScrubberLocked = true;
}
void sliderScrubber_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
IsVideoScrubberLocked = false;
MyVideo.Position = TimeSpan.FromMilliseconds(
MyVideo.NaturalDuration.TimeSpan.TotalMilliseconds * sliderScrubber.Value);
}
void timer_Tick(object sender, EventArgs e)
{
if (MyVideo.NaturalDuration.TimeSpan.TotalSeconds > 0 && !IsVideoScrubberLocked)
{
txtVideoPosition.Text =
string.Format("{0:00}:{1:00}", MyVideo.Position.Minutes, MyVideo.Position.Seconds);
sliderScrubber.Value = MyVideo.Position.TotalSeconds /
MyVideo.NaturalDuration.TimeSpan.TotalSeconds;
}
}
void MyVideo_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (MyVideo.CurrentState == MediaElementState.Playing)
{
timer.Start();
}
else
{
timer.Stop();
}
}
private void btReadFile_Click(object sender, RoutedEventArgs e)
{
dlg.Filter = "MP3 Files (*.mp3)|*.mp3|WMA Files (*.wma)|*.wma|Wmv Files (*.wmv)|*.wmv";
dlg.Multiselect = false;
// Show the open file dialog
dlg.ShowDialog();
}
private void btnPlayPause_Click(object sender, RoutedEventArgs e)
{
MyVideo.Pause();
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
if (dlg.SelectedFile != null)
{
// Set the source as the local file
MyVideo.SetSource(dlg.SelectedFile.OpenRead());
}
MyVideo.Play();
}
private void btnMute_Click(object sender, RoutedEventArgs e)
{
MyVideo.Volume = 0;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Net;
using System.Windows.Media.Imaging;
using System.IO;
using System.Text;
using System.Windows.Threading;
namespace Video_Dialog
{
public partial class Page : UserControl
{
private DispatcherTimer timer;
private bool IsVideoScrubberLocked { get; set; }
OpenFileDialog dlg = new OpenFileDialog();
private double unmutedVolume;
public Page()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(50);
timer.Tick += new EventHandler(timer_Tick);
sliderScrubber.MouseLeftButtonUp += new MouseButtonEventHandler(sliderScrubber_MouseLeftButtonUp);
sliderScrubber.MouseLeftButtonDown += new MouseButtonEventHandler(sliderScrubber_MouseLeftButtonDown);
sliderVolume.ValueChanged += new RoutedPropertyChangedEventHandler
}
void MyVideo_MediaOpened(object sender, RoutedEventArgs e)
{
sliderVolume.Value = MyVideo.Volume;
}
void sliderVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs
{
MyVideo.Volume = sliderVolume.Value;
}
void sliderScrubber_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsVideoScrubberLocked = true;
}
void sliderScrubber_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
IsVideoScrubberLocked = false;
MyVideo.Position = TimeSpan.FromMilliseconds(
MyVideo.NaturalDuration.TimeSpan.TotalMilliseconds * sliderScrubber.Value);
}
void timer_Tick(object sender, EventArgs e)
{
if (MyVideo.NaturalDuration.TimeSpan.TotalSeconds > 0 && !IsVideoScrubberLocked)
{
txtVideoPosition.Text =
string.Format("{0:00}:{1:00}", MyVideo.Position.Minutes, MyVideo.Position.Seconds);
sliderScrubber.Value = MyVideo.Position.TotalSeconds /
MyVideo.NaturalDuration.TimeSpan.TotalSeconds;
}
}
void MyVideo_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (MyVideo.CurrentState == MediaElementState.Playing)
{
timer.Start();
}
else
{
timer.Stop();
}
}
private void btReadFile_Click(object sender, RoutedEventArgs e)
{
dlg.Filter = "MP3 Files (*.mp3)|*.mp3|WMA Files (*.wma)|*.wma|Wmv Files (*.wmv)|*.wmv";
dlg.Multiselect = false;
// Show the open file dialog
dlg.ShowDialog();
}
private void btnPlayPause_Click(object sender, RoutedEventArgs e)
{
MyVideo.Pause();
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
if (dlg.SelectedFile != null)
{
// Set the source as the local file
MyVideo.SetSource(dlg.SelectedFile.OpenRead());
}
MyVideo.Play();
}
private void btnMute_Click(object sender, RoutedEventArgs e)
{
MyVideo.Volume = 0;
}
}
}
Monday, July 7, 2008
Cookies,Session
Purpose - Accessing session,cookies in your class files.
say,
I am using one global function that check that wether user session is
expired or not in that case i have created one class file. Now to access
values of session in the class file i can call the function like
cls_Check_Sessoin objSession=new cls_Check_Sessoin();
protected void Page_Load(object sender, EventArgs e)
{
if(objSession.IsAuthenticated(this.Context))
{
some porocess code;
}
else
{
Response.Redirect("Login.aspx");// will be called if session is expired
}
}
//-------------------In my class file i have function that check the page session
//--values like
public static bool IsAuthenticated(HttpContext context)
{
if (context.Session["User"] == null)
{
return false;
}
else
{
return true;
}
}
say,
I am using one global function that check that wether user session is
expired or not in that case i have created one class file. Now to access
values of session in the class file i can call the function like
cls_Check_Sessoin objSession=new cls_Check_Sessoin();
protected void Page_Load(object sender, EventArgs e)
{
if(objSession.IsAuthenticated(this.Context))
{
some porocess code;
}
else
{
Response.Redirect("Login.aspx");// will be called if session is expired
}
}
//-------------------In my class file i have function that check the page session
//--values like
public static bool IsAuthenticated(HttpContext context)
{
if (context.Session["User"] == null)
{
return false;
}
else
{
return true;
}
}
Thumbnails-Part2
Need to include following name spaces
using System.Drawing;
using System.Drawing.Drawing2D;
-------------Code-------------
int width=200;
int height=200;
string Path=server.mappath(".") + "\\UploadPhotos\\hello_old.jpg";
System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Path);
Bitmap SmallBitmap = new Bitmap(width, height, OriginalImage.PixelFormat);
Graphics SmallImg = Graphics.FromImage(SmallBitmap);
SmallImg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
SmallImg.DrawImage(OriginalImage, 0, 0, SmallBitmap.Width, SmallBitmap.Height);
//Print to the browser
context.Response.ContentType = "image/jpeg";
SmallBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
string NewFileName = "";
SmallBitmap.Save(server.mappath(".") + ""\\UploadPhotos\\hello.jpg", ImageFormat.Jpeg);
SmallImg.Dispose();
SmallImg.Dispose();
using System.Drawing;
using System.Drawing.Drawing2D;
-------------Code-------------
int width=200;
int height=200;
string Path=server.mappath(".") + "\\UploadPhotos\\hello_old.jpg";
System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Path);
Bitmap SmallBitmap = new Bitmap(width, height, OriginalImage.PixelFormat);
Graphics SmallImg = Graphics.FromImage(SmallBitmap);
SmallImg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
SmallImg.DrawImage(OriginalImage, 0, 0, SmallBitmap.Width, SmallBitmap.Height);
//Print to the browser
context.Response.ContentType = "image/jpeg";
SmallBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
string NewFileName = "";
SmallBitmap.Save(server.mappath(".") + ""\\UploadPhotos\\hello.jpg", ImageFormat.Jpeg);
SmallImg.Dispose();
SmallImg.Dispose();
To get IP Address
object obj = new object();
obj = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (obj == null)
{
obj = Request.ServerVariables["REMOTE_ADDR"];
}
obj = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (obj == null)
{
obj = Request.ServerVariables["REMOTE_ADDR"];
}
Encryption Decryption - ASP .Net , C#
Decryption Code
string passPhrase = "DevNetCor"; // can be any string
string saltValue = "test@key"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
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 ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
cipherText = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
--------Encryption Code
string passPhrase = "DevNetCor"; // can be any string
string saltValue = "test@key"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(saltValue);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
plainText = Convert.ToBase64String(cipherTextBytes);
string passPhrase = "DevNetCor"; // can be any string
string saltValue = "test@key"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
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 ciphertext;
// plaintext is never longer than ciphertext.
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
cipherText = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
--------Encryption Code
string passPhrase = "DevNetCor"; // can be any string
string saltValue = "test@key"; // can be any string
string hashAlgorithm = "MD5"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
byte[] initVectorBytes = System.Text.Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(saltValue);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
byte[] keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
RijndaelManaged symmetricKey = new RijndaelManaged();
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
symmetricKey.Mode = CipherMode.CBC;
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
MemoryStream memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
plainText = Convert.ToBase64String(cipherTextBytes);
Subscribe to:
Posts (Atom)