fastapi: 报错:InsecureKeyLengthWarning: The HMAC key is 31 bytes long, which is below the minimum recommended length of 32 bytes for SHA256.

一,报错信息:

/data/python/fastapi/demo1/venv/lib/python3.10/site-packages/jwt/api_jwt.py:368: InsecureKeyLengthWarning: 
The HMAC key is 31 bytes long, which is below the minimum recommended length of 32 bytes for SHA256. See RFC 7518 Section 3.2.

 

二,原因

这个报错信息其实是一个警告(Warning),它的意思非常明确:你用于生成 JWT 的密钥(Secret Key)太短了。

在使用 HS256(基于 SHA-256 的 HMAC)算法签名 JWT 时,根据官方安全标准(RFC 7518),密钥的长度至少需要达到 32 字节(256 位)
而你当前使用的密钥只有 31 字节,这在加密学上被认为是不够安全的,容易受到暴力破解。

要解决这个问题,你只需要更换一个更长、更安全的密钥即可。

三,解决:

手动修改密码钥的长度即可,
或执行下面的命令随机生成:

$ python3 -c "import secrets; print(secrets.token_hex(32))"
febd5f4634e157486a4aea1bf279083e508b130b865d2c0364a8e441482625cc

 

posted @ 2026-06-12 10:54  刘宏缔的架构森林  阅读(17)  评论(0)    收藏  举报