Tuesday, May 8, 2007

Code for Password Encryption in .NET

The namespace for using Cryptography is System.Security.Cryptography.

----------------------------------------------------------------
using System.Security.Cryptography;
----------------------------------------------------------------

MD5CryptoServiceProvider md5hasher = new MD5CryptoServiceProvider();
Byte[] hashedbytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedbytes = md5hasher.ComputeHash(encoder.GetBytes(txtPassword.Text));
-----------------------------------------------------------------
Now hashedbytes contains the encrypted password
-----------------------------------------------------------------
private Byte[] password;
password = hashedbytes
----------------------------------------------------------------

DataType for password in SQL SERVER is "binary(50)"

----------------------------------------------------------------
Stored procedure for creating user:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE PROCEDURE [dbo].[CreateUser]
@UserName VARCHAR(50),
@Password BINARY(16)
AS
BEGIN
IF NOT EXISTS(SELECT 'SOMTHING' FROM UserMst WHERE UserName=@UserName)
INSERT INTO
UserMst
(
UserName,
Password)
VALUES
(
@UserName,
@Password
)
RETURN SCOPE_IDENTITY()
END

No comments: