PasswordHasher 算法

本文介绍了一种基于SHA1哈希算法实现的密码验证方法,通过解析存储的哈希密码来验证用户输入的密码是否正确。具体步骤包括从已存储的哈希密码中提取盐值、密码哈希值等信息,并使用相同的盐值对用户提供的密码进行哈希运算,最后比较两个哈希值以判断密码是否匹配。
 1         public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
 2         {
 3             string[] passwordProperties = hashedPassword.Split('|');
 4             if (passwordProperties.Length != 3)
 5             {
 6                 return base.VerifyHashedPassword(hashedPassword, providedPassword);
 7             }
 8             else
 9             {
10                 string passwordHash = passwordProperties[0];
11                 int passwordformat = 1;
12                 string salt = passwordProperties[2];
13                 if (String.Equals(EncryptPassword(providedPassword, passwordformat, salt), passwordHash, StringComparison.CurrentCultureIgnoreCase))
14                 {
15                     return PasswordVerificationResult.SuccessRehashNeeded;
16                 }
17                 else
18                 {
19                     return PasswordVerificationResult.Failed;
20                 }
21             }
22         }
23 
24         
25 private string EncryptPassword(string pass, int passwordFormat, string salt) 26 { 27 if (passwordFormat == 0)
28 return pass; 29 30 byte[] bIn = Encoding.Unicode.GetBytes(pass); 31 byte[] bSalt = Convert.FromBase64String(salt); 32 byte[] bRet = null; 33 34 if (passwordFormat == 1) 35 { // MembershipPasswordFormat.Hashed 36 HashAlgorithm hm = HashAlgorithm.Create("SHA1"); 37 if (hm is KeyedHashAlgorithm) 38 { 39 KeyedHashAlgorithm kha = (KeyedHashAlgorithm)hm; 40 if (kha.Key.Length == bSalt.Length) 41 { 42 kha.Key = bSalt; 43 } 44 else if (kha.Key.Length < bSalt.Length) 45 { 46 byte[] bKey = new byte[kha.Key.Length]; 47 Buffer.BlockCopy(bSalt, 0, bKey, 0, bKey.Length); 48 kha.Key = bKey; 49 } 50 else 51 { 52 byte[] bKey = new byte[kha.Key.Length]; 53 for (int iter = 0; iter < bKey.Length; ) 54 { 55 int len = Math.Min(bSalt.Length, bKey.Length - iter); 56 Buffer.BlockCopy(bSalt, 0, bKey, iter, len); 57 iter += len; 58 } 59 kha.Key = bKey; 60 } 61 bRet = kha.ComputeHash(bIn); 62 } 63 else 64 { 65 byte[] bAll = new byte[bSalt.Length + bIn.Length]; 66 Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length); 67 Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length); 68 bRet = hm.ComputeHash(bAll); 69 } 70 } 71 72 return Convert.ToBase64String(bRet); 73 }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惑豁猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值