ASP.NET Code
  Home arrow ASP.NET Code arrow One way encryption
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET CODE

One way encryption
By:
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2003-03-03

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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 senderSystem.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 pwdcompare(@pwd,pwd,0))
      
    select @error 
    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 senderSystem.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 senderSystem.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 senderSystem.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.Int4));
       
    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

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Achieving True Agility -- How process can change the behavior of your 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!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Download the free Web Application Security eKit

    Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Rational Asset Manager eKit

    Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT