在ADO.NET中,向数据库添加数据时,怎样对数据中的密码进行加密?(也就是说在数据表中也看不到用户的密

码,只是一些经过编译后的字符串,以防止数据库管理员利用用户的密码进行非法操作。)
    首先,在c#WinForm程序中引入命名空间,"using System.Web.Security;",此命名空间是专门用来对程序进

行安全设置的;
    其次,定义一个string类型的变量,用来接收用输入的密码;
  string passWord = this.textBox1.Text.Trim();
    取到密码之后,接下来便是对密码进行加密处理:
  string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5");
    最后,将加密后的密码pwd添加到数据库中去。
  insert into userInfo(uName,pwd) values('{0}','{1}');select @@identity", this.txtUID.Text.Trim

(),passwrod);
  示例代码:
  using System.Web.Security;

//取得文本框中的密码
    string pwd = this.txtPwd1.Text.Trim();
    //对密码加密
    string passwrod = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5");
    //创建SQL语句,将加密后的密码保存到数据库中
    string insCmd =
          string.Format("insert into userInfo(uName,pwd) values('{0}','{1}');select @@identity",

this.txtUID.Text.Trim(),passwrod);
    using (SqlCommand cmd = new SqlCommand(insCmd, Form1.Connection))
    {
        int uid = Convert.ToInt32(cmd.ExecuteScalar());
        //int uid = int.Parse(cmd.ExecuteScalar());//error
        if (uid > 0)
        {
            string mess = string.Format("恭喜,注册成功!您的号码是{0}",uid);
            MessageBox.Show(mess);
        }
        else
        {
            MessageBox.Show("对不起,注册失败了!");
        }
    }

这样加密之后保证了用户密码的安全,但是又出现了一个问题,即用户登录时怎样对密码进行验证,该不会让

用户去记住加密后的那一长串字符串吧? 答案当然是否定的,那怎样解决呢?
  应该这样解决:
  在用户登录时,得到用户输入的密码;
  然后,将取到的密码再次进行加密;
  之后,根据用户名取出该用户在数据库中的真实密码;
  最后,将刚刚进行加密的密码与数据库密码进行比对,即可完成用户登录操作。
  示例代码:
  string pwd = this.txtPwd1.Text.Trim();
                string pwd1 = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5");
                string uid = this.txtUID.Text.Trim();
                string selCmd = string.Format("select pwd from userINfo where uName='{0}'", uid);
                string password = "";
                using (SqlCommand cmd = new SqlCommand(selCmd, Form1.Connection))
                {
                    password= cmd.ExecuteScalar().ToString();
                
                }
                if (password == pwd1)
                {
                    MessageBox.Show("登录成功");
                }
                else
                {
                    MessageBox.Show("密码错误!");
                }
完整实例(复制即可用):

1.数据库代码:

use tempdb
go
if exists (select * from sysobjects where name = 'UserInfo')
drop table UserInfo
go
create table UserInfo
(
 uId int identity(1,1) not null,
 uName nvarchar(20) not null,
 uAge int not null,
 password nvarchar(200) not null
)
go
alter table UserInfo
add constraint PK_uID primary key (uId)
alter table UserInfo
add constraint CK_uAge check (uAge between 0 and 100)
go
select * from UserInfo

2.c#代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web.Security;  //安全加密

namespace 密码加密示例
{
    public partial class Form1 : Form
    {
        //创建数据库连接字符串
        static readonly string strConn = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True";
        //创建数据库连接对象
        static SqlConnection connection = null;
        //属性
        public static SqlConnection Connection
        {
            get 
            {
                if (connection == null || connection.State != ConnectionState.Open)
                {
                    connection = new SqlConnection(strConn);  //连接数据库
                    connection.Open();  //打开数据库
                }
                return Form1.connection;  //返回一个连接
            }
            
        }

public Form1()
        {
            InitializeComponent();
        }

/// <summary>
        /// 检查用户输入
        /// </summary>
        /// <returns></returns>
        private bool CheckInput()
        {
            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                this.errorPro.SetError(this.txtName, "用户名不能为空!");
                this.txtName.Focus();
                return false;
            }
            else
            {
                this.errorPro.Dispose();  //终止提示错误
            }
            if (string.IsNullOrEmpty(this.txtAge.Text))
            {
                this.errorPro.SetError(this.txtAge, "姓名不能为空!");
                this.txtAge.Focus();
                return false;
            }
            else
            {
                this.errorPro.Dispose();
            }
            if (string.IsNullOrEmpty(this.txtPass.Text))
            {
                this.errorPro.SetError(this.txtPass, "密码不能为空!");
            }
            else
            {
                this.errorPro.Dispose();
            }
            return true;
        }

/// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.CheckInput())
            {
                //获取用户输入的密码
                string password = this.txtPass.Text.Trim();
                //对密码进行加密
                string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
                //创建SQL语句,将加密后的密码保存到数据库
                string insCmd = string.Format("insert into UserInfo values ('{0}','{1}','{2}')",
                    this.txtName.Text.Trim(), this.txtAge.Text.Trim(),pwd); 
                using (SqlCommand cmd = new SqlCommand(insCmd,Form1.Connection))
                {
                    if (cmd.ExecuteNonQuery() > 0)
                    {
                        MessageBox.Show("恭喜您,注册成功!");
                    }
                    else
                    {
                        MessageBox.Show("对不起,注册失败···");
                    }
                }
            }
        }
    }
}

