001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.revetsec.password;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import com.revetsec.internal.encoding.EncodingException;
020import com.revetsec.internal.encoding.StrictUtf8;
021import com.revetsec.internal.password.Argon2id;
022import com.revetsec.internal.password.Argon2idInterruptedException;
023import com.revetsec.internal.password.LegacyPasswordVerifier;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026
027import javax.annotation.concurrent.NotThreadSafe;
028import javax.annotation.concurrent.ThreadSafe;
029import java.nio.CharBuffer;
030import java.security.MessageDigest;
031import java.security.SecureRandom;
032import java.text.Normalizer;
033import java.util.Arrays;
034
035import static java.util.Objects.requireNonNull;
036
037/** Standalone, caller-thread password hashing. New hashes are Argon2id v19; legacy bcrypt and
038 * PBKDF2 verification are separate, opt-in operations selected by trusted account provenance.
039 * Applications own account lookup, per-account online admission, password policy, credential
040 * persistence, credential-version checks, rehash compare-and-swap, and login sessions/MFA.
041 * <p>Instances are safe to share across threads when their supplied work gate and pepper source
042 * are shared and thread-safe. No operation starts a worker thread. A pepper-enabled instance
043 * requires its peppered native stored form and never falls back to an unpeppered PHC value.
044 * One work permit covers preparation, pepper lookup and KDF cleanup. NFC uses the running JDK's
045 * Unicode data; stored forms do not identify that preparation revision. Applications own trusted
046 * credential preparation cohorts and verified migration between them.
047 * @since 1.0.0 */
048@ThreadSafe
049public final class PasswordHasher {
050    private static final int SALT_BYTES = 16;
051    private static final int TAG_BYTES = 32;
052
053    private final @NonNull Argon2idParameters parameters;
054    private final @NonNull PasswordWorkGate workGate;
055    private final @NonNull PasswordVerificationLimits limits;
056    private final @Nullable PasswordPepperSource pepperSource;
057    private final @Nullable LegacyPasswordPreparation bcryptPreparation;
058    private final int maximumBcryptLogRounds;
059    private final @Nullable LegacyPasswordPreparation pbkdf2Preparation;
060    private final int maximumPbkdf2Iterations;
061
062    private PasswordHasher(@NonNull Builder builder) {
063        this.parameters = builder.parameters;
064        this.workGate = requireNonNull(builder.workGate);
065        this.limits = builder.limits;
066        this.pepperSource = builder.pepperSource;
067        this.bcryptPreparation = builder.bcryptPreparation;
068        this.maximumBcryptLogRounds = builder.maximumBcryptLogRounds;
069        this.pbkdf2Preparation = builder.pbkdf2Preparation;
070        this.maximumPbkdf2Iterations = builder.maximumPbkdf2Iterations;
071    }
072
073    /** Starts configuration with the required new-hash policy. Construction performs no crypto,
074     * random-source, provider, storage, or network work.
075     * @param parameters Argon2id v19 creation parameters
076     * @return a builder
077     * @since 1.0.0 */
078    public static @NonNull Builder withArgon2id(@NonNull Argon2idParameters parameters) {
079        return new Builder(requireNonNull(parameters));
080    }
081
082    /** Hashes a new password after bounded NFC/strict-UTF-8 preparation. The input array is
083     * borrowed and never modified or retained; the caller must clear it when finished. No minimum
084     * password-strength policy is implied by successful hashing.
085     * @param password complete submitted password
086     * @return a new stored verifier, rejection, or unavailability
087     * @since 1.0.0 */
088    @CheckReturnValue
089    public @NonNull PasswordHashResult hashResult(char @NonNull [] password) {
090        requireNonNull(password);
091        if (Thread.currentThread().isInterrupted())
092            return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
093        PasswordWorkGate.Permit permit = workGate.tryAcquire(parameters.getMemoryKiB());
094        if (permit == null) return PasswordHashResult.unavailable(workAdmissionFailureReason());
095        try (permit) {
096            if (Thread.currentThread().isInterrupted())
097                return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
098            PreparedInput prepared = prepare(password, LegacyPasswordPreparation.NFC_UTF8);
099            if (prepared.reason != null) return PasswordHashResult.rejected(prepared.reason);
100            byte[] input = requireNonNull(prepared.bytes);
101            byte[] secret = new byte[0];
102            byte[] salt = new byte[SALT_BYTES];
103            byte[] tag = null;
104            try {
105                if (Thread.currentThread().isInterrupted())
106                    return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
107                String keyId = null;
108                if (pepperSource != null) {
109                    PasswordPepperSnapshot snapshot = pepperSnapshot();
110                    if (Thread.currentThread().isInterrupted())
111                        return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
112                    if (snapshot == null) return PasswordHashResult.unavailable(PasswordUnavailableReason.PEPPER_UNAVAILABLE);
113                    PasswordPepperKey key = snapshot.activeKey();
114                    keyId = key.getKeyId();
115                    secret = key.copyKeyBytes();
116                }
117                if (Thread.currentThread().isInterrupted())
118                    return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
119                try {
120                    new SecureRandom().nextBytes(salt);
121                } catch (RuntimeException e) {
122                    return PasswordHashResult.unavailable(PasswordUnavailableReason.CRYPTO_UNAVAILABLE);
123                }
124                tag = Argon2id.hash(input, salt, secret, parameters.getMemoryKiB(),
125                        parameters.getPasses(), parameters.getLanes(), TAG_BYTES);
126                return PasswordHashResult.succeeded(new PasswordHash(
127                        PasswordStoredForm.encode(parameters, salt, tag, keyId)));
128
129            } catch (Argon2idInterruptedException e) {
130                return PasswordHashResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
131            } finally {
132                Arrays.fill(input, (byte) 0);
133                Arrays.fill(secret, (byte) 0);
134                Arrays.fill(salt, (byte) 0);
135                if (tag != null) Arrays.fill(tag, (byte) 0);
136            }
137        }
138    }
139
140    /** Verifies only a native Argon2id stored form under this deployment's pepper policy. It
141     * parses and caps encoded length, costs, salt and tag before allocating KDF memory.
142     * @param password complete submitted password; borrowed and not modified
143     * @param storedForm account-owned stored verifier
144     * @return a complete verification outcome
145     * @since 1.0.0 */
146    @CheckReturnValue
147    public @NonNull PasswordVerificationResult verifyResult(char @NonNull [] password,
148            @NonNull String storedForm) {
149        requireNonNull(password); requireNonNull(storedForm);
150        if (Thread.currentThread().isInterrupted())
151            return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
152        PasswordStoredForm form = PasswordStoredForm.parse(storedForm, limits);
153        if (form.status() == PasswordStoredForm.Status.INVALID)
154            return PasswordVerificationResult.rejected(PasswordRejectionReason.INVALID_STORED_HASH);
155        if (form.status() == PasswordStoredForm.Status.UNSUPPORTED)
156            return PasswordVerificationResult.rejected(PasswordRejectionReason.UNSUPPORTED_STORED_HASH);
157        try {
158            if (pepperSource == null && form.peppered())
159                return PasswordVerificationResult.unavailable(PasswordUnavailableReason.PEPPER_UNAVAILABLE);
160            if (pepperSource != null && !form.peppered())
161                return PasswordVerificationResult.rejected(PasswordRejectionReason.UNSUPPORTED_STORED_HASH);
162            PasswordWorkGate.Permit permit = workGate.tryAcquire(form.memoryKiB());
163            if (permit == null) return PasswordVerificationResult.unavailable(workAdmissionFailureReason());
164            try (permit) {
165                if (Thread.currentThread().isInterrupted())
166                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
167                PreparedInput prepared = prepare(password, LegacyPasswordPreparation.NFC_UTF8);
168                if (prepared.reason != null) return PasswordVerificationResult.rejected(prepared.reason);
169                byte[] input = requireNonNull(prepared.bytes);
170                byte[] secret = new byte[0];
171                byte[] actual = null;
172                try {
173                    if (Thread.currentThread().isInterrupted())
174                        return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
175                    PasswordPepperSnapshot snapshot = null;
176                    if (pepperSource != null) {
177                        snapshot = pepperSnapshot();
178                        if (Thread.currentThread().isInterrupted())
179                            return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
180                        if (snapshot == null) return PasswordVerificationResult.unavailable(PasswordUnavailableReason.PEPPER_UNAVAILABLE);
181                        PasswordPepperKey key = snapshot.keyForId(requireNonNull(form.pepperKeyId()));
182                        if (key == null) return PasswordVerificationResult.unavailable(PasswordUnavailableReason.PEPPER_UNAVAILABLE);
183                        secret = key.copyKeyBytes();
184                    }
185                    if (Thread.currentThread().isInterrupted())
186                        return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
187                    actual = Argon2id.hash(input, form.salt(), secret, form.memoryKiB(),
188                            form.passes(), form.lanes(), form.tag().length);
189                    if (!MessageDigest.isEqual(form.tag(), actual)) return PasswordVerificationResult.notMatched();
190                    boolean policyDominates = parameters.getMemoryKiB() >= form.memoryKiB()
191                            && parameters.getPasses() >= form.passes();
192                    boolean staleCosts = parameters.getMemoryKiB() > form.memoryKiB()
193                            || parameters.getPasses() > form.passes()
194                            || parameters.getLanes() != form.lanes()
195                            || form.salt().length < SALT_BYTES || form.tag().length < TAG_BYTES;
196                    boolean oldPepper = snapshot != null
197                            && !snapshot.getActiveKeyId().equals(form.pepperKeyId());
198                    return PasswordVerificationResult.matched(policyDominates && (staleCosts || oldPepper));
199
200                } catch (Argon2idInterruptedException e) {
201                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
202                } finally {
203                    Arrays.fill(input, (byte) 0);
204                    Arrays.fill(secret, (byte) 0);
205                    if (actual != null) Arrays.fill(actual, (byte) 0);
206                }
207            }
208        } finally {
209            form.wipe();
210        }
211    }
212
213    /** Verifies one explicitly selected historical bcrypt record. The application must select
214     * this operation from trusted account provenance; no stored hash auto-selects a legacy path.
215     * Candidates exceeding bcrypt's 72-byte input limit are rejected without truncation.
216     * @param password submitted password; borrowed and not modified
217     * @param storedForm historical modular-crypt bcrypt value
218     * @return a complete verification outcome; every match recommends Argon2id rehash
219     * @since 1.0.0 */
220    @CheckReturnValue
221    public @NonNull PasswordVerificationResult verifyLegacyBcryptResult(char @NonNull [] password,
222            @NonNull String storedForm) {
223        requireNonNull(password); requireNonNull(storedForm);
224        if (bcryptPreparation == null)
225            return PasswordVerificationResult.rejected(PasswordRejectionReason.UNSUPPORTED_STORED_HASH);
226        if (storedForm.length() > limits.getMaximumStoredFormChars())
227            return PasswordVerificationResult.rejected(PasswordRejectionReason.INVALID_STORED_HASH);
228        if (Thread.currentThread().isInterrupted())
229            return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
230        PasswordWorkGate.Permit permit = workGate.tryAcquire(0);
231        if (permit == null) return PasswordVerificationResult.unavailable(workAdmissionFailureReason());
232        try (permit) {
233            if (Thread.currentThread().isInterrupted())
234                return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
235            PreparedInput prepared = prepare(password, bcryptPreparation);
236            if (prepared.reason != null) return PasswordVerificationResult.rejected(prepared.reason);
237            byte[] input = requireNonNull(prepared.bytes);
238            try {
239                if (Thread.currentThread().isInterrupted())
240                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
241                if (input.length > 72)
242                    return PasswordVerificationResult.rejected(PasswordRejectionReason.LEGACY_BCRYPT_INPUT_TOO_LONG);
243                LegacyPasswordVerifier.Result result = LegacyPasswordVerifier.verifyBcrypt(input, storedForm,
244                        maximumBcryptLogRounds);
245                if (Thread.currentThread().isInterrupted())
246                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
247                return legacyResult(result);
248
249            } finally {
250                Arrays.fill(input, (byte) 0);
251            }
252        }
253    }
254
255    /** Verifies one historical PBKDF2 record whose fields the application extracted from its
256     * trusted legacy schema. No generic PBKDF2 string parser or format autodetection is provided.
257     * @param password submitted password; borrowed and not modified
258     * @param hmac historical HMAC algorithm
259     * @param iterations historical iteration count
260     * @param salt historical salt; borrowed and not modified
261     * @param expectedTag historical derived value; borrowed and not modified
262     * @return a complete verification outcome; every match recommends Argon2id rehash
263     * @since 1.0.0 */
264    @CheckReturnValue
265    public @NonNull PasswordVerificationResult verifyLegacyPbkdf2Result(char @NonNull [] password,
266            @NonNull Pbkdf2Hmac hmac, @NonNull Integer iterations, byte @NonNull [] salt,
267            byte @NonNull [] expectedTag) {
268        requireNonNull(password); requireNonNull(hmac); requireNonNull(iterations); requireNonNull(salt); requireNonNull(expectedTag);
269        if (pbkdf2Preparation == null)
270            return PasswordVerificationResult.rejected(PasswordRejectionReason.UNSUPPORTED_STORED_HASH);
271        if (iterations < 1 || iterations > maximumPbkdf2Iterations || salt.length < 8
272                || salt.length > 64 || expectedTag.length < 16 || expectedTag.length > 64)
273            return PasswordVerificationResult.rejected(PasswordRejectionReason.INVALID_STORED_HASH);
274        if (Thread.currentThread().isInterrupted())
275            return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
276        PasswordWorkGate.Permit permit = workGate.tryAcquire(0);
277        if (permit == null) return PasswordVerificationResult.unavailable(workAdmissionFailureReason());
278        try (permit) {
279            if (Thread.currentThread().isInterrupted())
280                return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
281            PreparedInput prepared = prepare(password, pbkdf2Preparation);
282            if (prepared.reason != null) return PasswordVerificationResult.rejected(prepared.reason);
283            byte[] input = requireNonNull(prepared.bytes);
284            byte[] saltCopy = salt.clone();
285            byte[] tagCopy = expectedTag.clone();
286            try {
287                if (Thread.currentThread().isInterrupted())
288                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
289                LegacyPasswordVerifier.Result result = LegacyPasswordVerifier.verifyPbkdf2(input,
290                        hmac.jcaName(), iterations, saltCopy, tagCopy, maximumPbkdf2Iterations);
291                if (Thread.currentThread().isInterrupted())
292                    return PasswordVerificationResult.unavailable(PasswordUnavailableReason.INTERRUPTED);
293                return legacyResult(result);
294
295            } finally {
296                Arrays.fill(input, (byte) 0);
297                Arrays.fill(saltCopy, (byte) 0);
298                Arrays.fill(tagCopy, (byte) 0);
299            }
300        }
301    }
302
303    private static @NonNull PasswordUnavailableReason workAdmissionFailureReason() {
304        return Thread.currentThread().isInterrupted()
305                ? PasswordUnavailableReason.INTERRUPTED : PasswordUnavailableReason.WORK_CAPACITY;
306    }
307
308    private @Nullable PasswordPepperSnapshot pepperSnapshot() {
309        try {
310            PasswordPepperSnapshotResult result = requireNonNull(pepperSource).snapshotResult();
311            return result instanceof PasswordPepperSnapshotResult.Available available
312                    ? available.getSnapshot() : null;
313        } catch (RuntimeException e) {
314            return null;
315        }
316    }
317
318    private @NonNull PreparedInput prepare(char @NonNull [] password,
319            @NonNull LegacyPasswordPreparation preparation) {
320        if (password.length > limits.getMaximumPasswordChars())
321            return PreparedInput.rejected(PasswordRejectionReason.PASSWORD_TOO_LONG);
322        for (int i = 0; i < password.length; i++) {
323            char ch = password[i];
324            if (Character.isHighSurrogate(ch)) {
325                if (++i >= password.length || !Character.isLowSurrogate(password[i]))
326                    return PreparedInput.rejected(PasswordRejectionReason.INVALID_PASSWORD);
327            } else if (Character.isLowSurrogate(ch)) {
328                return PreparedInput.rejected(PasswordRejectionReason.INVALID_PASSWORD);
329            }
330        }
331        String text = preparation == LegacyPasswordPreparation.NFC_UTF8
332                ? Normalizer.normalize(CharBuffer.wrap(password), Normalizer.Form.NFC)
333                : new String(password);
334        try {
335            byte[] bytes = StrictUtf8.encode(text);
336            if (bytes.length > limits.getMaximumPasswordUtf8Bytes()) {
337                Arrays.fill(bytes, (byte) 0);
338                return PreparedInput.rejected(PasswordRejectionReason.PASSWORD_TOO_LONG);
339            }
340            return PreparedInput.accepted(bytes);
341        } catch (EncodingException e) {
342            return PreparedInput.rejected(PasswordRejectionReason.INVALID_PASSWORD);
343        }
344    }
345
346    private static @NonNull PasswordVerificationResult legacyResult(LegacyPasswordVerifier.@NonNull Result result) {
347        return switch (result) {
348            case MATCHED -> PasswordVerificationResult.matched(true);
349            case NOT_MATCHED -> PasswordVerificationResult.notMatched();
350            case TRUNCATED_INPUT -> PasswordVerificationResult.rejected(PasswordRejectionReason.LEGACY_BCRYPT_INPUT_TOO_LONG);
351            case MALFORMED -> PasswordVerificationResult.rejected(PasswordRejectionReason.INVALID_STORED_HASH);
352            case UNAVAILABLE -> PasswordVerificationResult.unavailable(PasswordUnavailableReason.CRYPTO_UNAVAILABLE);
353        };
354    }
355
356    private static final class PreparedInput {
357        private final byte @Nullable [] bytes;
358        private final @Nullable PasswordRejectionReason reason;
359        private PreparedInput(byte @Nullable [] bytes, @Nullable PasswordRejectionReason reason) {
360            this.bytes = bytes; this.reason = reason;
361        }
362        static @NonNull PreparedInput accepted(byte @NonNull [] bytes) { return new PreparedInput(bytes, null); }
363        static @NonNull PreparedInput rejected(@NonNull PasswordRejectionReason reason) { return new PreparedInput(null, reason); }
364    }
365
366    /** Mutable configuration helper. All provider and cryptographic work occurs during operations.
367     * @since 1.0.0 */
368    @NotThreadSafe
369    @CheckReturnValue
370    public static final class Builder {
371        private final @NonNull Argon2idParameters parameters;
372        private @Nullable PasswordWorkGate workGate;
373        private @NonNull PasswordVerificationLimits limits = PasswordVerificationLimits.fromDefaults();
374        private @Nullable PasswordPepperSource pepperSource;
375        private @Nullable LegacyPasswordPreparation bcryptPreparation;
376        private int maximumBcryptLogRounds;
377        private @Nullable LegacyPasswordPreparation pbkdf2Preparation;
378        private int maximumPbkdf2Iterations;
379
380        private Builder(@NonNull Argon2idParameters parameters) { this.parameters = parameters; }
381
382        /** Sets the shared, process-local preparation, pepper and KDF admission gate.
383         * @param gate shared gate, or null to clear this required setting
384         * @return this builder
385         * @since 1.0.0 */
386        public @NonNull Builder workGate(@Nullable PasswordWorkGate gate) { this.workGate = gate; return this; }
387
388        /** Sets strict input and stored-work ceilings. A stored memory cost within these ceilings
389         * but above the gate's total budget is intentionally unavailable even with an idle gate.
390         * @param limits verification ceilings, or null to restore conservative defaults
391         * @return this builder
392         * @since 1.0.0 */
393        public @NonNull Builder verificationLimits(@Nullable PasswordVerificationLimits limits) {
394            this.limits = limits == null ? PasswordVerificationLimits.fromDefaults() : limits; return this;
395        }
396
397        /** Requires RFC 9106 keyed Argon2id for new and native verified hashes. Ordinary raw PHC
398         * values are refused by a pepper-enabled hasher.
399         * @param source coherent active/retained key provider, or null to clear pepper policy
400         * @return this builder
401         * @since 1.0.0 */
402        public @NonNull Builder pepperSource(@Nullable PasswordPepperSource source) {
403            this.pepperSource = source; return this;
404        }
405
406        /** Enables explicit verify-only bcrypt migration. Historical preparation must be known.
407         * @param preparation original character preparation
408         * @param maximumLogRounds maximum accepted bcrypt log2 work cost, 4–16
409         * @return this builder
410         * @since 1.0.0 */
411        public @NonNull Builder legacyBcrypt(@NonNull LegacyPasswordPreparation preparation,
412                @NonNull Integer maximumLogRounds) {
413            this.bcryptPreparation = requireNonNull(preparation);
414            this.maximumBcryptLogRounds = requireNonNull(maximumLogRounds);
415            return this;
416        }
417
418        /** Enables explicit verify-only PBKDF2 migration. The application supplies historical
419         * salt, tag, iteration count, and HMAC selection from its trusted account schema.
420         * @param preparation original character preparation
421         * @param maximumIterations maximum accepted iteration count, at most 2,000,000
422         * @return this builder
423         * @since 1.0.0 */
424        public @NonNull Builder legacyPbkdf2(@NonNull LegacyPasswordPreparation preparation,
425                @NonNull Integer maximumIterations) {
426            this.pbkdf2Preparation = requireNonNull(preparation);
427            this.maximumPbkdf2Iterations = requireNonNull(maximumIterations);
428            return this;
429        }
430
431        /** Validates local configuration without looking up keys, providers, or random bytes.
432         * @return a thread-safe hasher
433         * @since 1.0.0 */
434        public @NonNull PasswordHasher build() {
435            if (workGate == null) throw new IllegalStateException("Password work gate is required");
436            if (parameters.getMemoryKiB() > workGate.getMaximumMemoryKiB()
437                    || parameters.getMemoryKiB() > limits.getMaximumArgon2idMemoryKiB()
438                    || parameters.getPasses() > limits.getMaximumArgon2idPasses()
439                    || parameters.getLanes() > limits.getMaximumArgon2idLanes()) {
440                throw new IllegalArgumentException("New-hash parameters exceed verification or work limits");
441            }
442            if (bcryptPreparation != null && (maximumBcryptLogRounds < 4 || maximumBcryptLogRounds > 16))
443                throw new IllegalArgumentException("Invalid bcrypt migration ceiling");
444            if (pbkdf2Preparation != null && (maximumPbkdf2Iterations < 1 || maximumPbkdf2Iterations > 2_000_000))
445                throw new IllegalArgumentException("Invalid PBKDF2 migration ceiling");
446            return new PasswordHasher(this);
447        }
448    }
449}