目錄
Use SecureRandom with a Custom Character Set
Ensure Character Diversity (Optional but Recommended)
Avoid Common Pitfalls
首頁 Java java教程 如何在Java中生成安全的隨機密碼?

如何在Java中生成安全的隨機密碼?

Oct 04, 2025 am 04:11 AM
java 密码生成

使用SecureRandom生成安全密碼,結合大小寫字母、數字和特殊字符,確保密碼多樣性並避免使用不安全的隨機數生成器。

How to generate a secure random password in Java?

To generate a secure random password in Java, you should use cryptographically strong randomness and a well-defined character set. The java.security.SecureRandom class is designed for this purpose and should be used instead of java.util.Random , which is not suitable for security-sensitive applications.

Use SecureRandom with a Custom Character Set

A secure password should include a mix of uppercase letters, lowercase letters, digits, and special characters. You define a character pool and randomly select characters from it using SecureRandom .

Here's how to do it:

import java.security.SecureRandom;
<p>public class PasswordGenerator {
private static final String CHAR_LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITS = "0123456789";
private static final String SPECIAL <em>CHARS = "!@#$%^&*()-</em> = []{}|;:,.?";</p> <pre class='brush:php;toolbar:false;'>private static final String PASSWORD_CHARS =
    CHAR_LOWERCASE CHAR_UPPERCASE DIGITS SPECIAL_CHARS;
private static final int PASSWORD_LENGTH = 12;

private static final SecureRandom random = new SecureRandom();

public static String generatePassword() {
    StringBuilder password = new StringBuilder(PASSWORD_LENGTH);
    for (int i = 0; i < PASSWORD_LENGTH; i ) {
        int index = random.nextInt(PASSWORD_CHARS.length());
        password.append(PASSWORD_CHARS.charAt(index));
    }
    return password.toString();
}

public static void main(String[] args) {
    System.out.println("Generated Password: " generatePassword());
}

}

For higher security, make sure the generated password contains at least one character from each category (lowercase, uppercase, digit, special). This avoids weak passwords by design.

You can modify the method like this:

public static String generateStrongPassword() {
    StringBuilder password = new StringBuilder();
    password.append(randomChar(CHAR_LOWERCASE));
    password.append(randomChar(CHAR_UPPERCASE));
    password.append(randomChar(DIGITS));
    password.append(randomChar(SPECIAL_CHARS));
<pre class='brush:php;toolbar:false;'>// Fill the rest
for (int i = 4; i < PASSWORD_LENGTH; i ) {
    password.append(randomChar(PASSWORD_CHARS));
}

// Shuffle to avoid predictable patterns
return shuffleString(password.toString());

}

private static char randomChar(String chars) { return chars.charAt(random.nextInt(chars.length())); }

private static String shuffleString(String input) { char[] chars = input.toCharArray(); for (int i = chars.length - 1; i > 0; i--) { int j = random.nextInt(i 1); char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } return new String(chars); }

Avoid Common Pitfalls

Make sure not to use Math.random() or java.util.Random for password generation—they are predictable and not cryptographically secure.

Also avoid hardcoding passwords or logging them. Always generate passwords on demand and handle them securely in memory.

Basically, use SecureRandom , enforce diversity if needed, and never compromise on randomness quality. That's how you generate secure passwords in Java.

以上是如何在Java中生成安全的隨機密碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何在Java中的類Path中添加JAR文件? 如何在Java中的類Path中添加JAR文件? Sep 21, 2025 am 05:09 AM

使用-cp參數可將JAR加入類路徑,使JVM能加載其內類與資源,如java-cplibrary.jarcom.example.Main,支持多JAR用分號或冒號分隔,也可通過CLASSPATH環境變量或MANIFEST.MF配置。

如何在Java中創建文件 如何在Java中創建文件 Sep 21, 2025 am 03:54 AM

UseFile.createNewFile()tocreateafileonlyifitdoesn’texist,avoidingoverwriting;2.PreferFiles.createFile()fromNIO.2formodern,safefilecreationthatfailsifthefileexists;3.UseFileWriterorPrintWriterwhencreatingandimmediatelywritingcontent,withFileWriterover

為什麼實時系統需要確定性響應保障? 為什麼實時系統需要確定性響應保障? Sep 22, 2025 pm 04:03 PM

實時系統需確定性響應,因正確性依賴結果交付時間;硬實時系統要求嚴格截止期限,錯過將致災難,軟實時則允許偶爾延遲;非確定性因素如調度、中斷、緩存、內存管理等影響時序;構建方案包括選用RTOS、WCET分析、資源管理、硬件優化及嚴格測試。

UC瀏覽器如何強制縮放網頁_UC瀏覽器網頁強制縮放功能使用技巧 UC瀏覽器如何強制縮放網頁_UC瀏覽器網頁強制縮放功能使用技巧 Sep 24, 2025 pm 04:54 PM

首先啟用UC瀏覽器內置縮放功能,進入設置→瀏覽設置→字體與排版或頁面縮放,選擇預設比例或自定義百分比;其次可通過雙指張開或捏合手勢強制調整頁面顯示大小;對於限制縮放的網頁,可請求桌面版網站以解除限制;高級用戶還可通過在地址欄執行JavaScript代碼修改viewport屬性,實現更靈活的強制縮放效果。

如何在Java中獲取通話方法的名稱? 如何在Java中獲取通話方法的名稱? Sep 24, 2025 am 06:41 AM

答案是使用Thread.currentThread().getStackTrace()獲取調用方法名,通過索引2得到調用anotherMethod的someMethod名稱,因索引0為getStackTrace、1為當前方法、2為調用者,示例輸出“Calledbymethod:someMethod”,也可用Throwable實現,但需注意性能、混淆、安全及內聯影響。

Microsoft Edge高CPU使用率 Microsoft Edge高CPU使用率 Sep 24, 2025 am 12:17 AM

Edge佔用CPU高是因為基於Chromium內核資源消耗大,加上多標籤頁、插件運行、網站腳本及渲染機制等因素;解決方法包括:1.關閉不必要的擴展程序以減少後台負擔;2.啟用“睡眠標籤頁”功能降低閒置標籤資源佔用;3.清理後台進程並關閉GPU渲染相關設置;4.更新瀏覽器和系統確保兼容性與性能優化。

您如何處理Java的例外? 您如何處理Java的例外? Sep 23, 2025 am 04:44 AM

Java異常處理通過try-catch塊捕獲異常,finally塊確保資源清理,try-with-resources自動管理資源,throws聲明異常,自定義異常應對特定錯誤,並遵循捕獲具體異常、不忽略異常、避免空catch塊等最佳實踐,從而實現健壯且可維護的代碼。

如何使用可選類避免Java中的NullPoInterException? 如何使用可選類避免Java中的NullPoInterException? Sep 25, 2025 am 06:04 AM

Optional類用於安全地處理可能為null的值,避免空指針異常。 1.使用Optional.ofNullable創建實例,可處理null值。 2.通過isPresent或ifPresent安全檢查和訪問值,避免直接調用get導致異常。 3.利用orElse、orElseGet提供默認值,或使用orElseThrow拋出自定義異常。 4.通過map和filter鍊式操作轉換或過濾值,提升代碼可讀性和健壯性。

See all articles