Learn how to create and manage .htpasswd files for Apache authentication using .NET.
.NET provides various cryptographic methods to securely encrypt passwords. For .htpasswd files, the BCrypt algorithm is often recommended. This example uses the BCrypt.Net-Next library for password hashing.
First, ensure you have installed the BCrypt.Net-Next NuGet package:
Install-Package BCrypt.Net-Next
Use the following C# script to create a new .htpasswd file with a username and a hashed password:
using System.IO; using BCrypt.Net; var username = "myUsername"; // Replace with your username var password = "myPassword"; // Replace with your password var hashedPassword = BCrypt.Net.BCrypt.HashPassword(password); var htpasswdContent = $"{username}:{hashedPassword}"; File.WriteAllText(".htpasswd", htpasswdContent);
To add a new user to an existing .htpasswd file, append the username and hashed password to the file:
using System.IO; using BCrypt.Net; var username = "newUser"; // Replace with the new username var password = "newPassword"; // Replace with the new password var hashedPassword = BCrypt.Net.BCrypt.HashPassword(password); var htpasswdContent = $"\n{username}:{hashedPassword}"; File.AppendAllText(".htpasswd", htpasswdContent);