Let me begin by saying that the examples in this article do not use the Microsoft Cryptography API (System.Security.Cryptography). Instead, I have used "pwdencrypt" and "pwdcompare", which are internal (and undocumented!!) functions of SQL Server [version] used to manage passwords. Pwdencrypt uses a one-way hash that takes a clear string and returns an encrypted version of that string. Pwdcompare compares an unencrypted string with its encrypted representation to check whether ...Let me begin by saying that the examples in this article do not use the Microsoft Cryptography API (System.Security.Cryptography). Instead, I have used "pwdencrypt" and "pwdcompare", which are internal (and undocumented!!) functions of SQL Server [version] used to manage passwords. Pwdencrypt uses a one-way hash that takes a clear string and returns an encrypted version of that string. Pwdcompare compares an unencrypted string with its encrypted representation to check whether they match. Let's go through an example to see how to use these functions from .NET:Sample table structure for storing the login information of an user: create table testlogin
( uid varchar(10), pwd varbinary(255) )
The subroutine below is used to store the user information after encrypting the password:
private void cmdAdd_Click(object sender, System.EventArgs e) { SqlConnection cn = new SqlConnection(ConnectionString); cn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into testlogin values (" + "'" + txtUserName.Text + "'," + "convert(varbinary(255), pwdencrypt (" + "'" + txtPassword.Text + "'" + ")))"; cmd.ExecuteNonQuery(); }
For readability purposes, I have shown the "insert" statements in multiple lines. It has to be in a single line for proper execution.Moreover, it is not advisable to write queries directly in the front end, so in the real world we would be using stored procedures.Now let's have a look at the procedure used to authenticate user data. The procedure checkLogin accepts a username and a password as input parameters and returns 0 or 1 as its output value.Procedure used to authenticate an user create procedure checkLogin
( @uid varchar(255), @pwd varchar(255), @error int = 0 output ) As
if exists (select * from testlogin where uid=@uid and 1 = pwdcompare(@pwd,pwd,0)) select @error = 1 else select @error = 0
The procedure is self-explanatory. The third parameter of pwdCompare is provided for backward compatibility (with earlier versions of SQL Server). While comparing passwords encrypted in SQL Server 6.5, we need to pass 1 for this value.[bold]The complete code-behind source code follows:[/bold] using System ; using System.Data; using System.Data.SqlClient; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
namespace testing { public class WebForm2 : System.Web.UI.Page { protected System.Web.UI.WebControls.RequiredFieldValidator RFVPassword; protected System.Web.UI.WebControls.RequiredFieldValidator RFVUserName; protected System.Web.UI.WebControls.Button cmdAdd; protected System.Web.UI.WebControls.TextBox txtUserName; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Button cmdLogin; protected System.Web.UI.WebControls.Label message; protected System.Web.UI.HtmlControls.HtmlForm Form1; protected System.Web.UI.WebControls.TextBox txtPassword;
string ConnectionString; public WebForm2() { ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["constr"]; }
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here }
#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdAdd.Click += new System.EventHandler(this.cmdAdd_Click); this.cmdLogin.Click += new System.EventHandler(this.cmdLogin_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion
private void cmdAdd_Click(object sender, System.EventArgs e) { SqlConnection cn = new SqlConnection(ConnectionString); cn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into testlogin values (" + "'" + txtUserName.Text + "'," + " convert(varbinary(255),pwdencrypt(" + "'" + txtPassword.Text + "'" + ")))"; cmd.ExecuteNonQuery(); }
private void cmdLogin_Click(object sender, System.EventArgs e) { SqlConnection cn = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand("checkLogin",cn); cmd.CommandType = CommandType.StoredProcedure; // Adding the first Input parameter SqlParameter workParam = cmd.Parameters.Add(new SqlParameter("@uid",SqlDbType.VarChar,255)); workParam.Value = txtUserName.Text;
// Adding the second Input parameter SqlParameter workParam1 = cmd.Parameters.Add(new SqlParameter("@pwd",SqlDbType.VarChar,255)); workParam1.Value = txtPassword.Text;
// Adding the output parameter SqlParameter workParam2 = cmd.Parameters.Add(new SqlParameter("@error",SqlDbType.Int, 4)); workParam2.Direction = ParameterDirection.Output;
try { // Opening a connection. cn.Open(); cmd.ExecuteScalar(); object LoginResult = workParam2.Value; LoginResult = LoginResult.ToString(); // Assigning the value 0 (fail) or 1 (success) to the label control if (LoginResult.ToString() == "1") message.Text = "You are Authorized !"; else message.Text = "You aren't authorized :-("; } catch (Exception ex) { message.Text = ex.Message; } finally { // close the connection cn.Close(); } } } }
Note:If a user forgets his password, we could reset it to some random value. Intriguingly, if you use one way encryption there's no way to determine what exactly the user's password was. | DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More ASP.NET Code Articles More By developerWorks - FREE Tools! | Achieving true agility is a never-ending effort. We will showcase how you can become agile incrementally, a few practices at the time.Which practices should any agile team strive to adopt? What additional practices should you consider based on your needs to scale? Adopting practices are however made much easier with the right tool support. What about if your tools adapt to your practices? We will take a look at how the Jazz technology can be leveraged to make your process change the behavior of your tools. FREE! Go There Now!
| | | | Visit IBM developerWorks to download a free trial version of WebSphere Business Modeler Advanced V6.1.1, IBM’s premier business process modeling and analysis tool for business users that offers process modeling, simulation, and analysis capabilities. IBM WebSphere Business Modeler helps you visualize, understand, and document business processes for continuous improvement. FREE! Go There Now!
| | | | Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today. FREE! Go There Now!
| | | | As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br /> FREE! Go There Now!
| | | | Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle. FREE! Go There Now!
| | | | Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast. FREE! Go There Now!
| | | | Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data. FREE! Go There Now!
| | | | IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community. FREE! Go There Now!
| | | | WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
| | | | With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |