Hi
Storing password in database as encrypted form is the good practice to store password. We can do this task using so many algorithms.
But here I m going to show you one of the easiest and complete secure method to encrypt and decrypt the password.
If you are storing password as encrypted formate using any algorithm without any salt value. Then hacker can easily decrypt the password using decryption method of same alogorith. But if you are using some salt value in your encrypted password then it will give completely strong encrtypted password.
Here we are mixing random salt value in encrtpted password.So It will be impossible to hack the data from database.
Here are some steps to do this tasks
Step1: Create one class i.e “Helper.cs” and write method like this.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Salt_Password_Sample { public class Helper { public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { // If salt is not specified, generate it. if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; } public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue) { // Convert base64-encoded hash value into a byte array. byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Make sure that hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Size of hash is based on the specified algorithm. switch (hashAlgorithm.ToUpper()) { case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. byte[] saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashAlgorithm, saltBytes); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); } } }
Step2: Call that method in code behind file like this.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Salt_Password_Sample { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void EncryptBtn_Click(object sender, EventArgs e) { string EPass = Helper.ComputeHash(TextBox1.Text, "SHA512", null); lblmsg.Text = EPass; } protected void Button1_Click(object sender, EventArgs e) { bool flag = Helper.VerifyHash(TextBox1.Text, "SHA512", lblmsg.Text); if (flag == true) { lblmsg1.Text = "You are the correct user"; } } } }
If you are implementing this code with database then do like this,at insert time code will be like this
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 Salt_Password_Sample; public partial class EmpReg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private void Cleartextbox() { txtAddress.Text = string.Empty; txtContactNo.Text = string.Empty; txtEmpName.Text = string.Empty; txtPassword.Text = string.Empty; txtUserId.Text = string.Empty; } protected void btnSubmit_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True")) { using (SqlCommand cmd = new SqlCommand("Insert into tblLogin(UserId,Password,EmpName,Address,ContactNo) values(@UserId,@Password,@EmpName,@Address,@ContactNo)", con)) { cmd.Parameters.AddWithValue("@UserId", txtUserId.Text); //Here i have implemented the code for doing encryption of password string ePass = Helper.ComputeHash(txtPassword.Text, "SHA512", null); cmd.Parameters.AddWithValue("@Password", ePass); cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text); cmd.Parameters.AddWithValue("@Address", txtAddress.Text); cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text); con.Open(); cmd.ExecuteNonQuery(); con.Close(); Cleartextbox(); lblmsg.Text = "Your profile has been created Sucessfully"; } } } }
At login time,we have to write code like this, But make ensure that UserId should be unique in database
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 Salt_Password_Sample; public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True")) { using(SqlCommand cmd=new SqlCommand("Select UserId,Password from tblLogin where UserId=@UserId",con)) { cmd.Parameters.AddWithValue("@UserId", txtUserName.Text); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); string userid = dt.Rows[0]["UserId"].ToString(); string password=dt.Rows[0]["Password"].ToString(); bool flag = Helper.VerifyHash(txtPassword.Text, "SHA512", password); if (userid == txtUserName.Text && flag == true) { Response.Redirect("Welcome.aspx"); } else { lblmsg.Text = "Invalid UserId or password"; } txtPassword.Text = string.Empty; txtUserName.Text = string.Empty; } } } }
For forget password you can do like this.
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 Salt_Password_Sample; public partial class ForgetPassword : System.Web.UI.Page { SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"); protected void Page_Load(object sender, EventArgs e) { } protected void btnUpdate_Click(object sender, EventArgs e) { string flag = CheckUserId(); if (flag == "true") { using (SqlCommand cmd = new SqlCommand("update tblLogin set Password=@Password where UserId=@UserId", con)) { cmd.Parameters.AddWithValue("@UserId", txtUserId.Text); //Here i have implemented the code for doing encryption of password string ePass = Helper.ComputeHash(txtPassword.Text, "SHA512", null); cmd.Parameters.AddWithValue("@Password", ePass); con.Open(); cmd.ExecuteNonQuery(); con.Close(); lblmsg.Text = "Your password has been Updated Sucessfully"; } } } private string CheckUserId() { using (SqlCommand cmd = new SqlCommand("Select UserId from tblLogin where UserId=@UserId", con)) { cmd.Parameters.AddWithValue("@UserId", txtUserId.Text); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count == 1) { return "true"; } else { lblmsg.Text = "Invalid UserId"; txtPassword.Text = string.Empty; return "false"; } } } }
Note:Before writting this article i read a lot on this topic.
I have tried to make completely secure code,But still if you think it is not a complete secure or hacker can hack the password, then fell free to share your idea.
You can download the code from here
thanks dude…. really encrypt and decrypt password in asp.net helped me a lot…
Hi
You are always welcome. I will always post useful article like this.
Hi Chandra,
I was really looking for the encryption deception code to use in my website. could you please send me the source of this. It will be really very helpful.
thanks.
It works for encryption not for decryption…….
Error is occurred during decryption and error is
catch (Exception ex)
Line 63: {
Line 64: throw new Exception(“Error in base64Decode” + ex.Message);
Line 65: }
Line 66:
base64DecodeInvalid length for a Base-64 char array.
Hi
Are you calling the decryption method like this
string str = EncryptionTest.base64Decode(Label1.Text);
Label2.Text = str;
hi i used
string str = EncryptionTest.base64Decode(Label1.Text);
Label2.Text = str;
these to decrypt a value but it returns some symbols not the original pwd.is there is any more function missing?becoz u used GetChars right..its my doubt..plz help me
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
the problem is not with GetChars(), but with this piece of code, Convert.FromBase64String(sData), I guess
Can you please mail me the source code.
Thank you
Hi arun,
I have sent the code to email Id. Please check it.
Hi
There is not missing any things. It is working perfect. I will send this code to your email id. You check it.
Hi Chandra – thank a lot for your solution – its the best so far I’ve come across. Although I’m using VS2005, I have successfully used the code to store encryption anyway. However, I also have the same problem of error “Invalid lengthfor a Base-64 char array, at System.Convert.FromBase64String(String s)” when trying to decrypt. Could you send me solution. Thanks.
Have you downloaded the latest code ? In latest code, i have not use the direct decryption process, i m using there some salt value.
Could you tell me, when are you getting this error ?Please check the latest code. while testing in my system, i didnot get any error.
Can you send me the decryption code for the above example. it has only encryption code.
can you please send to me also
hi,
this code works for pwd 6 charecters only,
if i want more than 6 char what can i do
please help me
Hi
It should be work for more than 6 character. You can also see in screen shot.where i have used the name which is more than 6 char. Could you tell me what type of errors are you getting ?
excellent…its working gr8
thanks !
nice work. not only is it simple ,but it also easily use. thank you very much for your contribution.
I m glad to know. You are welcome
Thank you
You are welcome
Thank’s it’s working fine
Sure. I will send you.
thanku
Nice Article
Hi Thank you so much this is very usefull for all. Good Keep on your work…
You are welcome to my blog.I will try to keep on posting artical like this.
How I should save a encryoted password in a database. Can u please help me?
Thank you,
Megana
Thanking You, for your code, and now how can i save this encrypted password in database table.
Sorry, password has been encrypted and saved into database, but while i use this
string str = EncryptionTest.base64Decode(Label1.Text);
Label2.Text = str;, i couldn’t get the decrypted password from the database.
Hi
Please download the code from share folder. I have also tested with database for you. Let me inform if you will get any problem.
Sorry, password has been encrypted and saved into database, but while i use this
string str = EncryptionTest.base64Decode(Label1.Text);
Label2.Text = str;, i couldn’t get the decrypted password from the database.
Hi,
this is senthil. when i have used in your decryption code i have error in (“Error in base64Decode” + ex.Message); “Error in base64DecodeInvalid length for a Base-64 char array.”. i want to just decrypt my password from my database table. please help me.
Hi friend,
I m really sorry for late reply. Nowadays i m not free getting time for checking my mail and my blog.
Since i got so many request from other person to upload code. So i m going to upload this code in my share folder. Please download from there.
Hi friends,
You can download my code from here. I have used VS2008 with inbuilt Sqlserver Express database.
https://skydrive.live.com/?qt=shared&cid=4b1f6c3e92f6522c#cid=4B1F6C3E92F6522C&id=4B1F6C3E92F6522C!125
Regards
Chandradev
Hi Chandra Dev,
Thank you, very much for your reply.
Hi,
I’m getting the decrypted password in a label, but I’m using a login page I want to login with the decrypted password in the textbox. But, the textbox is taking only the encrypted password. What can i do for this. I’m using Mysql connection. Waiting for you reply.
Hi @T. Megana Nesalin Rose, I have uploaded the exact code on basis of your request. But i have done with SQlServer and C#. Please download the code and check it. You have to only change connection string..
Hi i got encrypt and decrypt password thanks boss.
Hi,
Thank you very much, I got it. Your article is very useful for us. Publish even more articles like this
Sure i will keep on sharing useful artical. Nowadays i m working on window based project so i m not getting time to write some artical. But i love web technology, in free time i used to keep on posting useful artical.
Hi,
Can u send some examples about how to authenticate and authorize users for login page, which has roles such as admin and super admin. How can we set this in web.config file and coding for this.
Hi @T. Megana Nesalin Rose, sure i will do. I have already tested code on that topic. I will share it.
hi Chandra,
Hope u fine
I want to build my own web service with encrypted soap header.
Please help about this.
I search many sites but there is not proper solution find.
I m fine.Please give me some time,I will share artical on this topic.
Hi sir, hope u r doing great
My requirement is to store the value of textbox into database in encypted format. I know how to save data in database using C#.net. But I don’t know how to encrypt the user data. Also I need to get the password in decrypted format too. How can I do that
Hi sir, Please download the code from my share folder and check it. I have used this concept. if you will get any problem then let me know.
hi sir, hope u r fine
i inserted the multiple images by using grid view control. In database the images are stored in binary data format. i want to store in encrypted format. can u please help me out…..
please view my code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnupload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != “”)
{
byte[] myimage = new byte[(FileUpload1.PostedFile.ContentLength)+1];
byte[] myimage1 = new byte[(FileUpload2.PostedFile.ContentLength)+1];
HttpPostedFile image = FileUpload1.PostedFile;
image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
HttpPostedFile image1 = FileUpload2.PostedFile;
image1.InputStream.Read(myimage1, 0, (int)FileUpload2.PostedFile.ContentLength);
SqlConnection con = new SqlConnection(“Data Source=.;Initial Catalog=sample;User ID=sa;Password=123”);
con.Open();
SqlCommand cmd = new SqlCommand(“insert into tbl_multiple values(@ImageName,@Image,@Image1)”, con);
cmd.Parameters.Add(“@ImageName”, txtimagename.Text);
cmd.Parameters.Add(“@Image”, SqlDbType.Image, (myimage.Length)+1).Value = myimage;
cmd.Parameters.Add(“@Image1”, SqlDbType.Image, (myimage1.Length)+1).Value = myimage1;
cmd.ExecuteNonQuery();
con.Close();
}
}
protected void btnencrypt_Click(object sender, EventArgs e)
{
string val = txtimagename.Text;
string pass = EncryptionTest.base64Encode(val);
lblencrypt.Text = pass;
}
protected void btndecrypt_Click(object sender, EventArgs e)
{
string str = EncryptionTest.base64Decode(lbldecrypt.Text);
lbldecrypt.Text = str;
}
}
Hi sir, I am fine.
For storing multiple images in database as binary format is not a good approach in real project. If you will do like this, then loading of images will be very slow. If internet speed is slow, then you will also get exception error.
For doing this type of task, we can store “Image URL” path in database and Images in “Images” folder. so at the time of loading, It will take only Image URL from database. So there will be no that much server overload.
Here i don’t think any advantage to store image as encrypted format in database.It is not the sensitive data. If you want to protect the image for being download by other then we can do using other approach. Please let me know, what do you want to do ?
Regards
Chandradev
sir actually i am new to this .net recently i got a job. actually what ever the code i gave images are storing in binary data. but i have to store images in encrypt format.after completion then again i have to decrypt and retrieve the images this is want i want sir
i hope u will give the best answer sir with coding
and one more i want chating code sir…………….
Dear friend,
whatever you are going to do, it is not a good habit, we donot implement this concept in big project.
You check this URL
https://chandradev819.wordpress.com/2010/07/10/how-to-store-imageurl-into-database-and-deleting-image-from-image-folder/
If you will still get problem, let me know i will send more simplified code to you in free time.
Since you are learner, Please keep on asking question on http://forums.asp.net/ . There so many expert people are there. They will send quick reply
Hi
For chat messenger, is you requirement like this ?
http://forums.asp.net/t/1713493.aspx/1?Chat+application+on+the+Website
thanku sir for giving me a reply .accepting as ur frnd and for suggestion also……..
Hi
You are welcome. I also used to learn like you. I have updated my previous artical. It was not a good approach to do this task. Please check the latest code. It is so secure as compare to previous.
I am trying to enter this string to decode but not getting anything:
“0FFAAE00-417D-49F6-98AA-C0CCEEBFE9F9”. Can you please decode?
Thanks
thanks i got answer of my doubt.its good.
the above encryption used is hashing????
do u knw the code 4 auto sms???? …v want to add ds feature in our website…
Nowadays i m so busy in my new job. I cant open my blog in my office. Yes,this approach is not a complete secure.Please give me some time, i have to update my artical with complete secure code.
For sending sms, you have to integrate “SMS API” in your project. The service provider company will give that “API Code” with sample. It will be very easy to integrate.But that will be payable service.
Hi,
Nice to read your blog i liked it.My question is that i am creating user using ASP.NET configuration tool and it saves user password in encrypted format but i am unable to decrypt the password from the above method as i am trying to implement forgot password functionality any idea or suggestion ??? for reference here is my code
[HttpPost]
public ActionResult Index(ForgotPassword obj)
{
var result = from password in DataContext.aspnet_Membership
where password.Email == obj.Emailid
select password.Password;
foreach(string password in result)
{
pw = password;
}
if (pw != null)
{
FormsAuthenticationTicket Ftk = FormsAuthentication.Decrypt(pw);
//It gives error at this line
i am including using System.Web.Security; namespace
Any ideas…………………………
Please give me some time to check your code.
Please give me some time to check your code.
hi sir how r u.hope u r doing great.
sir i want in the given website the mouse cursor will be there know. when the cursor will move in webpage automatically the text should be also move with that cursor.For this i wnat java script please help me out as soon as possible. i hope u will sir……
for example see the given below url u can know what ever the code i have wrriten above
http://aipeukoraputdivision.blogspot.in/2010/07/new-symbol-of-indian-currency.html
Dear Sir,
i m geting this error when im decrypting the password, please help me
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Source Error:
Line 137: public static string Decrypt(string encryptedString)
Line 138: {
Line 139: FormsAuthenticationTicket Ftk = FormsAuthentication.Decrypt(encryptedString);
Line 140: return Ftk.Name;
Line 141: }
Nice Article.. Thanks you sir..
Regarding the error:valid Base-64 string as it contains a non-base 64 character,
Even I have got the sam error,but i got to know the reaosn for that.
The decryption algorythm works only for the encrypted data,If you try to decrypt a normal string it is returning the above error..
for 1024 encryption http://aspnettutorialonline.blogspot.com/2012/05/encryption-and-decryption-in-aspnet.html
Hi
Please use the latest code of this artical.
Hi Chandra,
I have tried this code but its not working with me,
can you pl. tell me where is the latest code you have mentioned here.
and if you please send me the code on my mail if posible
id: naveen_bti@yahoo.com
Thanks
Hi i have uploaded the code in share folder. Please check it. If you get any problem then let me inform.
GOod. It’s working nice. Thank you..
I glad to know that my artical helped you.
I have downloaded your file in your sky drive..there are 4 folders there..which 1 is the related one?
thanks chandra dev its working fine
thanks dude It works fine…
It help me to learn a lot
Nice to hear. I will try to write this type of artical.
Hi.. Very nice article… but decrypt is not working for me… Please send me the code for the decrypt the password.. I need to decrypt the password to match the password entered by the user from the password field… apologize for the errors or not understanding…
Hi
Here we canot decrypt the password direcly. We are mixing salt value to make it strong. Please go throght the code and check the authentication concept.
thanks for posted nice article,i done this as perfect but i can send single mail only i can’t send multiple mails at a time ,I have to write sp like
use msdb
GO
EXEC sp_send_dbmail @profile_name=’Manojprabakaran’,
@recipients=N’vadivelkarthick@gmail.com,manoj@icegen.net,karthick@icegen.net’,
@subject=’Test message’,
@body=’This is the body of the test message.
Congrates Database Mail Received By you Successfully.’
but mail would be send only first mail id,not an other …help me
Hi
I m really sorry for late reply. For sending email to multiple user, you should have to use looping concept. So for looping in database we can use cursor. For more detail, please check this url. here is the exact code
http://www.emailarchitect.net/easendmail/kb/sql.aspx?cat=6
please help me i want to store password as encrypted format and retrieve in oracle using asp.net send
thank you
Hi
you can also apply this concept with oracle database. Here we are doing encryption process using C# code.
Where is your Decrypt method?
Hi
Here we are not using direct decrypt process. We are adding some salt value for making the strong password
I need to be able to take the encrypted value and decrypt to plain text
Hi dev. Nice post , but i tried your code which i downloaded from the link you gave, Whenever i clicked on encrypt button with the same password the encryptyed password keep changing, it is not giving the same encryption key is that correct?
and how in case it is store in the database use it to Authenticate user, i tried to encrypt the passwrod and store it into the database and whenever user login encrypt the password he gave and compare it with the encrypted password stored but Not working, i dont know if i missed some steps ,am i doing it in right way or there is otherway?
Please waiting for ur answer.
thx.
Hi
It is correct. Here we are mixing random salt value with encrypted password. So every time it will give different value. It has been done due to security purpose. For example somebody hacked you database and he want to decode your password then he may try to comparing the encrypted password.
But if we will do like this, it will be impossible to guess and crack the password by hacker.
I have done the authentication process without using database. You try to analysis the code and implement in your project. In my free time, i will integrate with database and i will share here.
Thanks dev got how to integrate it with my database. thanks a lot, great post, great article,easy to understand and well detailed, well commented, and like your implementation.
Hey there! I have tried your code..
thanks a lot! i have done the encryption and stored inside the database…
now, the problem is the decryption part, i tried to do it but cannot…
do u have a sample code where there is database on it? Thank you so much!! 🙂
Apologies, but I am using vb not c# do you have a vb version of your code?
Thanks in advance
Hi ChandraDev….Your article was very useful…..But i have no idea about decryption….Can you please send me the code for decryption…..The code for decryption is not there in your share folder. Your help will be greatly appreciated. Thankyou
Hi
Here we are not using direct decryption process.
Hi Dev,
Thank you so much for this code. great work.
I have downloaded your code from skydrive.
But i didn’t found any decryption method. Can you send on my email id ?
BTW thanks.
Hi
Please read the artical properly. Here we are not decrypting the password directly. if we will decrypt directly then here will be no security. Then anybody can hack the sensitive data. Please run the code and try to analyze the code.
Hi,
I read your article it’s good. I need to encrypt and also decrypt confidential data. Is there any code so that I can use both rather than just using convert.tobase64 format?
May not be a problem if doesn’t generate random number.
I was curious if you ever thought of changing the page layout of your blog?
Its very well written; I love what youve got to say. But maybe
you could a little more in the way of content so people
could connect with it better. Youve got an awful lot of text for only having 1 or 2 images.
Maybe you could space it out better?
Thanks for your suggestion. I will do it in my free time.
hello sir i want urgent need encypted code ….my reqment is when student is regsiter then automatically genrate the password and send it to student emailid ….i want tht password send in email but in encyptedmode and when student want decrypt the password first he/she enter the private key then password chnge the mode ..plz help me u can send me code
Hi
You can write one class for randam generation of password. If somebody is going to complete registration process then send one randam generated password and make the status is false. If he will click on that given URL then make his account is active.
Please refer this URL
http://stackoverflow.com/questions/15181361/sending-email-verification-link-to-activate-profile-c-sharp
http://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account
Great beat ! I wish to apprentice while you amend your site,
how can i subscribe for a blog website? The account aided me
a acceptable deal. I had been a little bit acquainted
of this your broadcast provided bright clear idea
Hi Everyone,
I was trying to follow this Class, and what I have done is stored the password in SQL Data Base using the first method (ComputeHash), but when I tried to return the string stored in SQL DB and compare it to the string the user put it in a textBox, it is throwing and error in the method (VerifyHash) in the this line:
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
Saying “Invalid length for a Base-64 char array.”
Here is the code I used in both “adding the username and password” and retrieving username and password.
//Encrypt Password
string EPass = ComputeHash(textBox8.Text, “SHA512”, null);
cmd = new SqlCommand(“Add_User_SP”, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@Username”, textBox7.Text.ToString().Trim());
cmd.Parameters.AddWithValue(“@Password”, EPass);
cmd.Parameters.AddWithValue(“@Email”, textBox10.Text.ToString().Trim());
con.Open();
int c = cmd.ExecuteNonQuery();
if (c > 0)
{
con.Close();
MessageBox.Show(“New User Inserted”, “Confirmation”, MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox7.Text = “”; textBox8.Text = “”; textBox9.Text = “”; textBox10.Text = “”; textBox11.Text = “”;
}
else
MessageBox.Show(“Insertion Failed, try again”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
con.Close();
And here is the code for retrieving password and validate it against user input in the password textBox:
string DB_Pass;
//This variable “DB_Pass” is for passing the password from SQLDB and pass it to the VerifyHash method
string EPass = ComputeHash(textBox2.Text, “SHA512”, null);
cmd = new SqlCommand(“Login_SP_Encrypted”, con);
cmd.Parameters.AddWithValue(“@Username”, textBox1.Text.ToString().Trim());
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
{
while (rdr.Read())
{
un = rdr[“Username”].ToString();
email = rdr[“Email”].ToString();
DB_Pass = rdr[“Password”].ToString();
}
con.Close();
}
bool flag = VerifyHash(textBox2.Text, “SHA512”, DB_Pass);
if (flag == true)
{
MessageBox.Show(“You are the correct user”);
Form f2 = new Staff_Details_Form();
this.Hide();
f2.Show();
}
else
MessageBox.Show(“Invalid Username Or Password!”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
Any idea “Chandra Dev” why I’m getting that error and what should I do??!!
Hi
I have updated the artical, Please do like that. Now i hope that you can easily implement that code in your project.
All good, found out that the database password column data type was the problem, I used to set it to nvarchar(50) and that won’t allow to take more than 50 char, and when the encrypted password was stored, it was more than 50 char, but when I changed that to nvarchar(Max), all working now.
Thanks heaps for your help Chandra 🙂
I just have 2 more question about app.config file.
1- Is there anyway I can store and save to it (or update current value stored in it? Could you give an example code?
2- How to make a form show for one time only with (Don’t show again) check box
Thanks in advanced Chandra 🙂
Hi to all, the contents existing at this site are in fact amazing for people knowledge,
well, keep up the good work fellows.
Thanks for your kind word. I will keep on posting good artical like this.
Not open in VS 2010 ur given code i download
Hi
I have done using VS 2012. There would be one more code sample. Please download it.
Sir your post is best for encrypt and decrypt password……it is very useful…………Will you plz provide me the code for retrieve forget password of hash password
Hi Everyone,
I just wanted to share what I found out about storing the encrypted password in the database and the “Invalid length for a Base-64 char array.” exception.
Found out that you need to change the password column data type in the database to whatever it is to nvarchar(Max) or any other data type that contain such a long string as it is sometimes exceed the 90 char.
I went step by step in code and found out when I was comparing the string that was generated and saved from the code to the one that was saved in the database and found out that it was missing lots of characters. 🙂
Sir your post is best for encrypt and decrypt password……it is very useful…………Will you plz provide me the code for retrieve forget password of hash password???
Hi Rahul,
I have already given option to download the code. Please download from there.
sir i downloaded from website its works fine but i want to know how it works when user forgets the password, how to reset the old password or change the password….
sir i downloaded from website its works fine but i want to know how it works when user forgets the password, how to reset the old password or change the password….actually i am beginner in asp.net so plz provide me the code
Dear Rahul
On basis of your requirement, i have updated the artical and source code. Please check it and let me know if you will get any problem.
Sir you r genius,you solved my prob thanks sir your post are useful for beginners like me,,,,,i downloaded the code its works perfectly…
Sir will you plz tell me how to forward reset link to reset forget password to user’s registered email id of hashed(salt) password
I m glad to know that my post helped you. Yes sending hashed code to user emailid is more secure as compare to directly change password on basis of emailId. In this approach also concept will be same. Firstly you have to send the one website URL + hashed code to that registered emailId and you have to also store that code in our table. if user will click on that URL then it will redirect to your website with that code.
At page load time you can read that hashcode and validate in database.If this is the right user then give permission to reset password otherwise display invalid message.
hello sir i tried a lot to do so but i can’t get the right thing,,,sir i humbly requested to you plz provide the code to me on my email id(rahul06.it@gmail.com)
hello sir i tried a lot to do so but i can’t get the right thing,,,sir i humbly requested to you plz provide the code to me on my email id(rahul06.it@gmail.com)
I will send it. No problem.
sir i haven’t received the code plz mail me………..
Dear rahul, I have sent the code. Please check your inbox.
thanks sir for responding……you rocksssss
Hey there outstanding blog! Does running a blog such as this take a large amount of work?
I’ve virtually no understanding of programming however I was hoping to start my own blog in the near future. Anyways, should you have any recommendations or techniques for new blog owners please share. I know this is off topic however I simply had to ask. Thank you!
Hello there! This is my first comment here
so I just wanted to give a quick shout out and say I truly enjoy reading your posts.
Can you suggest any other blogs/websites/forums that go over the
same subjects? Thanks for your time!
Thank you. You can get more resource on http://www.asp.net/,http://www.c-sharpcorner.com/ and Stackoverflow site
I don’t make it a habit to make comments on
many articles, on that the other hand this one deserves attention.
I agree with the data you have written so eloquently here.
Thank you.
I’m not sure where you’re getting your information, but great topic.
I needs to spend some time learning more or understanding more.
Thanks for wonderful information I was looking for this
information for my mission.
sir will you plz tell me how to convert .aspx page into PDF using C#……..
Dear brother,
Please check this URL
http://www.aspsnippets.com/Articles/Export-ASPNet-Web-Page-with-images-to-PDF-using-ITextsharp.aspx
Let me know if you will get any problem.
hello sir i tried a lot to convert “.aspx” to pdf but it throughs error such as illegal character in path.My requirement is when user fills the registration form and upload the photo through file upload tool after save the form then it save as in pdf format such as any competition form when we fill all the details and upload the photo then we save the forms(all the details) on clicking the “Save as PDF” such as in IBPS website..
above link convert the webpage but If page contain any image control or file then How would we render it to PDF?
so sir plz provide some solution to me………..
how to create ASP.net website compatible in all browsers
sir i get the ans from your blog refer to topic cross browser compatibility
but i want to know how to change login hyperlink to log out,i create login through programming ,i’m not using the login panel provided by the VS.net
Hi,
For that you have to write code in code behind file. For example after login, you can change the text of linkbutton by C# code.
May i ask how do you do a forget password with email with the hash tag? Any reference? Regards.
Thanks for sharing your thoughts about indicative. Regards
Thanks alot Webmaster, usually I don’t left any comments in the web pages but this is amazing, at least for me as a newbie, I really appreciate it a bunch.
My best whishes for you.
I always spent my half an hour to read this webpage’s content every day along with a cup of coffee.
Thanks. Nice to know about this.
Reblogged this on infotoinfo and commented:
Good Knowledge blog.
You actually make it seem so easy with your presentation but I find this matter
to be really something which I think I would never understand.
It seems too complicated and extremely broad for me.
I’m looking forward for your next post, I will try to get the hang of it!
Hello! Someone in my Myspace group shared this site
with us so I came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting
this to my followers! Outstanding blog and amazing design.
prada 2013
Heya i am for the first time here. I came across
this board and I find It truly useful & it helped me
out a lot. I hope to give something back and aid others like you aided me.
Chandra Dev,
Firstly, thanks for such an insightful article and i’m one of your follower.
I ran into an issue with verifying the stored hash value.
my stored string hashValue = “4Nhuu2LRLntxkUs8Nb0DzL84GRgi5AWhsf+fhfiy6BwTNiM9UUZSdFfWhkCond9hkBBZOA==”;
and when i pass this to verifyHash method it converts into bytes using FromBase64String and that in turn yields to a bytes array of length 52. The problem comes when this length is compared to hashSizeInBytes, which is 64, and the latter being larger resulting in the false condition hence unable to proceed further.
I’ve raised the same question in stackexchange : http://stackoverflow.com/questions/24728561/variable-is-bigger-than-byte-size-why
Please go thru it in case i’ve not made myself clear with the description.
Hi
Why are you using Base64 encode and decode approach. That is not a secure approach. In that approach hecker can easily heck your password. Please your some alogirthm with some salt value like SHA512.
I have already created sample code using SHA512. Please use this in your application.
Hi
I used the same approach as you did. Infact i’m using the same code inside out. Problem, though, comes up when this piece of code picks up.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
This results in false cause the hashvalue = “4Nhuu2LRLntxkUs8Nb0DzL84GRgi5AWhsf+fhfiy6BwTNiM9UUZSdFfWhkCond9hkBBZOA==”- which is a stored value in SQL- when converted into bytes(hashWithSaltBytes) it gives out rather 52 long byte array which in turn when put up a comparison against 64 size long hashSizeInBytes , leading to falsehood.
Hope, it makes sense and this is where i need help.
Bharath.
Hi
could you please share your complete code with me. so that i can understand your exact problem.
public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
{
if (saltBytes == null)
{
int minSaltSize = 4;
int maxSaltSize = 8;
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
saltBytes = new byte[saltSize];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(saltBytes);
}
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes[i] = plainTextBytes[i];
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
HashAlgorithm hash;
if (hashAlgorithm == null)
hashAlgorithm = "";
switch (hashAlgorithm.ToUpper())
{
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA384Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes[i] = hashBytes[i];
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
string hashValue = Convert.ToBase64String(hashWithSaltBytes);
return hashValue;
}
//using the above method i got the plain text "qwerty" converted to hashValue and have it stored in DB. Now when user enters the password the below method puts up the comparison with the hashValue and decides if the user is authentic. Is what I understand. Now the problem comes up when I run this piece of code as it results to false. if (hashwithSaltBytes.Length < hashSizeInBytes)
return false;
The problem, like i stated earlier, the comparison is between 52 sixe byte array and 64 size byte array. As 52<64, leading to false.
public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue)
{
byte[] hashwithSaltBytes = Convert.FromBase64String(hashValue);
int hashSizeInBytes, hashSizeInBits;
if (hashAlgorithm == null)
hashAlgorithm = "";
switch (hashAlgorithm.ToUpper())
{
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default:
hashSizeInBits = 128;
break;
}
hashSizeInBytes = hashSizeInBits / 8;
if (hashwithSaltBytes.Length < hashSizeInBytes)
return false;
byte[] saltBytes = new byte[hashwithSaltBytes.Length – hashSizeInBytes];
for (int i = 0; i < saltBytes.Length; i++)
saltBytes[i] = hashwithSaltBytes[hashSizeInBytes + i];
string expectedString = ComputeHash(plainText, hashAlgorithm, saltBytes);
return (expectedString == hashValue);
}
Hi
Sorry for late reply. I had already share the sample application using this algorithm in my skydrive. have you downloaded and tested the code in your system ?
Pretty nice post. I just stumbled upon your weblog and wanted to say that
I’ve truly enjoyed surfing around your blog posts.
In any case I’ll be subscribing to your rss feed and I hope you write again soon!
Hi, chandradev,
I still got error to decrypt , Encryption is ok. but decrypt is problem, in verifyHash method
Invalid length for a Base-64 char array or string.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
I tried your code that attached in this article,
pls help me.
regards
Very good example. I’ve been looking for a good way to hash some text and store it in a database. This is the best way I’ve seen so far for C Sharp and you made it very easy to understand. Thanks!
I am glad to know that you liked it.
Excellent post. I was checking constantly this blog and I’m impressed!
Extremely useful info specially the last part 🙂 I care for such info much.
I was seeking this particular information for a long time.
Thank you and good luck.
Thank you for posting sweet feedback.
one of the best examples for encryption and decryption. Thank you buddy
I am glad to know that you liked it.
Pretty nice post. I just stumbled upon your weblog
and wanted to say that I’ve really enjoyed browsing your blog posts.
In any case I’ll be subscribing to your feed and I hope you write again very soon!
Hello sir,
BUT HOW WE CAN DECRYPT MY STRING
IN THIS ARTICLE EXPLAIN ONLY VERIFY STRING
I WANT TO DECRYPT MY STRING .
you canot decrypt the password. If you will decrypt the password to original formate. Then there will be security problem. Developer can easily decode the sensitive password from database.
Hi Chandra ,I am quite new to c# coding… I want to encrypt a password using SHA-256 algorithm using user salt string or without user salt string in asp.net c# . can you please send me the code or full example how to implement this in .net (both aspx and c#) on this mail id – dhanashri.dbd@gmail.com
Also please tell me how to produce generate user salt random number using SHA1PNRG algorithm
I have already used in this artical. Please go through this.
i am getting an error at this line of VerifyHash 😦
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
Hi Chandra,
I was really looking for the encryption deception code to use in my website. could you please send me the source of this. It will be really very helpful.
thanks.
hi…sir may i know how to encrypt a particular column data from mdb file plss.
sir please I need code for decryption..
Please Sir Send me the code for visual studio 2010 in my mail id.Plzzzz….It’s urgent
Please download the code from given below path
https://onedrive.live.com/?cid=4b1f6c3e92f6522c&id=4B1F6C3E92F6522C%21262&authkey=!AIttykIAJNAxdC0
Hello Sir,
Invalid length for a Base-64 char array or string.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
Please suggest me ASAP. It’s urgent.
After increase size of password column from database my issue solved
Good to know that you fixed the issue by yourself.
Great goods from you, man. I’ve understand your stuff previous to and
you’re just too magnificent. I actually like what you’ve acquired
here, really like what you are saying and the way in which you say it.
You make it enjoyable and you still care for to keep
it sensible. I cant wait to read far more from you.
This is actually a wonderful site.
Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know.
Hey, thanks for the post.Really thank you! Really Cool.
Appreciate you sharing, great blog post.Thanks Again. Really Cool. ddddgdbagebb
Really great info can be found on site.
Thank you,it’s very useful and it saves me a lot of time,but can i ask you a question about when i transmit the user information to my database there are always two information about the same person?
Hi sir,
hope you’ll help me.
First of all thank you for the amazing tutorial, very helpful.
Now, my question. Why at this point of code in Helper.cs i have an hashValue with a lot of white space at the end?
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
Cause of this VerifyHash return me false and I can’t login succesfully.
Thank you.
Hello,
Noob here, was researching on the encrypt/decrypt methods and not use whats provided with ASP.net. Ran into this article and is exactly what i was looking for. Is there a way i can get the complete code? There do not seem a link as mentioned at the bottom of the article “You can download the code from here”. Appreciate your assist.
Hello sir, tried to use your code. Had problems though when using the VerifyHash, and your skydrive doesnt seem to be active. Can you share the code to help solve this issue->> Invalid length for a Base-64 char array or string. Its quite urgent. Thanks
I figured it out, thanks all the same for the post. Apparently the column saving the hash was small hence it truncated the values.
Dear Sir,
I use the above code. It works perfectly for me.
Now I want to decrypt this password as per requirement. and send the password in Mobile on forget password
How I can do it as m not able to find decrypt function in code also shared attachment is not available.
please send me the code on rahuldhande21@gmail.com
Hi Rahul, In this approach we don’t decrypt the password. You can give option to user to change the password. Have you seen any time get old password on gmail/facebook/homail ? They will give option to change the password.
Hi Chandra,
I am facing issue with code. Can u please send full code.
Thanks.
I have updated the source code download. Please download from there.