Search code examples
powershellsha1.htpasswd

Create htpasswd SHA1 password in powershell


I want to create a htpasswd password, based on SHA1, in PowerShell.

Using the word "test" as password I have tested various functions and always get the SHA1 value:

a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

Testing this in a htpasswd file

user:{SHA}a94a8fe5ccb19ba61c4c0873d391e987982fbbd3

I am not able to login.

Using an online htpasswd generator. For example https://www.askapache.com/online-tools/htpasswd-generator/ I get

user:{SHA}qUqP5cyxm6YcTAhz05Hph5gvu9M=

Which works just fine.

At first I thought I need to do a base64 en/decoding, but that is not the case.

Anybody an idea on how to get from "test" to "qUqP5cyxm6YcTAhz05Hph5gvu9M="?


Solution

  • At first I thought I need to do a base64 en/decoding

    That is indeed the case! But it's not the string "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" that you need to encode, it's the underlying byte array it represents

    $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}"