C#應用偽隨機數完成加密用戶暗碼的辦法。本站提示廣大學習愛好者:(C#應用偽隨機數完成加密用戶暗碼的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用偽隨機數完成加密用戶暗碼的辦法正文
本文所述實例為應用偽隨機數停止用戶暗碼加密,這段代碼為焦點部門重要代碼,須要合營其它的法式完成,感興致的讀者可以本身進一步加以完美,不費話了,上面列出重要代碼:
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 } }