VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之C#使用伪随机数实现加密用户密码的方法

本文所述实例为使用伪随机数进行用户密码加密,这段代码为核心部分主要代码,需要配合其它的程序实现,感兴趣的读者可以自己进一步加以完善,不费话了,下面列出主要代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PRanDataEncrypt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox3.Text != "")
{
if (DecryptPwd(textBox3.Text) == textBox2.Text)
MessageBox.Show("用户登录成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("用户密码错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
 
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = textBox2.Text = textBox3.Text = string.Empty;
textBox2.Focus();
}
 
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox3.Text = EncryptPwd(textBox2.Text);
}
 
//定义加密用户密码所用的伪随机数
private string randStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
#region 使用伪随机数加密用户登录密码
/// <summary>
/// 使用伪随机数加密用户登录密码
/// </summary>
/// <param name="str">用户登录密码</param>
/// <returns>加密后的用户登录密码</returns>
private string EncryptPwd(string str)
{
byte[] btData = Encoding.Default.GetBytes(str);
int j, k, m;
int len = randStr.Length;
StringBuilder sb = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < btData.Length; i++)
{
j = (byte)rand.Next(6);
btData[i] = (byte)((int)btData[i] ^ j);
k = (int)btData[i] % len;
m = (int)btData[i] / len;
m = m * 8 + j;
sb.Append(randStr.Substring(k, 1) + randStr.Substring(m, 1));
}
return sb.ToString();
}
#endregion
#region 解密用户登录密码
/// <summary>
/// 解密用户登录密码
/// </summary>
/// <param name="str">经过加密的用户登录密码</param>
/// <returns>解密后的用户登录密码</returns>
private string DecryptPwd(string str)
{
try
{
int j, k, m, n = 0;
int len = randStr.Length;
byte[] btData = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
{
k = randStr.IndexOf(str[i]);
m = randStr.IndexOf(str[i + 1]);
j = m / 8;
m = m - j * 8;
btData[n] = (byte)(j * len + k);
btData[n] = (byte)((int)btData[n] ^ m);
n++;
}
return Encoding.Default.GetString(btData);
}
catch { return ""; }
}
#endregion
}
}


相关教程