WCF初见之Salt+Hash加密

最近要对密码进行Salt加密,故查看了相关资料,其实就是把需要加密的值先和随机的Salt值连接在一起,再进行加密(可以哈希,也可以MD5加密等等)。

下面是具体步骤:

1.先创建相关数据库:

--创建数据库表Salt_Encryption
CREATE TABLE Salt_Encryption
(
Name             VARCHAR(15) PRIMARY KEY NOT NULL,        --用户名
[Password]         VARCHAR(50) NOT NULL,                    --密码
Salt             VARCHAR(10) NOT NULL                    --Salt值
)

2.新建一个Salt_Encryption_WCF的WCF应用程序,因为要用到数据库,所以先创建一个名为SaltModel.edmx的实体类:

然后跟着步骤来就可以了

3.创建服务契约和创建服务:
(1)IService1.cs (创建服务契约):

 

using System;
using System.Collections.Generic;
using System.ServiceModel;

namespace Salt_Encryption_WCF
{
    
    [ServiceContract]
    public interface IService1
    {
         /***********************************密码加密*********************************************************/
        // 创建一个随机的Salt值
        [OperationContract]
        string CreateSalt();
        //对Salt后的密码进行哈希
        [OperationContract]
        string CreatePasswordHash(string pwd, string strSalt);
        /*************************************数据库操作********************************************/
        // 新增数据
        [OperationContract]
        void insertSql(string strName, string strPwd, string Salt);
        // 查询数据
        [OperationContract]
        IEnumerable<Salt_Encryption> selectSql();
    }
}

(2)Service1.svc (创建服务)

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web.Security;
using System.Security.Cryptography;
namespace Salt_Encryption_WCF
{
    
    public class Service1 : IService1
    {
        /***********************************密码加密*********************************************************/
        private const int saltLenght = 4;  //定义Salt值的长度

        /// <summary>
        /// 创建一个随机的Salt值
        /// </summary>
        /// <returns>随机数的字符串</returns>
        public string CreateSalt()
        {
            //生成一个加密的随机数
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff  = new byte[saltLenght];
            rng.GetBytes(buff);
            //返回一个Base64随机数的字符串
            return Convert.ToBase64String(buff);
        }

        /// <summary>
        /// 对Salt后的密码进行哈希
        /// </summary>
        /// <param name="pwd">密码</param>
        /// <param name="strSalt">Salt值</param>
        /// <returns>返回加密好的密码</returns>
        public string CreatePasswordHash(string pwd,string strSalt)
        {
            //把密码和Salt连起来
            string saltAndPwd = String.Concat(pwd,strSalt);
            //对密码进行哈希
            string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd,"sha1");
            //返回哈希后的值
            return hashenPwd;
        }
        /*************************************数据库操作********************************************/
        SaltEnEntities db = new SaltEnEntities();
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="strName">用户名</param>
        /// <param name="strPwd">密码</param>
        /// <param name="Salt">Salt值</param>
        public void insertSql(string strName,string strPwd,string strSalt)
        {
            Salt_Encryption s = new Salt_Encryption();
            s.Name = strName;
            s.Password = strPwd;
            s.Salt = strSalt;
            //添加数据
            db.Salt_Encryption.AddObject(s);
            //保存数据的改变
            db.SaveChanges();
        }


        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Salt_Encryption> selectSql()
        {
            IEnumerable<Salt_Encryption> sql = from info in db.Salt_Encryption
                                               select info;
            return sql;
        }
    }
}

4.然后新建一个名为Test2Salt的Web客户端(用于测试),先引用创建的WCF服务,具体过程见WCF初见之HelloWorld,然后进行Web端的代码编写:
(1)Test2SaltForm.aspx(Web界面代码)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test2SaltForm.aspx.cs" Inherits="Test2Salt.Test2SaltForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="Name" runat="server" Text="用户名:" Height="20px" Width="80px"></asp:Label>
    <asp:TextBox ID="toName" runat="server" Height="20px" Width="120px" ></asp:TextBox>
    </div>
    <div>
    <asp:Label ID="Password" runat="server" Text="密码:" Height="20px" Width="80px"></asp:Label>
    <asp:TextBox ID="toPassword" runat="server" Height="20px" Width="120px" 
            TextMode="Password"></asp:TextBox>
    </div>
    <asp:Button ID="InsertData" runat="server" Text="插入数据" 
        onclick="InsertData_Click"/>
    <asp:GridView ID="gv" runat="server">
    </asp:GridView>
    </form>
</body>
</html>

(2)Test2SaltForm.aspx.cs(功能实现代码)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test2Salt
{
    public partial class Test2SaltForm : System.Web.UI.Page
    {
        host.Service1Client host = new host.Service1Client();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) { DataPageBind(); }
        }

        private void DataPageBind()
        {
            //绑定数据,并显示数据
            gv.DataSource = host.selectSql();
            gv.DataBind();
        }

        protected void InsertData_Click(object sender, EventArgs e)
        {
            string strName = toName.Text.Trim();
            string strPwd = toPassword.Text.Trim();
            //得到Salt值
            string Salt = host.CreateSalt();
            //得到加密后的密码
            string Pwd = host.CreatePasswordHash(strPwd,Salt);
            host.insertSql(strName,Pwd,Salt);
            DataPageBind();
        }


    }
}

5.效果图如下:

 

PS:如果想验证用户名和密码的话,只要获取数据库中的Salt值,对你输入的密码进行加密,然后和数据库中的密码进行对比就可以了。

 

posted @ 2012-06-26 10:04  叶超Luka  阅读(2856)  评论(0编辑  收藏  举报