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

Python实现Digest Access Authentication时response结果不符问题

问题:摘要认证Response值与示例不符

我参考维基百科的摘要认证示例操作,已经算出正确的HA1和HA2,但生成的response和教程结果不一致,代码如下:

password =  "Circle Of Life"

username="Mufasa"
realm="testrealm@host.com"
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"
uri="/dir/index.html"
qop="auth"
nc="00000001"
cnonce="0a4f113b"
response="6629fae49393a05397450978507c4ef1"
opaque="5ccc069c403ebaf9f0171e9517f40e41"
import hashlib 
def getMD5(s):
    return hashlib.md5(s.encode()).hexdigest()
def get1(password):
    return (getMD5(username +":"+realm+":"+password))

hash1 =get1(password)
HA2 = getMD5("GET:"+uri)
print(hash1)
print(HA2)
print(getMD5(hash1 +":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+":"+HA2))
问题原因

生成response的拼接字符串里多了一个多余的冒号:hash1 +":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+":"+HA2,这里qop后面连续加了两个冒号,导致中间多了一个空值,不符合摘要认证的response计算规则。

正确的拼接格式应为:HA1:nonce:nc:cnonce:qop:HA2,不需要额外的冒号。

修正后的代码
password =  "Circle Of Life"

username="Mufasa"
realm="testrealm@host.com"
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"
uri="/dir/index.html"
qop="auth"
nc="00000001"
cnonce="0a4f113b"
response="6629fae49393a05397450978507c4ef1"
opaque="5ccc069c403ebaf9f0171e9517f40e41"
import hashlib 
def getMD5(s):
    return hashlib.md5(s.encode()).hexdigest()
def get1(password):
    return (getMD5(username +":"+realm+":"+password))

hash1 =get1(password)
HA2 = getMD5("GET:"+uri)
print(hash1)
print(HA2)
# 去掉多余的冒号
print(getMD5(hash1 +":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+HA2))

运行修正后的代码,就能得到示例中的正确response值:6629fae49393a05397450978507c4ef1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:33:31