Shannon Entropy Scores Password Strength

Count character frequencies and sum -p log2 p to score repeat-heavy strings near zero bits per character — a rough signal, not a security verdict.

JavaSecurity Boundaries

Code

snippet
import java.util.HashMap;
import java.util.Map;

public class EntropyMeter {

    // Shannon entropy of character frequencies, in bits per character;
    // a rough strength signal, not a security verdict
    static double entropy(String password) {
        if (password.isEmpty()) {
            return 0.0;
        }
        Map<Character, Integer> counts = new HashMap<>();
        for (char c : password.toCharArray()) {
            counts.merge(c, 1, Integer::sum);
        }
        double bits = 0.0;
        for (int count : counts.values()) {
            double p = (double) count / password.length();
            bits -= p * (Math.log(p) / Math.log(2));
        }
        return bits;
    }

    public static void main(String[] args) {
        for (String password : new String[] {"aaaaaaaa", "aaaabbbb", "abcdefgh"}) {
            System.out.printf("%-8s -> %.3f bits per char%n", password, entropy(password));
        }
    }
}

How the pieces connect — Shannon Entropy Scores Password Strength

Under the hood: the class EntropyMeter and the functions entropy and main.

Iteration happens inside for (char c : password.toCharArray()) — everything outside it runs once.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

The entry-point signature is static double entropy(String password)

Start the program and main runs entropy one after another.

Core lines

Map<Character, Integer> counts = new HashMap<>();
double p = (double) count / password.length();
bits -= p * (Math.log(p) / Math.log(2));

Interactive Tools for This Topic

FAQ

How do you run Shannon Entropy Scores Password Strength?
Execute it straight away — the program needs nothing beyond the runtime.