[ZT]Generating Forms Authentication Compatible Passwords (SHA1)

本文介绍了使用VB.Net创建与表单身份验证兼容的SHA1密码的两种方法,分别适用于.Net Web应用程序和.Net Windows窗体或控制台应用程序。存储明文密码很危险,SHA1可将密码编码为不可读形式,更安全地存储在数据库中。文中给出了具体代码示例。

Generating Forms Authentication Compatible Passwords (SHA1)
by Anthony Ogden.

In this article we will take a quick look at two methods for creating SHA1 passwords for use on the web.

In brief we show how to generate SHA1 hashes that are Forms Authentication compatible via:

  • Net Web Application
  • .Net Windows Form or Console Application

Why would we want to create an SHA1 Password Hash?
The answer to this is easy. It is dangerous to store passwords anywhere in plain text!! SHA1 gives a quick and easy way to encode a password into a non-human readable form. This means it is safer to store in a database, and should the database be viewed by anyone who shouldn't know the passwords, it will be much more difficult for them to work out what a user's password is.

Creating an SHA1 Password Hash using a Web Application
Download the VB.Net project file here.

When creating a Web Application we can use the HashPasswordForStoringInConfigFile object in the FormsAuthentication namespace to generate our SHA1 password hash.

The following section of code shows an example of this:

Dim encpass As String = _
  FormsAuthentication.HashPasswordForStoringInConfigFile(tbxPassword.Text, _
  "sha1")
tbxResult.Text = encpass.ToString()

The code takes the text from the "thePassword" textbox control and hashes the contents with the SHA1 algorithm. The result is then in the "theResult" textbox control.

This hashed password can then be placed in your web.config file or in a database and used in your web application for Forms Authentication. In a future tutorial we will show how to go on and use this in an application.

Creating an SHA1 Password Hash using a Windows Form/Console Application
Download the VB.Net project file for this application here.

The code for creating a Forms Authentication compatible password from a Windows App is slightly different. Instead of using the System.Web.Security.FormsAuthentication namespace, we use the System.Security.Cryptography namespace. We also have an additional step to take in converting the SHA1 hash from binary into a Hexadecimal string, which is the format used in FormsAuthentication.

The following sections of code show the steps we have to take to get a compatible password hash from a windows application:

	Dim myString As String = "PASSWORD"
	Dim Data As Byte()

	Data = Encoding.ASCII.GetBytes(myString)

The SHA1Managed object expected our data as binary bytes, so the code above converts our string "PASSWORD" into a sequence of bytes.

	Dim shaM As New SHA1Managed()
	Dim resultHash As Byte() = shaM.ComputeHash(Data)

The preceding lines encode our data with SHA1 and we end up with a sequence of binary bytes representing the encoded password.

	Dim resultHexString = ""
	Dim b As Byte

	For Each b In resultHash
		resultHexString += Hex(b)
	Next

The lines above take our binary data and convert the bytes into a Hexadecimal string representation, the format that is used when using FormsAuthentication. You can check you get the same results by first running the web application version and taking the resulting string, running the windows application with the same password and comparing the encoded result.

