Secret Wipe With char Array And Arrays.fill

Keep secrets in char[] and zero the buffer with Arrays.fill after use; immutable String copies linger until GC, so passwords should never become one.

JavaSecurity Boundaries

Code

snippet
import java.util.Arrays;

public class SecretWipe {

    // 校验口令后立刻清零缓冲:比对与清理在同一步完成
    static boolean verify(char[] secret, char[] expected) {
        try {
            return Arrays.equals(secret, expected);
        } finally {
            Arrays.fill(secret, (char) 0);
        }
    }

    public static void main(String[] args) {
        // Console.readPassword() 返回 char[]:口令尽量不落成 String,
        // String 不可变、只能等 GC,char[] 可以主动清零
        char[] typed = "hunter2!".toCharArray();

        System.out.println("verify: " + verify(typed, "hunter2!".toCharArray()));

        long nonZero = new String(typed).chars().filter(c -> c != 0).count();
        System.out.println("non-zero chars left: " + nonZero);
    }
}

How it works

Secret Wipe With char Array And Arrays.fill reduces to the class SecretWipe and the functions verify and main.

Putting it to use

The one signature that matters here is static boolean verify(char[] secret, char[] expected)

The demo output is labeled (verify:, non-zero chars left:), so each printed line points back to the operation that produced it.

The entry point wires verify together — run it once and the whole demo flows.

Core lines

long nonZero = new String(typed).chars().filter(c -> c != 0).count();
return Arrays.equals(secret, expected);

Interactive Tools for This Topic

FAQ

What does Secret Wipe With char Array And Arrays.fill print when run?
Invoke the file as-is — the `verify:`, `non-zero chars left:` prefixes identify which step printed each line.