Generating .htpasswd Files in Java

Learn how to create and manage .htpasswd files for Apache authentication using Java.

Introduction

Java can be used to generate .htpasswd files for Apache HTTP server authentication. This involves hashing passwords in a way that is compatible with Apache's authentication mechanism. Below, we use Java's cryptographic libraries for this purpose.

Prerequisites

Ensure you have the Apache Commons Codec library available in your project for encoding the hashed password:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>
            
Creating a New .htpasswd File

Here's a simple Java method to create a new .htpasswd file:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;

public void createHtpasswdFile(String username, String password) throws Exception {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(password.getBytes("UTF-8"));
    String encodedPassword = "{SHA}" + Base64.encodeBase64String(hash);

    String content = username + ":" + encodedPassword;
    Files.write(Paths.get(".htpasswd"), content.getBytes());
}
            
Appending a User to an Existing .htpasswd File

To add a new user to an existing .htpasswd file, append the user with a hashed password:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;

public void appendUserToHtpasswdFile(String username, String password) throws Exception {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(password.getBytes("UTF-8"));
    String encodedPassword = "{SHA}" + Base64.encodeBase64String(hash);

    String content = "\n" + username + ":" + encodedPassword;
    Files.write(Paths.get(".htpasswd"), content.getBytes(), StandardOpenOption.APPEND);
}