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! | The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times. FREE! Go There Now!
| | | | Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance. FREE! Go There Now!
| | | | Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success. FREE! Go There Now!
| | | | Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
| | | | Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications. FREE! Go There Now!
| | | | Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points. FREE! Go There Now!
| | | | Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1. FREE! Go There Now!
| | | | Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic. 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!
| | | | Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |