三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

HMAC(Hash-based Message Authentication Code)认证示例

HMAC(Hash-based Message Authentication Code)认证示例

HMAC(Hash-based Message Authentication Code)认证从示例中实践

如在《企业内小网站兼用Windows验证登录》https://www.cnblogs.com/insus/p/20061556 这篇随笔中,有从GetDomainUser.aspx获取windows认证User.Identity.Name传送给Login.aspx网页并存储于HiddenField中,而且是明文的。

有个想法,用户会不会修改个此值,盗别人的用户信息来登录呢?

为了解决这个担心,我们可以使用HMAC签名处理。

创建,HmacAuth类,
2026-05-18_09-12-12

 

namespace Insus.NET
{public static class HmacAuth{public static string ComputeSignature(string data, string secretKey) {var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));return Convert.ToBase64String(hash);}}
}
View Code

 

去web.config添加,appSettings,如下高亮一行:
2026-05-18_09-19-21

 

我在GetDomainUser.aspx.cs修改,
2026-05-18_09-17-09

 


上截图中#19,是从Web.config获取SecretKey,此key在维护时,可以不定期修改不相同的值。

#23是计算签名。

#25把Identity.Name和签名一起返加呼叫方。

接下来,我需要在Login.aspx页添加与修改,

2026-05-18_09-29-29


红色框框HiddenField存储HMAC签名。

在SignIn事件中,去计算签名并匹配,看看是否相同。
2026-05-18_09-33-37

 

上截图中,
#50行,从HiddenField取得Identity.Name。
#51,取到签名。
#52,从web.config取到secretKey。
#54,计算签名。
#56,计算出来的签名与从GetDomainUser.aspx计算的签名对比。对比结果相同,说明Identity.Name未被修改过。


← 返回列表