-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswordHelper.cs
More file actions
269 lines (227 loc) · 9.89 KB
/
PasswordHelper.cs
File metadata and controls
269 lines (227 loc) · 9.89 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SecurityUtils
{
/// <summary>
/// 密码安全处理工具类
/// 提供加密、哈希、验证等功能
/// </summary>
public static class PasswordHelper
{
// 默认加密参数
private const int DefaultSaltSize = 16;
private const int DefaultKeySize = 256;
private const int DefaultIterations = 10000;
#region 哈希方法
/// <summary>
/// 使用PBKDF2算法生成密码哈希
/// </summary>
/// <param name="password">原始密码</param>
/// <param name="salt">盐值(输出参数)</param>
/// <param name="iterations">迭代次数</param>
/// <returns>Base64格式的哈希值</returns>
public static string CreateHash(string password, out string salt, int iterations = DefaultIterations)
{
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("密码不能为空");
// 生成随机盐值
using (var rng = RandomNumberGenerator.Create())
{
byte[] saltBytes = new byte[DefaultSaltSize];
rng.GetBytes(saltBytes);
salt = Convert.ToBase64String(saltBytes);
}
return CreateHash(password, salt, iterations);
}
/// <summary>
/// 使用PBKDF2算法生成密码哈希
/// </summary>
/// <param name="password">原始密码</param>
/// <param name="salt">盐值</param>
/// <param name="iterations">迭代次数</param>
/// <returns>Base64格式的哈希值</returns>
public static string CreateHash(string password, string salt, int iterations = DefaultIterations)
{
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("密码不能为空");
if (string.IsNullOrWhiteSpace(salt))
throw new ArgumentException("盐值不能为空");
// 将密码和盐值转换为字节数组
byte[] saltBytes = Convert.FromBase64String(salt);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// 使用PBKDF2算法生成哈希
using (var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, saltBytes, iterations, HashAlgorithmName.SHA256))
{
byte[] hashBytes = pbkdf2.GetBytes(32); // 256位
return Convert.ToBase64String(hashBytes);
}
}
/// <summary>
/// 验证密码与哈希是否匹配
/// </summary>
/// <param name="password">原始密码</param>
/// <param name="salt">盐值</param>
/// <param name="storedHash">存储的哈希值</param>
/// <param name="iterations">迭代次数</param>
/// <returns>是否匹配</returns>
public static bool VerifyHash(string password, string salt, string storedHash, int iterations = DefaultIterations)
{
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentException("密码不能为空");
if (string.IsNullOrWhiteSpace(salt))
throw new ArgumentException("盐值不能为空");
if (string.IsNullOrWhiteSpace(storedHash))
throw new ArgumentException("存储的哈希值不能为空");
// 生成新哈希
string newHash = CreateHash(password, salt, iterations);
// 使用恒定时间比较防止时序攻击
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(newHash),
Encoding.UTF8.GetBytes(storedHash)
);
}
#endregion
#region 加密方法
/// <summary>
/// AES加密字符串
/// </summary>
/// <param name="plainText">明文</param>
/// <param name="key">加密密钥</param>
/// <param name="iv">初始化向量(输出参数)</param>
/// <returns>Base64格式的加密结果</returns>
public static string Encrypt(string plainText, string key, out string iv)
{
if (string.IsNullOrWhiteSpace(plainText))
throw new ArgumentException("明文不能为空");
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("密钥不能为空");
// 生成密钥和IV
byte[] keyBytes = DeriveKey(key, DefaultKeySize / 8);
byte[] ivBytes;
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.GenerateIV();
ivBytes = aes.IV;
iv = Convert.ToBase64String(ivBytes);
return Encrypt(plainText, key, ivBytes);
}
}
/// <summary>
/// AES加密字符串
/// </summary>
/// <param name="plainText">明文</param>
/// <param name="key">加密密钥</param>
/// <param name="iv">初始化向量</param>
/// <returns>Base64格式的加密结果</returns>
public static string Encrypt(string plainText, string key, string iv)
{
if (string.IsNullOrWhiteSpace(plainText))
throw new ArgumentException("明文不能为空");
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("密钥不能为空");
if (string.IsNullOrWhiteSpace(iv))
throw new ArgumentException("初始化向量不能为空");
byte[] ivBytes = Convert.FromBase64String(iv);
return Encrypt(plainText, key, ivBytes);
}
private static string Encrypt(string plainText, string key, byte[] ivBytes)
{
byte[] keyBytes = DeriveKey(key, DefaultKeySize / 8);
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = aes.CreateEncryptor())
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
/// <summary>
/// AES解密字符串
/// </summary>
/// <param name="cipherText">Base64格式的密文</param>
/// <param name="key">加密密钥</param>
/// <param name="iv">初始化向量</param>
/// <returns>解密后的明文</returns>
public static string Decrypt(string cipherText, string key, string iv)
{
if (string.IsNullOrWhiteSpace(cipherText))
throw new ArgumentException("密文不能为空");
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentException("密钥不能为空");
if (string.IsNullOrWhiteSpace(iv))
throw new ArgumentException("初始化向量不能为空");
byte[] keyBytes = DeriveKey(key, DefaultKeySize / 8);
byte[] ivBytes = Convert.FromBase64String(iv);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (ICryptoTransform decryptor = aes.CreateDecryptor())
using (MemoryStream ms = new MemoryStream(cipherBytes))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
#endregion
#region 辅助方法
/// <summary>
/// 从密码派生密钥
/// </summary>
private static byte[] DeriveKey(string password, int keySize)
{
byte[] salt = Encoding.UTF8.GetBytes("SecureKeySalt");
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, DefaultIterations, HashAlgorithmName.SHA256))
{
return pbkdf2.GetBytes(keySize);
}
}
/// <summary>
/// 生成强随机密码
/// </summary>
/// <param name="length">密码长度</param>
/// <param name="includeSpecialChars">是否包含特殊字符</param>
/// <returns>随机密码</returns>
public static string GenerateRandomPassword(int length = 16, bool includeSpecialChars = true)
{
const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string lower = "abcdefghijklmnopqrstuvwxyz";
const string digits = "0123456789";
const string special = "!@#$%^&*()_-+=[]{}|;:,.<>?";
string validChars = upper + lower + digits;
if (includeSpecialChars) validChars += special;
StringBuilder password = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] randomBytes = new byte[4];
while (password.Length < length)
{
rng.GetBytes(randomBytes);
uint randomValue = BitConverter.ToUInt32(randomBytes, 0);
password.Append(validChars[(int)(randomValue % (uint)validChars.Length)]);
}
}
return password.ToString();
}
#endregion
}
}