完!

c#程序中对密码进行加密的方法的更多相关文章

  1. 微信小程序中显示html富文本的方法

    微信小程序中显示html富文本的方法 使用方法:git地址:https://github.com/icindy/wxParse 一.下载wxParse文件 二.在要引入的页面的js文件中,引入文件 j ...

  2. node.js中用户密码的加密

    crypro实现用户密码的加密 在实际的项目中,只要涉及到用户的信息,就是十分重要的.设想一下数据库里面存放的用户的密码是明文的形式,后果是有多严重.所以今天给大家分享一下express中怎样实现用户 ...

  3. C#控制台或应用程序中两个多个Main()方法的可行性方案

    大多数初级程序员或学生都认为在C#控制台或应用程序中只能有一个Main()方法.但是事实上是可以有多个Main()方法的. 在C#控制台或应用程序中,在多个类中,且每个类里最多只能存在一个Main() ...

  4. C#控制台或应用程序中两个多个Main()方法的设置

    大多数初级程序员或学生都认为在C#控制台或应用程序中只能有一个Main()方法.但是事实上是可以有多个Main()方法的. 在C#控制台或应用程序中,在多个类中,且每个类里最多只能存在一个Main() ...

  5. 在数据库中sql查询很快,但在程序中查询较慢的解决方法

    在写java的时候,有一个方法查询速度比其他方法慢很多,但在数据库查询很快,原来是因为程序中使用参数化查询时参数类型错误的原因 select * from TransactionNo, fmis_Ac ...

  6. 微信小程序中获取高度及设备的方法

    由于js中可以采用操纵dom的方法来获取页面元素的高度,可是在微信小程序中不能操纵dom,经过查找之后发现仅仅只有以下几个方法可以获取到高度 wx.getSystemInfoSync().window ...

  7. 开发微信小程序 中遇到的坑 及解决方法

    1.wx.request 只能访问 https 解决: 新建项目  不填appid  即可访问 localhost 2.页面中多重三元表达式  解析有问题 解决: <!--{{index}} { ...

  8. ABAP程序中关于长文本的处理方法

    现象描述 长文本在SAP的运用主要体现在一些notes的记录,或者一些比较长的文本的存取,比如工作流的审批意见,采购申请和采购订单的附加说明等等.如下图: 处理过程 1:SAP中所有的长文本都存在两张 ...

  9. SpringBoot项目配置文件中密码的加密

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/15565862.html 版权声明:本文为博主原创文章,转载请附上博文链接! 公众号:追梦1819 ...

随机推荐

  1. MSSQL部分补丁的列表及下载地址(持续更新)

    整理了MSSQL部分补丁的列表及下载地址(截至2016-11-18),供参考下. Edition Version Date Published Download Link SQL Server 201 ...

  2. 图解TCP/IP→第2章基础知识

    ####TCP.IP背景**关键词:ARPANET,UNIX,分组交换技术,*ARPANET(阿帕网),也是全球互联网的鼻祖.阿帕网的成功也充分证明了基于分组交换技术的通信方法的可行性.*20世纪70 ...

  3. R自动数据收集第一章概述——《List of World Heritage in Danger》

      导包     library(stringr) library(XML) library(maps) heritage_parsed <- htmlParse("http://en ...

  4. AD域组策略-只显示指定的控制面板选项配置方法

    操作方法: 1.打开组策略管理器,新建一个组策略并右击编辑. 2,找到隐藏指定的“控制面板”项并双击打开:并参照设置: 填入要显示的控制面板项目,比如: joystick.cpl 表示将显示“游戏控制 ...

  5. beaglebone black 安装QNX过程

    首先去http://community.qnx.com/sf/go/projects.bsp/frs.texas_instruments_am335_beaglebo 把下面4个下载下来.

  6. JSONKit在项目中使用设置(ARC与方法更新)

    在项目中经常会遇到解析json的情况,如果有同学想要解析JSON,那么JSONKit可以是一个不错的选择. git中JSONKit 的地址为:https://github.com/johnezang/ ...

  7. SDC Tcl package of Timequest

    Tcl comand Tcl Commands all_clocks all_inputs all_outputs all_registers create_clock create_generate ...

  8. Linux(Ubuntu)下安装NodeJs

    用以下命令来升级系统,并且安装一些Node.JS必要的包. Linux(Ubuntu)下安装NodeJs 安装nodeJS之前,如果没有安装g++ make libssl-dev等, 1.更新系统和依 ...

  9. Dijkstra 算法

    all the nodes should be carectorized into three groups: (visited, front, unknown) we should pay spec ...

  10. ThinkPHP3.2.3多文件上传,文件丢失问题的解决

    描述 thinkphp多文件上传时,有些时候会出现文件丢失的情况.比如上传多个图片,最终只上传了一个图片.本地测试的时候是正常的,但上传到服务器上就会出现丢失文件这种情况. 原因 查看tp上传类(Th ...