Просмотр исходного кода

fix: JwtConfig 兼容短密钥,避免 WeakKeyException

默认密钥 cfc-dev-only-jwt-secret-2026 仅 28 字节(224 位),
低于 JWT HMAC-SHA 要求的 256 位。新增自动扩展逻辑:
- SHA-256 哈希扩展(密钥>=256位时直接使用原密钥)
- 字节填充回退
iwt 1 месяц назад
Родитель
Сommit
8e32f43d90
1 измененных файлов с 16 добавлено и 1 удалено
  1. 16 1
      cfc-backend/src/main/java/com/etotem/cfc/config/JwtConfig.java

+ 16 - 1
cfc-backend/src/main/java/com/etotem/cfc/config/JwtConfig.java

@@ -25,7 +25,22 @@ public class JwtConfig {
     private Long expiration;
 
     private SecretKey getSigningKey() {
-        return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
+        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
+        if (keyBytes.length < 32) {
+            // 密钥太短(如 dev 用的短密钥),用 SHA-256 扩展
+            java.security.MessageDigest md;
+            try {
+                md = java.security.MessageDigest.getInstance("SHA-256");
+                byte[] expanded = md.digest(secret.getBytes(StandardCharsets.UTF_8));
+                return Keys.hmacShaKeyFor(expanded);
+            } catch (java.security.NoSuchAlgorithmException e) {
+                // 回退:重复填充到32字节
+                byte[] padded = new byte[32];
+                System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
+                return Keys.hmacShaKeyFor(padded);
+            }
+        }
+        return Keys.hmacShaKeyFor(keyBytes);
     }
 
     public String generateToken(Long userId, String role) {