signed cookie
値を書き換えられた場合に、書き換えを検知するための仕組み。
サーバー内のシークレットキーを使ってハッシュ値を生成し、元の値に付けて(サインして)ブラウザに渡しておく
ブラウザから送られてきたcookieの値が改竄されていないか、サインが一致するか再度ハッシュ値を計算して比較する
簡単な例
signed-session.py>>> from hashlib import md5
>>> secret = 'naisho'
>>> sessionid = 'session-123456'
>>> sign = md5((secret+sessionid).encode()).hexdigest()
>>> signed_sessionid = sessionid + '.' + sign
>>> signed_sessionid
'session-123456.f23128c5492a1e18a351db634d042462'
signed_sessionid
に含まれるsessionidを書き換えても、 secret
を知らないとサイン部分の値は生成できない
secret
のような固定のキーを使ってハッシュすることをkeyed hashingと言う
> 15.1.4.3.3. Keyed hashing
> Keyed hashing can be used for authentication as a faster and simpler replacement for Hash-based message authentication code (HMAC). BLAKE2 can be securely used in prefix-MAC mode thanks to the indifferentiability property inherited from BLAKE.
コード
keyed_hashing.py>>> from hashlib import blake2b
>>> secret = 'naisho'
>>> sessionid = 'session-123456'
>>> h = blake2b(key=secret.encode(), digest_size=8)
>>> h.update(sessionid.encode())
>>> sign = h.hexdigest()
>>> signed_sessionid = sessionid + '.' + sign
>>> signed_sessionid
'session-123456.e63aeab4d83218fd'