You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BCryptPasswordEncoder密码长度是否超72字符?能否用于Web应用?

Spring Security BCryptPasswordEncoder: 72-Character Password Limit & Web App Suitability

Great question — let's unpack this thoroughly, since it's a common point of confusion with bcrypt and Spring Security.

The Core Fact: Bcrypt's Native 72-Character Limit

First, let's clarify the root cause: the bcrypt algorithm itself has a hard limit of 72 characters for password inputs. Any characters beyond the 72nd are silently truncated before hashing. This isn't a flaw in Spring Security's implementation—it's a fundamental design choice of the bcrypt algorithm itself.

Why Spring Security's BCryptPasswordEncoder Doesn't Warn You

When you tested with a 1000-character password and saw no warnings, that's expected behavior. The BCryptPasswordEncoder in Spring Security doesn't log warnings or throw exceptions for passwords exceeding 72 characters by default. It simply delegates to the underlying bcrypt implementation (typically the BCrypt class from the org.springframework.security.crypto.bcrypt package), which handles the truncation quietly.

This lack of explicit documentation in the JavaDoc can be confusing, but it's because the limit is tied to the algorithm, not the encoder wrapper itself.

Can You Use It for Web Apps If Passwords Exceed 72 Characters?

It depends on your application's requirements:

  • If you accept truncated password validation: You can use it, but you should communicate this limitation to users. For example, add a note on your registration/login pages stating that passwords longer than 72 characters will have any extra characters ignored. This prevents users from mistakenly assuming their full long password is being used for security.
  • If you need full validation of long passwords: Bcrypt isn't the right choice here. Instead, consider using password hashing algorithms that support arbitrary-length passwords, like:
    • Argon2PasswordEncoder (Spring Security 5.3+)
    • Pbkdf2PasswordEncoder
      Both of these are fully supported by Spring Security and don't have the 72-character restriction.

Quick Test to Confirm the Truncation

If you want to verify this behavior yourself, you can run a simple test:

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String longPassword = "a".repeat(100);
String hash = encoder.encode(longPassword);

// Test with the first 72 characters
boolean matchesShort = encoder.matches("a".repeat(72), hash);
// Test with the full 100 characters
boolean matchesLong = encoder.matches(longPassword, hash);

// Both will return true, proving truncation happens
System.out.println(matchesShort); // true
System.out.println(matchesLong); // true

内容的提问来源于stack exchange,提问作者user2652379

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:14:35