HMAC-SHA1 是一种基于散列函数 SHA-1 的消息认证码(MAC)算法,用于确保数据完整性和身份验证。其核心思想是通过一个共享密钥与消息结合,生成一个固定长度的摘要,该摘要能够验证消息未被篡改,并且只有拥有相同密钥的接收方才能生成相同的摘要。 ### HMAC-SHA1 的工作原理 HMAC-SHA1 的工作流程可以分为以下几个步骤: 1. **密钥处理**:如果密钥长度超过 SHA-1 的块大小(64 字节),则先对密钥进行一次 SHA-1 哈希运算,使其长度变为 20 字节(160 位)。如果密钥长度不足 64 字节,则在其后面填充零字节,使其达到 64 字节。 2. **生成内部密钥和外部密钥**:将处理后的密钥分别与两个固定的填充字节 `opad`(0x5C)和 `ipad`(0x36)进行异或操作,生成两个不同的密钥 `k_opad` 和 `k_ipad`。这两个密钥的作用是增加算法的不可预测性。 3. **内部哈希计算**:将 `k_ipad` 与消息拼接,然后对其进行一次 SHA-1 哈希运算,生成一个中间哈希值。 4. **外部哈希计算**:将 `k_opad` 与上一步生成的中间哈希值拼接,再次进行 SHA-1 哈希运算,最终生成 HMAC-SHA1 的输出。 ### HMAC-SHA1 的数学表达式 HMAC-SHA1 的计算公式可以表示为: $$ \text{HMAC-SHA1}(K, m) = \text{SHA1}( (K_{\text{opad}} \parallel \text{SHA1}(K_{\text{ipad}} \parallel m)) ) $$ 其中: - $ K $ 是密钥; - $ m $ 是输入消息; - $ K_{\text{ipad}} = K \oplus \text{ipad} $; - $ K_{\text{opad}} = K \oplus \text{opad} $; - $ \parallel $ 表示字符串拼接操作。 ### HMAC-SHA1 的安全性 尽管 SHA-1 已经被证明存在碰撞攻击的漏洞,但在 HMAC 构造中,SHA-1 的碰撞攻击并不会直接影响 HMAC 的安全性。这是因为 HMAC 的设计使得攻击者需要同时知道密钥和内部状态,这在大多数实际应用中是难以实现的。然而,随着密码学的发展,建议使用更安全的哈希函数如 SHA-256 或 SHA-3 来替代 SHA-1,以获得更强的安全保障。 ### HMAC-SHA1 的应用场景 HMAC-SHA1 被广泛应用于各种安全协议中,例如: - **OAuth 1.0**:用于生成请求签名,确保请求的完整性和真实性。 - **IPsec**:在 Internet 协议安全中,用于验证数据包的来源和完整性。 - **TLS/SSL**:在传输层安全协议中,用于生成消息认证码,防止数据被篡改。 ### HMAC-SHA1 的代码实现(Java) 以下是一个使用 Java 实现 HMAC-SHA1 的示例代码: ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class HmacSha1Example { public static String generateHmacSha1(String data, String key) { try { // 创建 HMAC-SHA1 密钥 SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); // 获取 Mac 实例并初始化 Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKeySpec); // 执行 HMAC-SHA1 计算 byte[] hmacBytes = mac.doFinal(data.getBytes()); // 将结果进行 Base64 编码并返回 return Base64.getEncoder().encodeToString(hmacBytes); } catch (Exception e) { throw new RuntimeException("Error generating HMAC-SHA1", e); } } public static void main(String[] args) { String data = "Hello, World!"; String key = "secret_key"; String hmac = generateHmacSha1(data, key); System.out.println("HMAC-SHA1: " + hmac); } } ``` ### HMAC-SHA1 的代码实现(C) 以下是一个使用 OpenSSL 库实现 HMAC-SHA1 的 C 语言示例代码: ```c #include <openssl/hmac.h> #include <openssl/evp.h> #include <stdio.h> #include <string.h> void generate_hmac_sha1(const char *data, const char *key, unsigned char *digest) { unsigned int digest_len = EVP_MD_size(EVP_sha1()); HMAC(EVP_sha1(), key, strlen(key), (unsigned char *)data, strlen(data), digest, &digest_len); } int main() { const char *data = "Hello, World!"; const char *key = "secret_key"; unsigned char digest[20]; // SHA1 输出长度为 20 字节 generate_hmac_sha1(data, key, digest); // 打印十六进制格式的 HMAC-SHA1 结果 for (int i = 0; i < 20; i++) { printf("%02x", digest[i]); } printf("\n"); return 0; } ``` ### 总结 HMAC-SHA1 是一种结合了密钥和消息的认证机制,通过 SHA-1 哈希函数生成一个固定长度的摘要,用于验证数据的完整性和真实性。虽然 SHA-1 存在一定的安全风险,但在 HMAC 构造中仍然具有较高的安全性。为了进一步提升安全性,建议使用更现代的哈希算法如 SHA-256 或 SHA-3。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值