目录
1. 使用哈希算法加密密码
可以使用C#中的System.Security.Cryptography
库来进行密码加密。示例代码如下:
using System;
using System.Security.Cryptography;
using System.Text;
public class PasswordHasher
{
public static string HashPassword(string password)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder builder = new StringBuilder();
foreach (byte b in bytes)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
}
}
2. 用户注册时加密密码并保存到数据库
假设使用ADO.NET来操作数据库,示例代码如下:
string connectionString = "your_connection_string_here";
string username = "username_from_user_input";
string password = "password_from_user_input";
string hashedPassword = PasswordHasher.HashPassword(password);
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "INSERT INTO Users (Username, Password) VALUES (@Username, @Password)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", username);