Currently i am doing a little project, the user registration password field is encrypted in the database, therefore I need to authenticate users using md5 algorithm also but my code is not working, whenever i try to input the correct password(unencrypted) it enters but later out i figured out that any password I type, the system will accept it even it doesn't matches in the database.
Can you help me? Here is my code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string pAssword = txtPassword.Text;
MD5CryptoServiceProvider encryptor = new MD5CryptoServiceProvider();
byte[] encryptedValue;
UTF8Encoding encoder = new UTF8Encoding();
encryptedValue = encryptor.ComputeHash(encoder.GetBytes(pAssword));
DataSet ds = new DataSet();
ds = (startWebService.getAllUsers());
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string userName = dRow["UserName"].ToString();
string passWord = dRow["Password"].ToString();
string acctNo = dRow["AccountNumber"].ToString();
if (userName == txtUsername.Text.ToString() && acctNo == txtAcctNo.Text.ToString() && passWord == encryptedValue.ToString() )
{
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text.ToString(), false);
lblError.Text = "You got it!";
Response.Redirect("MyAccount.aspx");
}
else
{
this.lblError.ForeColor = System.Drawing.Color.Red;
this.lblError.Text = "Either you have been type an incorrect network credentials or you have reached the maximum login attempts for your account.Please try again or contact the system administrator.";
startWebService.updateFailedLogin(txtAcctNo.Text.ToString(), txtUsername.Text.ToString());
}
}
}
}
my web services:
private DataSet GetDataSet(string strSPROC)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strSPROC;
conn.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = cmd;
DataSet dsMT = new DataSet();
myDataAdapter.Fill(dsMT);
return dsMT;
conn.Close();
}
[WebMethod]
public DataSet getAllUsers()
{
return GetDataSet("ELMS_ALLINTERNETUSERS");
}
Please help me, I have to correct this in a way that the system will accepts the correct equivalent of encrypted text for example I type: spain = wdhs3x9029 but i tried to type philippines , it accepts also.
There is a nice built-in method for hashing passwords (you can use MD5 with it):
string encryptedValue = FormsAuthentication.HashPasswordForStoringInConfigFile(pAssword, "MD5");
You can read more about this method here. If you need to reinvent the wheel, then I suggest you change your method of getting hash as string to something more like this:
MD5CryptoServiceProvider encryptor = new MD5CryptoServiceProvider();
UTF8Encoding encoder = new UTF8Encoding();
byte[] encryptedValueBytes = encryptor.ComputeHash(encoder.GetBytes(pAssword));
StringBuilder encryptedValueBuilder = new StringBuilder();
for (int i = 0; i < encryptedValueBytes.Length; i++)
{
encryptedValueBuilder.Append(data[i].ToString("x2"));
}
string encryptedValue = encryptedValueBuilder.ToString();
instead of simple .ToString() on byte array.
Related
I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password
I am creating a WinForm Application that reads all the records from a certain column in a textfile. What I now need is a Data Dictionary that I can use to read records from the Database once the applications runs and prior to reading the TextFile. I need to read a specific column from the database and match it with the textfile. I am not sure how to go about creating a data dictionary. This is what I have so far.
This is to read the textfile, which is working fine.
using (StreamReader file = new StreamReader("C:\\Test1.txt"))
{
string nw = file.ReadLine();
textBox1.Text += nw + "\r\n";
while (!file.EndOfStream)
{
string text = file.ReadLine();
textBox1.Text += text + "\r\n";
string[] split_words = text.Split('|');
int dob = int.Parse(split_words[3]);
This is what I have so far to create the Data Dictionary.
public static Dictionary<int, string> dictionary = new Dictionary<int, string>();
You can use a SqlDataReader. Here is some code, you just need to modify it to suit your needs. I have added comments for you:
// declare the SqlDataReader, which is used in
// both the try block and the finally block
SqlDataReader rdr = null;
// Put your connection string here
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
// create a command object. Your query will go here
SqlCommand cmd = new SqlCommand(
"select * from Customers", conn);
try
{
// open the connection
conn.Open();
// 1. get an instance of the SqlDataReader
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string id = (int)rdr["SomeColumn"];
string name = (string)rdr["SomeOtherColumn"];
dictionary.Add(id, name);
}
}
finally
{
// 3. close the reader
if (rdr != null)
{
rdr.Close();
}
// close the connection
if (conn != null)
{
conn.Close();
}
}
i have implemented my user passwords to be hashed. And what i want is to implement a forgot/change password. However i am not able to convert the hashed password to the original password and that gives me a failure to do the forgot/change password feature. Here is my code from my registration page:
cmd.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash (txtPW.Text));
Here is my creathash code:
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and my changepassword page:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "select * from UserData ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
if (txt_cpassword.Text == reader["Password"].ToString())
{
up = 1;
}
}
reader.Close();
con.Close();
if (up == 1)
{
con.Open();
str = "update UserData set Password=#Password where UserName='" + Session["New"].ToString() + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 500));
com.Parameters["#Password"].Value = (txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What i want to do is to be able to convert my hashed password to the original password for it to be changed. Any tricks? or is it possible though?
I want to login automatically after registration by using a session like Session["ud"] , but I don't know where should I put it.
public partial class index : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void btnSave_Click(object sender, EventArgs e)
{
long idx;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (#P1,#P2,#P3,#P4,#P5) select ##Identity";
cmd.Parameters.AddWithValue("#P1", txtInfo.Text);
cmd.Parameters.AddWithValue("#P2", txtEmail.Text);
cmd.Parameters.AddWithValue("#P3", txtUserName.Text);
cmd.Parameters.AddWithValue("#P4", txtPass.Text);
cmd.Parameters.AddWithValue("#P5", rdbMale.Checked);
cnn.Open();
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
here we want to upload the image of user and it works correctly
string fn = "";
if (FileUpload1.HasFile == true)
{
fn = FileUpload1.FileName;
string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
FileUpload1.PostedFile.SaveAs(des);
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.Connection = cnn;
cmdUpdate.CommandText = "Update tblUser Set UImg=#P5 where UId=#P0";
cmdUpdate.Parameters.AddWithValue("#P5", idx.ToString() + ".jpg");
cmdUpdate.Parameters.AddWithValue("#P0", idx);
cnn.Open();
cmdUpdate.ExecuteNonQuery();
cnn.Close();
}
Response.Redirect("Profile.aspx");
}
}
once you have entered data into in sql database you will get id of new user here
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
Once you get the id assign it to your session
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
Session["ud"]=idx;
once you have assigned session ,you just have to redirect to required page and validate Session variable if it's null or not.
i hope on Profile.aspx page you are checking for same session variable.
Profile.aspx.cs--on page load
if (Session["ud"] != null)
{
//successfull login
}
else
{
//redirect to login page
}
I am trying to send an encrypted email using Microsoft.Exchange.WebServices.Data.
public void SendMessage(FacadeModel.EmailMessage message)
{
var item = new EWS.EmailMessage(_mailService);
var handler = new SecureMimeMessageHandler();
byte[] con = handler.encry("test", "me#mail.com.au");
item.MimeContent = new EWS.MimeContent(Encoding.ASCII.HeaderName, con);
item.ToRecipients.Add("me#mail.com.au");
item.From = new EWS.EmailAddress("", "me#mail.com.au");
item.Body = "test";
item.Send();
}
public byte[] encry(string body, string to)
{
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
X509Certificate2 cert1 = GetMatchingCertificate(certs[1], "me#mail.com.au", X509KeyUsageFlags.KeyEncipherment);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: application/pkcs7-mime; smime-type=signed-data;name=smime.p7m"));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert1);
envelope.Encrypt(recipient);
return envelope.Encode();
}
But still i am getting a plain email with no encryption in outlook. where have i gone wrong?
I posted a suggestion on the MSDN forum. Try setting the ItemClass to "IPM.Note.SMIME".