### Complete Password Validation Service in Java Source: https://context7.com/nulab/zxcvbn4j/llms.txt A full integration example of zxcvbn4j for a password validation service. It includes customization, localization, and security best practices like securely wiping password data from memory. ```java import com.nulabinc.zxcvbn.*; import com.nulabinc.zxcvbn.matchers.Match; import java.util.*; public class PasswordValidationService { private final Zxcvbn zxcvbn; private final int minimumScore; public PasswordValidationService(int minimumScore) throws Exception { this.minimumScore = minimumScore; this.zxcvbn = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .build(); } public ValidationResult validate(CharSequence password, List userInputs, Locale locale) { // Measure password strength Strength strength = zxcvbn.measure(password, userInputs); try { // Build result ValidationResult result = new ValidationResult(); result.valid = strength.getScore() >= minimumScore; result.score = strength.getScore(); result.guesses = strength.getGuesses(); // Get localized feedback Feedback feedback = strength.getFeedback(); result.warning = feedback.getWarning(locale); result.suggestions = feedback.getSuggestions(locale); // Get crack time display AttackTimes.CrackTimesDisplay display = strength.getCrackTimesDisplay(); result.crackTime = display.getOnlineThrottling100perHour(); // Analyze detected patterns result.patterns = new ArrayList<>(); for (Match match : strength.getSequence()) { result.patterns.add(match.pattern.name() + ": " + match.token); } return result; } finally { // Securely wipe password from memory strength.wipe(); } } public static class ValidationResult { public boolean valid; public int score; public double guesses; public String warning; public List suggestions; public String crackTime; public List patterns; @Override public String toString() { return String.format( "Valid: %s, Score: %d, CrackTime: %s, Warning: %s, Suggestions: %s", valid, score, crackTime, warning, suggestions ); } } public static void main(String[] args) throws Exception { PasswordValidationService service = new PasswordValidationService(3); // User context for personalized validation List userInputs = Arrays.asList("john", "doe", "johndoe", "acme"); // Test various passwords String[] passwords = { "password", "johndoe123", "Summer2024!", "correct horse battery staple", "xK9#mP2$vL5@nQ8" }; for (String password : passwords) { System.out.println("\n=== Password: " + password + " ==="); ValidationResult result = service.validate(password, userInputs, Locale.ENGLISH); System.out.println(result); System.out.println("Patterns: " + result.patterns); } } } ``` -------------------------------- ### Get Crack Time in Seconds Source: https://context7.com/nulab/zxcvbn4j/llms.txt Retrieves crack time estimates in seconds for online throttled, online unthrottled, offline slow hashing, and offline fast hashing attack scenarios. Requires importing AttackTimes, Strength, and Zxcvbn classes. ```java import com.nulabinc.zxcvbn.AttackTimes; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; public class CrackTimeEstimation { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("Summer2024!"); // Get crack time in seconds for different attack scenarios AttackTimes.CrackTimeSeconds crackTimeSeconds = strength.getCrackTimeSeconds(); // Online attack with rate limiting (100 attempts per hour) double onlineThrottled = crackTimeSeconds.getOnlineThrottling100perHour(); System.out.println("Online throttled: " + onlineThrottled + " seconds"); // ~360000 seconds (100 hours) // Online attack without rate limiting (10 attempts per second) double onlineUnthrottled = crackTimeSeconds.getOnlineNoThrottling10perSecond(); System.out.println("Online unthrottled: " + onlineUnthrottled + " seconds"); // ~1000 seconds // Offline attack with slow hash like bcrypt (10,000 attempts per second) double offlineSlow = crackTimeSeconds.getOfflineSlowHashing1e4perSecond(); System.out.println("Offline slow hash: " + offlineSlow + " seconds"); // ~1 second // Offline attack with fast hash like MD5/SHA (10 billion attempts per second) double offlineFast = crackTimeSeconds.getOfflineFastHashing1e10PerSecond(); System.out.println("Offline fast hash: " + offlineFast + " seconds"); // ~0.000001 seconds } } ``` -------------------------------- ### Get Human-Readable Crack Times Source: https://context7.com/nulab/zxcvbn4j/llms.txt Provides human-readable crack time estimates as formatted strings for end-user display. This method is useful for presenting complex time data in an easily understandable format. Requires importing AttackTimes, Strength, and Zxcvbn classes. ```java import com.nulabinc.zxcvbn.AttackTimes; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; public class CrackTimeDisplay { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); // Test different password strengths String[] passwords = {"password", "Summer2024", "correct-horse-battery-staple"}; for (String password : passwords) { Strength strength = zxcvbn.measure(password); AttackTimes.CrackTimesDisplay display = strength.getCrackTimesDisplay(); System.out.println("\nPassword: " + password); System.out.println("Score: " + strength.getScore()); System.out.println("Online (throttled): " + display.getOnlineThrottling100perHour()); System.out.println("Online (unthrottled): " + display.getOnlineNoThrottling10perSecond()); System.out.println("Offline (slow hash): " + display.getOfflineSlowHashing1e4perSecond()); System.out.println("Offline (fast hash): " + display.getOfflineFastHashing1e10PerSecond()); } /* Output: Password: password Score: 0 Online (throttled): 3 minutes Online (unthrottled): less than a second Offline (slow hash): less than a second Offline (fast hash): less than a second Password: Summer2024 Score: 1 Online (throttled): 4 days Online (unthrottled): 17 minutes Offline (slow hash): less than a second Offline (fast hash): less than a second Password: correct-horse-battery-staple Score: 4 Online (throttled): centuries Online (unthrottled): centuries Offline (slow hash): centuries Offline (fast hash): 5 months */ } } ``` -------------------------------- ### Get Password Strength Feedback Source: https://context7.com/nulab/zxcvbn4j/llms.txt Use Strength.getFeedback() to obtain a Feedback object. Feedback is only provided for passwords with a score of 2 or below, offering warnings and suggestions for improvement. ```java import com.nulabinc.zxcvbn.Feedback; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import java.util.List; public class PasswordFeedback { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); // Weak password - common password Strength strength1 = zxcvbn.measure("password123"); Feedback feedback1 = strength1.getFeedback(); System.out.println("Password: password123"); System.out.println("Warning: " + feedback1.getWarning()); // Output: "This is a very common password." System.out.println("Suggestions: " + feedback1.getSuggestions()); // Output: ["Add another word or two. Uncommon words are better."] // Weak password - keyboard pattern Strength strength2 = zxcvbn.measure("qwerty"); Feedback feedback2 = strength2.getFeedback(); System.out.println("\nPassword: qwerty"); System.out.println("Warning: " + feedback2.getWarning()); // Output: "Short keyboard patterns are easy to guess." System.out.println("Suggestions: " + feedback2.getSuggestions()); // Output: ["Use a longer keyboard pattern with more turns."] // Weak password - repeated characters Strength strength3 = zxcvbn.measure("aaaaaaa"); Feedback feedback3 = strength3.getFeedback(); System.out.println("\nPassword: aaaaaaa"); System.out.println("Warning: " + feedback3.getWarning()); // Output: "Repeats like \"aaa\" are easy to guess." // Weak password - date pattern Strength strength4 = zxcvbn.measure("19901225"); Feedback feedback4 = strength4.getFeedback(); System.out.println("\nPassword: 19901225"); System.out.println("Warning: " + feedback4.getWarning()); // Output: "Dates are often easy to guess." // Strong password - no feedback needed Strength strength5 = zxcvbn.measure("xK9#mP2$vL5@nQ8"); Feedback feedback5 = strength5.getFeedback(); System.out.println("\nPassword: xK9#mP2$vL5@nQ8"); System.out.println("Warning: " + feedback5.getWarning()); // Output: "" (empty - no issues) System.out.println("Suggestions: " + feedback5.getSuggestions()); // Output: [] (empty - password is strong) } } ``` -------------------------------- ### Load All Default Resources Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md This is the simplest way to initialize zxcvbn, loading all default dictionaries and keyboards. ```java Zxcvbn zxcvbn = new Zxcvbn(); ``` ```java Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .build(); ``` -------------------------------- ### Build and Test zxcvbn4j Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Commands to clone the repository, build, test, and benchmark the zxcvbn4j project using Gradle. ```bash $ git clone https://github.com/nulab/zxcvbn4j.git $ cd ./zxcvbn4j $ ./gradlew build # build $ ./gradlew test # test $ ./gradlew jmh # benchmark ``` -------------------------------- ### Access Standard Keyboard Layouts in Java Source: https://context7.com/nulab/zxcvbn4j/llms.txt Demonstrates how to access and load built-in keyboard layouts like QWERTY, Dvorak, JIS, and keypads using StandardKeyboards. Useful for spatial pattern detection in password analysis. ```java import com.nulabinc.zxcvbn.StandardKeyboards; import com.nulabinc.zxcvbn.matchers.Keyboard; import java.util.List; public class StandardKeyboardsReference { public static void main(String[] args) throws Exception { // Available keyboard loaders and their constants System.out.println("Available keyboards:"); System.out.println("- QWERTY: " + StandardKeyboards.QWERTY); System.out.println("- DVORAK: " + StandardKeyboards.DVORAK); System.out.println("- JIS: " + StandardKeyboards.JIS); // Japanese Industrial Standard System.out.println("- KEYPAD: " + StandardKeyboards.KEYPAD); System.out.println("- MAC_KEYPAD: " + StandardKeyboards.MAC_KEYPAD); // Load individual keyboards Keyboard qwerty = StandardKeyboards.QWERTY_LOADER.load(); Keyboard dvorak = StandardKeyboards.DVORAK_LOADER.load(); Keyboard jis = StandardKeyboards.JIS_LOADER.load(); Keyboard keypad = StandardKeyboards.KEYPAD_LOADER.load(); Keyboard macKeypad = StandardKeyboards.MAC_KEYPAD_LOADER.load(); // Load all keyboards at once List allKeyboards = StandardKeyboards.loadAllKeyboards(); System.out.println("\nTotal keyboards loaded: " + allKeyboards.size()); } } ``` -------------------------------- ### Select and Use Specific Default Resources Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Choose specific default dictionaries and keyboards to load for password analysis. ```java Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionary(StandardDictionaries.ENGLISH_WIKIPEDIA_LOADER.load()) .dictionary(StandardDictionaries.PASSWORDS_LOADER.load()) .keyboard(StandardKeyboards.QWERTY_LOADER.load()) .keyboard(StandardKeyboards.DVORAK_LOADER.load()) .build(); ``` -------------------------------- ### Build Default and Minimal Zxcvbn Instances Source: https://context7.com/nulab/zxcvbn4j/llms.txt Use ZxcvbnBuilder to create Zxcvbn instances. The default build includes all standard dictionaries and keyboards, while a minimal build can be faster by selecting specific dictionaries and keyboards. ```java import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import com.nulabinc.zxcvbn.ZxcvbnBuilder; import com.nulabinc.zxcvbn.StandardDictionaries; import com.nulabinc.zxcvbn.StandardKeyboards; public class CustomZxcvbnBuilder { public static void main(String[] args) throws Exception { // Build with all default dictionaries and keyboards (equivalent to new Zxcvbn()) Zxcvbn defaultZxcvbn = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .build(); // Build with only selected dictionaries for faster performance Zxcvbn minimalZxcvbn = new ZxcvbnBuilder() .dictionary(StandardDictionaries.PASSWORDS_LOADER.load()) .dictionary(StandardDictionaries.ENGLISH_WIKIPEDIA_LOADER.load()) .keyboard(StandardKeyboards.QWERTY_LOADER.load()) .build(); // Compare results String password = "sunshine"; Strength defaultResult = defaultZxcvbn.measure(password); System.out.println("Default score: " + defaultResult.getScore()); Strength minimalResult = minimalZxcvbn.measure(password); System.out.println("Minimal score: " + minimalResult.getScore()); } } ``` -------------------------------- ### Customize Dictionaries and Keyboards from Classpath Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Build a Zxcvbn instance with custom dictionaries and keyboards loaded from resources on the Java classpath using ZxcvbnBuilder. ```java Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionary(new DictionaryLoader("us_tv_and_film", new ClasspathResource("/com/nulabinc/zxcvbn/matchers/dictionarys/us_tv_and_film.txt")).load()) .keyboard(new SlantedKeyboardLoader("qwerty", new ClasspathResource("/com/nulabinc/zxcvbn/matchers/keyboards/qwerty.txt")).load()) .keyboard(new AlignedKeyboardLoader("keypad", new ClasspathResource("/com/nulabinc/zxcvbn/matchers/keyboards/keypad.txt")).load()) .build(); ``` -------------------------------- ### Load Custom Dictionary and Keyboard Resources Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Use this snippet to load custom dictionary and keyboard files from the file system. Ensure the `MyResourceFromFile` class is defined and accessible. ```java File dictionaryFile = new File("/home/foo/dictionary.txt"); Resource myDictionaryResource = new MyResourceFromFile(dictionaryFile); File keyboardFile = new File("/home/bar/keyboard.txt"); Resource myKeyboardURLResource = new MyResourceFromFile(keyboardFile); Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionary(new DictionaryLoader("my_dictionary", myDictionaryResource).load()) .keyboard(new SlantedKeyboardLoader("my_keyboard", myKeyboardURLResource).load()) .build(); public class MyResourceFromFile implements Resource { private File file; public MyResourceFromFile(File file) { this.file = file; } @Override public InputStream getInputStream() throws IOException { return new FileInputStream(this.file); } } ``` -------------------------------- ### Customize Dictionaries and Keyboards via HTTP Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Implement the Resource interface to load custom dictionaries and keyboards from URLs via HTTP(s) when building a Zxcvbn instance. ```java URL dictionaryURL = new URL("https://example.com/foo/dictionary.txt"); Resource myDictionaryResource = new MyResourceOverHTTP(dictionaryURL); URL keyboardURL = new URL("https://example.com/bar/keyboard.txt"); Resource myKeyboardURLResource = new MyResourceOverHTTP(keyboardURL); Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionary(new DictionaryLoader("my_dictionary", myDictionaryResource).load()) .keyboard(new SlantedKeyboardLoader("my_keyboard", myKeyboardURLResource).load()) .build(); public class MyResourceOverHTTP implements Resource { private URL url; public MyResourceOverHTTP(URL url) { this.url = url; } @Override public InputStream getInputStream() throws IOException { HttpURLConnection conn = (HttpURLConnection) this.url.openConnection(); return conn.getInputStream(); } } ``` -------------------------------- ### Configure Custom Keyboard Layouts in zxcvbn4j Source: https://context7.com/nulab/zxcvbn4j/llms.txt Load standard and custom keyboard layouts, including JIS, Azerty, and phone keypads, to improve password pattern detection. Ensure custom keyboard layout files are correctly formatted and accessible via `ClasspathResource`. ```java import com.nulabinc.zxcvbn.Zxcvbn; import com.nulabinc.zxcvbn.ZxcvbnBuilder; import com.nulabinc.zxcvbn.StandardDictionaries; import com.nulabinc.zxcvbn.StandardKeyboards; import com.nulabinc.zxcvbn.io.ClasspathResource; import com.nulabinc.zxcvbn.matchers.SlantedKeyboardLoader; import com.nulabinc.zxcvbn.matchers.AlignedKeyboardLoader; public class CustomKeyboards { public static void main(String[] args) throws Exception { // Use standard QWERTY and add JIS (Japanese Industrial Standard) keyboard Zxcvbn zxcvbn = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboard(StandardKeyboards.QWERTY_LOADER.load()) .keyboard(StandardKeyboards.DVORAK_LOADER.load()) .keyboard(StandardKeyboards.JIS_LOADER.load()) // Japanese keyboard .keyboard(StandardKeyboards.KEYPAD_LOADER.load()) .keyboard(StandardKeyboards.MAC_KEYPAD_LOADER.load()) .build(); // Load custom slanted keyboard (standard keyboard with diagonal adjacency) // Use SlantedKeyboardLoader for QWERTY-style keyboards Zxcvbn withCustomSlanted = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboard(new SlantedKeyboardLoader( "azerty", new ClasspathResource("/keyboards/azerty.txt") ).load()) .keyboard(StandardKeyboards.KEYPAD_LOADER.load()) .build(); // Load custom aligned keyboard (keypad-style with vertical/horizontal adjacency) // Use AlignedKeyboardLoader for numeric keypads Zxcvbn withCustomAligned = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboard(StandardKeyboards.QWERTY_LOADER.load()) .keyboard(new AlignedKeyboardLoader( "phone_keypad", new ClasspathResource("/keyboards/phone_keypad.txt") ).load()) .build(); } } ``` ```text /* Slanted keyboard file format (qwerty.txt): `~ 1! 2@ 3# 4$ 5% 6^ 7& 8* 9( 0) -_ =+ qQ wW eE rR tT yY uU iI oO pP [{ ]} \| aA sS dD fF gG hH jJ kK lL ;: '" zZ xX cC vV bB nN mM ,< .> /? */ ``` ```text /* Aligned keyboard file format (keypad.txt): / * - 7 8 9 + 4 5 6 1 2 3 0 . */ ``` -------------------------------- ### Accessing Standard Dictionaries in Zxcvbn4j Source: https://context7.com/nulab/zxcvbn4j/llms.txt Shows how to access and load various built-in dictionaries used by Zxcvbn for password analysis. These include common passwords, Wikipedia words, and name databases. Dictionaries can be loaded individually or all at once. ```java import com.nulabinc.zxcvbn.StandardDictionaries; import com.nulabinc.zxcvbn.matchers.Dictionary; import java.util.List; public class StandardDictionariesReference { public static void main(String[] args) throws Exception { // Available dictionary loaders and their constants System.out.println("Available dictionaries:"); System.out.println("- PASSWORDS: " + StandardDictionaries.PASSWORDS); System.out.println("- ENGLISH_WIKIPEDIA: " + StandardDictionaries.ENGLISH_WIKIPEDIA); System.out.println("- US_TV_AND_FILM: " + StandardDictionaries.US_TV_AND_FILM); System.out.println("- SURNAMES: " + StandardDictionaries.SURNAMES); System.out.println("- MALE_NAMES: " + StandardDictionaries.MALE_NAMES); System.out.println("- FEMALE_NAMES: " + StandardDictionaries.FEMALE_NAMES); // Load individual dictionaries Dictionary passwords = StandardDictionaries.PASSWORDS_LOADER.load(); Dictionary wikipedia = StandardDictionaries.ENGLISH_WIKIPEDIA_LOADER.load(); Dictionary tvFilm = StandardDictionaries.US_TV_AND_FILM_LOADER.load(); Dictionary surnames = StandardDictionaries.SURNAMES_LOADER.load(); Dictionary maleNames = StandardDictionaries.MALE_NAMES_LOADER.load(); Dictionary femaleNames = StandardDictionaries.FEMALE_NAMES_LOADER.load(); // Load all dictionaries at once List allDictionaries = StandardDictionaries.loadAllDictionaries(); System.out.println("\nTotal dictionaries loaded: " + allDictionaries.size()); } } ``` -------------------------------- ### Basic Password Strength Measurement Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Instantiate Zxcvbn and measure the strength of a given password. This is the most straightforward way to use the library. ```java Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("This is password"); ``` -------------------------------- ### Multi-Locale Feedback Support in Java Source: https://context7.com/nulab/zxcvbn4j/llms.txt Demonstrates how to create a Feedback object that supports multiple locales for password strength feedback messages. This is useful for internationalized applications. ```java import com.nulabinc.zxcvbn.Feedback; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; public class MultiLocaleSupport { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("qwerty123"); // Prepare multiple locale bundles Map messages = new HashMap<>(); messages.put(Locale.JAPANESE, ResourceBundle.getBundle( "com/nulabinc/zxcvbn/messages", Locale.JAPANESE)); messages.put(Locale.GERMAN, ResourceBundle.getBundle( "com/nulabinc/zxcvbn/messages", Locale.GERMAN)); messages.put(Locale.FRENCH, ResourceBundle.getBundle( "com/nulabinc/zxcvbn/messages", Locale.FRENCH)); messages.put(Locale.ITALIAN, ResourceBundle.getBundle( "com/nulabinc/zxcvbn/messages", Locale.ITALIAN)); // Create feedback with multiple locale support Feedback feedback = strength.getFeedback(); Feedback multiLocaleFeedback = feedback.replaceResourceBundle(messages); // Get warnings in different languages System.out.println("Japanese: " + multiLocaleFeedback.getWarning(Locale.JAPANESE)); System.out.println("German: " + multiLocaleFeedback.getWarning(Locale.GERMAN)); System.out.println("French: " + multiLocaleFeedback.getWarning(Locale.FRENCH)); System.out.println("Italian: " + multiLocaleFeedback.getWarning(Locale.ITALIAN)); // Falls back to default for unsupported locales System.out.println("Spanish: " + multiLocaleFeedback.getWarning(new Locale("es"))); } } ``` -------------------------------- ### Localize Password Feedback with ResourceBundle Source: https://context7.com/nulab/zxcvbn4j/llms.txt Create a localized Feedback object using Feedback.withResourceBundle(ResourceBundle messages). This allows displaying warnings and suggestions in different languages by providing a custom ResourceBundle. ```java import com.nulabinc.zxcvbn.Feedback; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import java.util.Locale; import java.util.ResourceBundle; public class LocalizedFeedback { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("password123"); // Get default (English) feedback Feedback englishFeedback = strength.getFeedback(); System.out.println("English warning: " + englishFeedback.getWarning()); // Output: "This is a very common password." // Get Japanese feedback using built-in messages Feedback japaneseFeedback = strength.getFeedback(); System.out.println("Japanese warning: " + japaneseFeedback.getWarning(Locale.JAPANESE)); // Get German feedback System.out.println("German warning: " + englishFeedback.getWarning(Locale.GERMAN)); // Use custom ResourceBundle for localization ResourceBundle customBundle = ResourceBundle.getBundle( "com/nulabinc/zxcvbn/messages", Locale.FRENCH ); Feedback frenchFeedback = englishFeedback.withResourceBundle(customBundle); System.out.println("French warning: " + frenchFeedback.getWarning()); System.out.println("French suggestions: " + frenchFeedback.getSuggestions()); } } ``` -------------------------------- ### Load Custom Dictionary from Classpath Source: https://context7.com/nulab/zxcvbn4j/llms.txt Load a custom dictionary file from the classpath using ZxcvbnBuilder and a ClasspathResource. This is useful for including domain-specific terms. ```java import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import com.nulabinc.zxcvbn.ZxcvbnBuilder; import com.nulabinc.zxcvbn.StandardDictionaries; import com.nulabinc.zxcvbn.StandardKeyboards; import com.nulabinc.zxcvbn.io.ClasspathResource; import com.nulabinc.zxcvbn.io.Resource; import com.nulabinc.zxcvbn.matchers.DictionaryLoader; import java.io.*; public class CustomDictionaries { public static void main(String[] args) throws Exception { // Load dictionary from classpath Zxcvbn zxcvbnWithClasspath = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .dictionary(new DictionaryLoader( "company_terms", new ClasspathResource("/dictionaries/company_terms.txt") ).load()) .build(); // Load dictionary from filesystem Resource fileResource = new Resource() { @Override public InputStream getInputStream() throws IOException { return new FileInputStream("/path/to/custom_dictionary.txt"); } }; Zxcvbn zxcvbnWithFile = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .dictionary(new DictionaryLoader("custom", fileResource).load()) .build(); // Load dictionary from HTTP Resource httpResource = new Resource() { @Override public InputStream getInputStream() throws IOException { java.net.URL url = new java.net.URL("https://example.com/dictionary.txt"); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection(); return conn.getInputStream(); } }; Zxcvbn zxcvbnWithHttp = new ZxcvbnBuilder() .dictionaries(StandardDictionaries.loadAllDictionaries()) .keyboards(StandardKeyboards.loadAllKeyboards()) .dictionary(new DictionaryLoader("remote", httpResource).load()) .build(); } } /* Dictionary file format (company_terms.txt): acme acmecorp widgetpro superwidget mycompany ourproduct */ ``` -------------------------------- ### Feedback.withResourceBundle(ResourceBundle messages) Source: https://context7.com/nulab/zxcvbn4j/llms.txt Creates a localized Feedback object using a custom ResourceBundle for translations. This allows displaying warnings and suggestions in the user's preferred language. ```APIDOC ## Feedback.withResourceBundle(ResourceBundle messages) ### Description Creates a localized Feedback object using a custom ResourceBundle for translations. This allows displaying warnings and suggestions in the user's preferred language. ### Method ```java Feedback.withResourceBundle(ResourceBundle messages) ``` ### Parameters #### Request Body - **messages** (ResourceBundle) - Required - A ResourceBundle object containing localized strings for feedback messages. ### Request Example ```java ResourceBundle customBundle = ResourceBundle.getBundle("com/nulabinc/zxcvbn/messages", Locale.FRENCH); Feedback frenchFeedback = englishFeedback.withResourceBundle(customBundle); ``` ### Response #### Success Response (Localized Feedback Object) - **warning** (string) - A localized warning message. - **suggestions** (list of strings) - A list of localized suggestions. #### Response Example ```json { "warning": "Ce mot de passe est très courant.", "suggestions": ["Ajoutez un ou deux mots supplémentaires. Les mots peu courants sont meilleurs."] } ``` ``` -------------------------------- ### Replace Resource Bundles for Multiple Locales Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Replace default feedback messages with custom bundles for multiple locales. This allows for dynamic localization based on a map of locales to resource bundles. ```java Strength strength = zxcvbn.measure(password); Feedback feedback = strength.getFeedback(); Map messages = new HashMap<>(); messages.put(Locale.JAPANESE, ResourceBundle.getBundle("This is bundle name", Locale.JAPANESE)); messages.put(Locale.ITALIAN, ResourceBundle.getBundle("This is bundle name", Locale.ITALIAN)); Feedback replacedFeedback = feedback.replaceResourceBundle(messages); ``` -------------------------------- ### Strength Properties Explained Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Illustrates the various properties of the 'Strength' object returned by the zxcvbn measure function, including guesses, crack times, score, feedback, and calculation time. ```plaintext # estimated guesses needed to crack password strength.guesses # order of magnitude of strength.guesses strength.guessesLog10 # dictionary of back-of-the-envelope crack time # estimations, in seconds, based on a few scenarios strength.crackTimeSeconds { # online attack on a service that ratelimits password auth attempts. onlineThrottling100PerHour # online attack on a service that doesn't ratelimit, # or where an attacker has outsmarted ratelimiting. onlineNoThrottling10PerSecond # offline attack. assumes multiple attackers, # proper user-unique salting, and a slow hash function # w/ moderate work factor, such as bcrypt, scrypt, PBKDF2. offlineSlowHashing1e4PerSecond # offline attack with user-unique salting but a fast hash # function like SHA-1, SHA-256 or MD5. A wide range of # reasonable numbers anywhere from one billion - one trillion # guesses per second, depending on number of cores and machines. # ballparking at 10B/sec. offlineFastHashing1e10PerSecond } # same keys as result.crack_time_seconds, # with friendlier display string values: # "less than a second", "3 hours", "centuries", etc. strength.crackTimeDisplay # Integer from 0-4 (useful for implementing a strength bar) # 0 Weak (guesses < 10^3 + 5) # 1 Fair (guesses < 10^6 + 5) # 2 Good (guesses < 10^8 + 5) # 3 Strong (guesses < 10^10 + 5) # 4 Very strong (guesses >= 10^10 + 5) strength.score # verbal feedback to help choose better passwords. set when score <= 2. strength.feedback { # explains what's wrong, eg. 'this is a top-10 common password'. # not always set -- sometimes an empty string warning # a possibly-empty list of suggestions to help choose a less # guessable password. eg. 'Add another word or two' suggestions } # the list of patterns that zxcvbn based the guess calculation on. strength.sequence # how long it took zxcvbn to calculate an answer, in milliseconds. strength.calc_time ``` -------------------------------- ### Strength.getCrackTimesDisplay() Source: https://context7.com/nulab/zxcvbn4j/llms.txt Provides human-readable crack time estimates suitable for end-user display. ```APIDOC ## Strength.getCrackTimesDisplay() ### Description Returns human-readable crack time estimates as formatted strings (e.g., "3 hours", "centuries", "less than a second") suitable for displaying to end users. ### Method `getCrackTimesDisplay()` ### Parameters None ### Response - **onlineThrottling100perHour** (string) - Human-readable estimate for online attacks with 100 attempts per hour. - **onlineNoThrottling10perSecond** (string) - Human-readable estimate for online attacks with 10 attempts per second. - **offlineSlowHashing1e4perSecond** (string) - Human-readable estimate for offline attacks with slow hashing (10,000 attempts/second). - **offlineFastHashing1e10PerSecond** (string) - Human-readable estimate for offline attacks with fast hashing (10 billion attempts/second). ### Request Example ```java import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("Summer2024"); AttackTimes.CrackTimesDisplay display = strength.getCrackTimesDisplay(); System.out.println("Online (throttled): " + display.getOnlineThrottling100perHour()); ``` ### Response Example ```json { "onlineThrottling100perHour": "4 days", "onlineNoThrottling10perSecond": "17 minutes", "offlineSlowHashing1e4perSecond": "less than a second", "offlineFastHashing1e10PerSecond": "less than a second" } ``` ``` -------------------------------- ### Strength.getFeedback() Source: https://context7.com/nulab/zxcvbn4j/llms.txt Retrieves feedback for a given password's strength. Feedback is provided only when the password score is 2 or below, offering a warning and suggestions for improvement. ```APIDOC ## Strength.getFeedback() ### Description Returns a Feedback object containing a warning message explaining what's wrong with the password and a list of suggestions for creating a stronger password. Feedback is only provided when the score is 2 or below. ### Method ```java Strength.getFeedback() ``` ### Parameters None ### Request Example ```java Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("password123"); Feedback feedback = strength.getFeedback(); ``` ### Response #### Success Response (Feedback Object) - **warning** (string) - A message explaining the password weakness. - **suggestions** (list of strings) - A list of actionable suggestions to improve password strength. #### Response Example ```json { "warning": "This is a very common password.", "suggestions": ["Add another word or two. Uncommon words are better."] } ``` ``` -------------------------------- ### Feedback.replaceResourceBundle Source: https://context7.com/nulab/zxcvbn4j/llms.txt Allows replacing the default ResourceBundle with custom ones for multi-language feedback support. This is useful for applications that need to provide password strength feedback in various languages. ```APIDOC ## Feedback.replaceResourceBundle(Map messages) ### Description Creates a Feedback object that dynamically selects the appropriate ResourceBundle based on locale. Useful for applications supporting multiple languages simultaneously. ### Method `replaceResourceBundle` ### Parameters #### Request Body - **messages** (Map) - Required - A map where keys are Locale objects and values are ResourceBundle objects for each language. ### Request Example ```java Map messages = new HashMap<>(); messages.put(Locale.JAPANESE, ResourceBundle.getBundle("com/nulabinc/zxcvbn/messages", Locale.JAPANESE)); messages.put(Locale.GERMAN, ResourceBundle.getBundle("com/nulabinc/zxcvbn/messages", Locale.GERMAN)); // ... add other locales as needed Feedback multiLocaleFeedback = feedback.replaceResourceBundle(messages); ``` ### Response #### Success Response (200) - **Feedback** (Feedback) - A new Feedback object configured with the provided resource bundles. #### Response Example ```java // The method returns a Feedback object, no direct JSON response. // Example of using the returned object: System.out.println(multiLocaleFeedback.getWarning(Locale.JAPANESE)); ``` ``` -------------------------------- ### Localize Feedback Messages by Locale Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Localize feedback messages for a specific locale using `ResourceBundle`. Ensure the property file exists and is correctly named. ```java // Get the Strength instance. Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("This is password"); // Get the ResourceBundle based on the name and locale of the property file(※). ResourceBundle resourceBundle = ResourceBundle.getBundle("This is bundle name", Locale.JAPAN); // Feedback to pass the ResourceBundle. And to generate a localized Feedback. Feedback feedback = strength.getFeedback(); Feedback localizedFeedback = feedback.withResourceBundle(resourceBundle); // getSuggestions() and getWarning() returns localized feedback message. List localizedSuggestions = localizedFeedback.getSuggestions(); String localizedWarning = localizedFeedback.getWarning(); ``` -------------------------------- ### Gradle Dependency for zxcvbn4j Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Add this dependency to your Gradle project to include the zxcvbn4j library for password strength estimation. ```gradle compile 'com.nulab-inc:zxcvbn:1.9.0' ``` -------------------------------- ### Basic Password Strength Measurement Source: https://context7.com/nulab/zxcvbn4j/llms.txt This section details how to measure the strength of a password using the primary `measure` method, which returns a `Strength` object containing score, crack time estimates, and feedback. ```APIDOC ## Zxcvbn.measure(CharSequence password) ### Description Analyzes a password and returns a Strength object containing the estimated number of guesses, crack time estimates, a 0-4 score, and feedback for improvement. This is the primary method for password strength evaluation. ### Method ```java Zxcvbn.measure(CharSequence password) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; public class BasicUsage { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("correcthorsebatterystaple"); int score = strength.getScore(); System.out.println("Score: " + score); double guesses = strength.getGuesses(); System.out.println("Guesses: " + guesses); double guessesLog10 = strength.getGuessesLog10(); System.out.println("Guesses Log10: " + guessesLog10); long calcTime = strength.getCalcTime(); System.out.println("Calculation time: " + calcTime + " ns"); } } ``` ### Response #### Success Response (200) - **score** (int) - A score from 0 (weak) to 4 (very strong). - **guesses** (double) - The estimated number of guesses required to crack the password. - **guessesLog10** (double) - The base-10 logarithm of the estimated guesses. - **calcTime** (long) - The time taken for calculation in nanoseconds. #### Response Example ```json { "score": 4, "guesses": 4.4511222251212E13, "guessesLog10": 13.65, "calcTime": 123456789 } ``` ``` ```APIDOC ## Zxcvbn.measure(CharSequence password, List sanitizedInputs) ### Description Measures password strength while penalizing passwords that contain user-specific information like usernames, email addresses, or company names. The sanitized inputs are treated as easily guessable dictionary words. ### Method ```java Zxcvbn.measure(CharSequence password, List sanitizedInputs) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; import java.util.Arrays; import java.util.List; public class CustomDictionaryUsage { public static void main(String[] args) { Zxcvbn zxcvbn = new Zxcvbn(); List sanitizedInputs = Arrays.asList("john", "doe", "johndoe", "john.doe@acme.com", "acme", "acmecorp"); Strength weakStrength = zxcvbn.measure("johndoe2024", sanitizedInputs); System.out.println("Score with user info: " + weakStrength.getScore()); Strength normalStrength = zxcvbn.measure("johndoe2024"); System.out.println("Score without context: " + normalStrength.getScore()); Strength strongStrength = zxcvbn.measure("xK9#mP2$vL5@nQ8", sanitizedInputs); System.out.println("Strong password score: " + strongStrength.getScore()); } } ``` ### Response #### Success Response (200) - **score** (int) - A score from 0 (weak) to 4 (very strong), potentially lower if user-specific inputs are present. - **guesses** (double) - The estimated number of guesses required to crack the password. - **guessesLog10** (double) - The base-10 logarithm of the estimated guesses. - **calcTime** (long) - The time taken for calculation in nanoseconds. #### Response Example ```json { "score": 0, "guesses": 10000, "guessesLog10": 4.0, "calcTime": 50000000 } ``` ``` -------------------------------- ### Password Strength Measurement with Custom Dictionary Source: https://github.com/nulab/zxcvbn4j/blob/main/README.md Measure password strength while providing a custom list of keywords to be considered. This can improve accuracy for specific domains. ```java List sanitizedInputs = new ArrayList(); sanitizedInputs.add("nulab"); sanitizedInputs.add("backlog"); sanitizedInputs.add("cacoo"); sanitizedInputs.add("typetalk"); Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("This is password", sanitizedInputs); ``` -------------------------------- ### Strength.getCrackTimeSeconds() Source: https://context7.com/nulab/zxcvbn4j/llms.txt Retrieves estimated crack times in seconds for various attack scenarios. ```APIDOC ## Strength.getCrackTimeSeconds() ### Description Returns crack time estimates in seconds for four different attack scenarios: online throttled (100 attempts/hour), online unthrottled (10 attempts/second), offline slow hashing (10,000 attempts/second with bcrypt/scrypt), and offline fast hashing (10 billion attempts/second with SHA-1/MD5). ### Method `getCrackTimeSeconds()` ### Parameters None ### Response - **onlineThrottling100perHour** (double) - Estimated crack time in seconds for online attacks with 100 attempts per hour. - **onlineNoThrottling10perSecond** (double) - Estimated crack time in seconds for online attacks with 10 attempts per second. - **offlineSlowHashing1e4perSecond** (double) - Estimated crack time in seconds for offline attacks with slow hashing (10,000 attempts/second). - **offlineFastHashing1e10PerSecond** (double) - Estimated crack time in seconds for offline attacks with fast hashing (10 billion attempts/second). ### Request Example ```java import com.nulabinc.zxcvbn.AttackTimes; import com.nulabinc.zxcvbn.Strength; import com.nulabinc.zxcvbn.Zxcvbn; Zxcvbn zxcvbn = new Zxcvbn(); Strength strength = zxcvbn.measure("Summer2024!"); AttackTimes.CrackTimeSeconds crackTimeSeconds = strength.getCrackTimeSeconds(); double onlineThrottled = crackTimeSeconds.getOnlineThrottling100perHour(); System.out.println("Online throttled: " + onlineThrottled + " seconds"); ``` ### Response Example ```json { "onlineThrottling100perHour": 360000.0, "onlineNoThrottling10perSecond": 1000.0, "offlineSlowHashing1e4perSecond": 1.0, "offlineFastHashing1e10PerSecond": 0.000001 } ``` ```