首页 > 解决方案 > 在 powershell 中创建 htpasswd SHA1 密码

问题描述

我想在 PowerShell 中创建一个基于 SHA1 的 htpasswd 密码。

使用单词“test”作为密码,我测试了各种功能,并且总是得到 SHA1 值:

a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

在 htpasswd 文件中测试它

user:{SHA}a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

我无法登录。

使用在线 htpasswd 生成器。例如https://www.askapache.com/online-tools/htpasswd-generator/我得到

user:{SHA}qUqP5cyxm6YcTAhz05Hph5gvu9M=

哪个工作得很好。

起初我以为我需要进行 base64 编码/解码,但事实并非如此。

有人知道如何从“测试”到“qUqP5cyxm6YcTAhz05Hph5gvu9M =”吗?

标签: powershellsha1.htpasswd

解决方案


起初我以为我需要做一个base64编码/解码

确实如此!但是您需要编码的不是字符串“a94a8fe5ccb19ba61c4c0873d391e987982fbbd3”,而是它代表的底层字节数组

$username = 'user'
$password = 'test'

# Compute hash over password
$passwordBytes = [System.Text.Encoding]::ASCII.GetBytes($password)
$sha1 = [System.Security.Cryptography.SHA1]::Create()
$hash = $sha1.ComputeHash($passwordBytes)

# Had we at this point converted $hash to a hex string with, say:
#
#   [BitConverter]::ToString($hash).ToLower() -replace '-'
#
# ... we would have gotten "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"


# Convert resulting bytes to base64
$hashedpasswd = [convert]::ToBase64String($hash)

# Generate htpasswd entry
"${username}:{{SHA}}${hashedpasswd}"

推荐阅读