Skip to content

Password Hashing و Signed Tokenها: bcrypt، Argon2، Salt و Pepper، HMAC-Signed URL، امضای JWT/PASETO ​

"We present two algorithms with adaptable cost--eksblowfish, a block cipher with a purposefully expensive key schedule, and bcrypt, a related hash function." — Niels Provos و David Mazières، A Future-Adaptable Password Scheme، USENIX ۱۹۹۹

خلاصه (Summary): گذرواژه‌ها باید به شکل hash کند، salt‌دار و دارای پارامترِ ذخیره‌شده نگه‌داری شوند؛ هر چیز دیگری که به بیرون می‌دهید (API key، لینک، session، token) یا hashِ یک رازِ تصادفی است یا با کلید امضا می‌شود، و تنها حرکت واقعی مهاجم حدس‌زدنِ آفلاین یا جعل امضاست. تمرکز (Focus): بایت‌ها و الگوریتم‌ها: bcrypt، Argon2id، scrypt، PBKDF2، salt، pepper، رشتهٔ PHC، مقایسهٔ constant-time، HMAC-signed URL و امضای JWT/PASETO با EdDSA، ES256، RS256 و HS256. هدف یادگیری (Learning goal): برای هر راز ابزار درست را انتخاب کنید، یک hash یا token را بایت‌به‌بایت بخوانید، هزینه را روی ماشین خودتان تنظیم کنید و حمله‌ها (کرک آفلاین، alg: none، key confusion، timing) را از علامتشان بشناسید.

این صفحه صاحب بایت‌ها و الگوریتم‌های ذخیرهٔ گذرواژه و امضای token است. خودِ جریان‌های ورود (ثبت‌نام، MFA، session، ایمیل بازیابی) در Authentication: Passwords, MFA & Sessions است و JWT به‌عنوان معماری (access در برابر refresh، revocation، gateway) در JWT Deep Dive. اجزای زیرین (HMAC، KDF، امضا، تصادفی‌بودن) در Cryptography Fundamentals، توابع hash در Checksums & Hashing، Base64url در Binary-to-Text Encoding و راهنمای API زبان Go در Hashing & Crypto in Go آمده است. کوکی و session در Web Sessions, Cookies & CORS، OAuth/OIDC در OAuth2, OIDC & SSO، رمزنگاری سطح دیتابیس در Encryption at Rest, in Transit & in Use و سیم در TLS in Practice است.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
جدولی برای هر نوع راز: چه ذخیره کنم و با چههمه‌چیز در یک دقیقه
چرا گذرواژه را رمز نمی‌کنیم و مهاجم کیستچرا وجود دارد
bcrypt، scrypt، Argon2 و PASETO از کجا آمدنداز کجا آمده
salt، pepper، work factor، bcrypt، Argon2id، scrypt، PBKDF2hash کردن گذرواژه، مفهوم به مفهوم
رشتهٔ $argon2id$v=19$m=65536,t=3,p=4$salt$hash بایت‌به‌بایتقالب رشتهٔ PHC
rehash هنگام ورود، constant-time compare، لیست نشتیاداره‌کردن یک password store
API key، توکن بازیابی، session IDhash کردن رازهای دیگر
HMAC، کوکی امضاشده، signed URL، URL::signedRouteمقدار و URL امضاشده با HMAC
بایت‌های JWT، HS256 در برابر RS256 و ES256 و EdDSA، alg: none، kid، JWKSامضای JWT
PASETO، Branca، Macaroons، JWEجایگزین‌های JWT
جدول هر ابزار و کتابخانه، پیام‌های خطای دقیقرفتار هر محصول، سازوکار
مهاجرت hashهای قدیمی، چرخش کلید، بازنشانی گذرواژهراه‌حل مسئله‌های کلاسیک
کدام الگوریتم برای کدام کارانتخاب
از مونولیت تا سیستم توزیع‌شده: کلید کجاستدر معماری
بازتولید همهٔ عددهای این صفحهآزمایشگاه
باورهای غلط، چکیده، واژه‌نامهبدفهمی‌ها، چکیده، واژه‌نامه

همه‌چیز در یک دقیقه ​

برای هر نوع راز چه در دیتابیس بگذارید.

SecretYou storeAlgorithmWhy
User password (low entropy, chosen by a human)PHC/bcrypt string: algorithm, parameters, salt, tagArgon2id (bcrypt if you must), slow and saltedThe attacker will guess offline, so every guess must be expensive
API key, personal access token (high entropy, 256 random bits)SHA-256 hex digest, plus a prefix/last-four for displayPlain SHA-256Nothing to guess; a slow hash only burns your CPU
Session ID, password-reset token, email-verification tokenSHA-256 digest of the random value, with an expiryPlain SHA-256Same as API keys; the DB leak must not be a login
Signed link (unsubscribe, download, magic login)Nothing: the signature travels in the URLHMAC-SHA256 over path + query + expiryServer stays stateless; tampering is detectable
Access token for other servicesNothing, or a revocation listJWT/PASETO signed with a private key (EdDSA, ES256)Any verifier with the public key can check it without calling you
Data you must read back (card number, OAuth refresh token)CiphertextEncryption (AES-GCM), not hashingHashing is one-way; see Cryptography Fundamentals

گذرواژه: تنظیمات پیشنهادی در یک نگاه.

AlgorithmMinimum from OWASPNotes
Argon2idm=19456 KiB (19 MiB), t=2, p=1 (equivalent options: m=47104,t=1; m=12288,t=3; m=9216,t=4; m=7168,t=5)First choice. RFC 9106 gives larger "uniformly safe" settings
scryptN=2^17, r=8, p=1If Argon2id is not available
bcryptwork factor (cost) 10 or more, password limit 72 bytesLegacy but still fine; Laravel default is 12
PBKDF2-HMAC-SHA256600,000 iterations or moreOnly when FIPS-140 compliance forces it

Token: کدام امضا.

NeedPickAvoid
One service signs and verifies its own tokensHS256 (HMAC) with a 32+ byte random key, or EdDSAWeak or human-chosen HMAC secrets
One issuer, many verifiers (microservices, JWKS)EdDSA (Ed25519) or ES256; verifiers hold only the public keyHS256 shared with every verifier
Compliance requires RSARS256 or PS256 with a 2048-bit or larger keyTrusting the alg header
You control both ends and want no algorithm field to attackPASETO v4.public / v4.localAccepting alg: none, mixing HMAC and RSA keys

سه کاری که همین امروز باید انجام دهید.

وضعیتاین کار را بکنید
گذرواژه ذخیره می‌کنیدArgon2id یا bcrypt از طریق hasher خودِ framework؛ هنگام verify پارامترها را از خودِ hash بخوانید؛ اگر ضعیف بود موقع ورود rehash کنید
token یا امضا را verify می‌کنیدبا تابع constant-time مقایسه کنید، فهرست الگوریتم‌ها را در کد ثابت کنید و هرگز از خودِ token نخوانید
token تصادفی صادر می‌کنیدفقط یک بار نشان دهید، digest مربوط به SHA-256 را ذخیره کنید و expiry بگذارید

چرا وجود دارد ​

دیتابیس دیر یا زود نشت می‌کند: SQL injection، backup دزدیده‌شده، ادمین ناراضی، bucket اشتباه‌تنظیم. مهم این است که مهاجم بعد از آن چه دارد. اگر گذرواژه‌ها خام باشند یا با کلیدی رمز شده باشند که کنارشان است، نشت یعنی تصاحبِ دسته‌جمعیِ حساب‌ها (و چون مردم گذرواژه را تکرار می‌کنند، تصاحب سایت‌های دیگر). اگر hashِ کند و salt‌دار باشند، مهاجم باید یکی‌یکی حدس بزند و هر حدس پول خرج می‌کند. Signed tokenها و URLها مسئلهٔ آینه‌ای را حل می‌کنند: چطور مقداری را به کسی بدهیم، هیچ نسخه‌ای نگه نداریم و بعداً بدانیم این مقدار از ماست و دست نخورده است؟

ChoiceWeaker, simplerStronger, costlier
Password storageOne SHA-256 pass, 1 microsecond per guessArgon2id, tens of milliseconds and tens of MiB per guess
Server costCheap loginsEvery login burns CPU and RAM; a login flood becomes a denial-of-service lever
Token verificationLook up a random ID in the databaseVerify a signature offline, but now revocation is hard
Signing keyOne shared HMAC secretPublic/private pair: more moving parts, safer distribution
Algorithm agilityLet the token say which algorithmFix the algorithm in code: less flexible, far fewer attacks

یک تصویر روزمره که در ادامه تکرار می‌شود. ذخیرهٔ گذرواژه مثل گاوصندوقی با شمارندهٔ کند است: گاوصندوق (hash) جوش‌خورده است، نمی‌شود ترکیب را از آن بیرون کشید و امتحان یک ترکیب به‌جای یک میلی‌ثانیه ده ثانیه طول می‌کشد. Salt شمارهٔ سریال متفاوت روی هر گاوصندوق است، پس باز کردن یکی چیزی دربارهٔ بقیه نمی‌گوید. Pepper کلید رازی است که در ساختمان دیگری نگه می‌دارید. لینک امضاشده مهر موم است: هر کس نامه را می‌خواند، ولی فقط صاحب انگشتر می‌تواند مهرِ مطابق بزند.

سه بدفهمیِ رایج، از همین اول.

MisunderstandingReality
"We encrypt passwords with AES, so they are safe."Encryption is reversible by design; whoever gets the key (and it is usually on the same server) gets every password. You never need to read a password back, so use a one-way function.
"SHA-256 with a salt is secure."The salt stops rainbow tables and cross-user reuse, but SHA-256 is built to be fast: a modern GPU does billions of guesses per second. The slowness is the security.
"A JWT is encrypted, so I can put the user's email and role in it."A signed JWT is only Base64url text. Anyone holding the token can read it; the signature only proves nobody changed it.

مدل مهاجم (Attacker model) ​

هر انتخاب طراحی پایین پاسخ به یکی از این مهاجم‌هاست. قبل از انتخاب پارامتر آن‌ها را نام ببرید.

AttackerCapabilityWhat stops them
Online guesserSends login requests, one guess per requestRate limits, lockouts, MFA (authentication chapter); not a hashing problem
Credential stufferReplays email/password pairs from other breachesBreach-list checks (HIBP), MFA, unique passwords
Offline crackerHas the hash column; tries billions of candidates on GPUsSlow, memory-hard hashes; per-user salts; long passwords
Rainbow-table userHas precomputed hash-to-password tablesA random salt per user makes every table useless
Database-only thiefSQL injection or backup, but not the app serverPepper held outside the database
App-server thiefReads environment and memory tooNothing local; HSM or remote KMS limits what leaks
Timing observerMeasures response time to learn how many bytes matchedConstant-time compare, equal work on all paths
Token forgerEdits a token or link to gain accessSignature verified with a key the forger lacks, pinned algorithm
Token thiefSteals a valid token (XSS, logs, proxy)Short expiry, HttpOnly cookies, TLS, rotation, revocation

اقتصادِ کرک آفلاین. هزینهٔ هر حدسِ مهاجم همان چیزی است که شما تنظیم می‌کنید. اگر هر حدس برای شما ۵۰ میلی‌ثانیهٔ یک core و ۶۴ MiB حافظه باشد، مهاجمِ دارای یک رَک GPU سود کمی می‌برد، چون گلوگاه حافظه است نه محاسبه. اگر هر حدس یک میکروثانیه باشد، گذرواژهٔ ۱۰ حرفیِ حروف کوچک در چند ساعت می‌افتد. همین یک واقعیت بقیهٔ فصل را توضیح می‌دهد.

از کجا آمده ​

YearEventWhy it matters
1997RFC 2104 (HMAC), Bellare, Canetti, Krawczyk, February 1997The standard keyed hash: the basis for signed cookies, signed URLs, HS256 and PBKDF2
1999bcrypt, Provos & Mazières, USENIX 1999First widely deployed adaptable-cost password hash; the cost is stored in the hash
2015RFC 7519 (JWT), May 2015, with JWA RFC 7518The standard token format; defines alg: none as legal, which later becomes an attack
2015Password Hashing Competition (PHC) names Argon2 the winnerMemory-hard design; the PHC string format comes from the same effort (taken from the Argon2 reference README, which shows $argon2i$v=19$m=65536,t=2,p=4$...)
2017RFC 8037 adds EdDSA (Ed25519) to JOSESmall, fast, deterministic signatures for JWT
laterPASETO ("Platform-Agnostic Security Tokens") versions v1 to v4; v4 is the one this page usesRemoves algorithm choice from the token (PASETO spec and its V3/V4 rationale were read)
2020RFC 8725 (BCP 225), February 2020: JWT Best Current PracticesNames the attacks: weak signatures, key confusion, cross-JWT confusion
2021RFC 9106 (Argon2), September 2021, InformationalGives the "first" and "second recommended" parameter sets
current revisionNIST SP 800-63B-4 (the revision I read): 15 characters minimum for single-factor passwords, no composition rules, blocklist checksPolicy moves from "complexity" to "length plus breach list"

مقالهٔ Provos منبع اولیهٔ این ایده است که «هزینهٔ محاسباتیِ هر طرح امنِ گذرواژه باید با بهتر شدن سخت‌افزار بالا برود» (چکیدهٔ خودشان)؛ پارامتر cost در bcrypt دقیقاً برای همین وجود دارد. نتیجهٔ مسابقهٔ PHC و قالب رشتهٔ PHC در اینجا فقط از README مرجع Argon2 نقل شده است (فایل spec خودِ مخزن PHC قابل دریافت نبود)؛ RFCها، OWASP، NIST و گفته‌های Laravel در این صفحه از منابع ذخیره‌شده‌ای خوانده شده‌اند که در بخش منابع آمده است.

hash کردن گذرواژه، مفهوم به مفهوم ​

مسیر کامل ذخیره در یک تصویر: pepper، salt و work factor به یک hashِ کند می‌رسند و هر چیزی جز pepper در رشتهٔ ذخیره‌شده می‌ماند.

passworduser inputHMAC-SHA256(pepper, password)Argon2id / bcryptslow, memory-hardusers.password$argon2id$v=19$m=..$salt$tagsalt + params + tagpepper (secret)vault / HSM / env, NOT in DBsalt (random)16 bytes, per user, publicwork factorcost / m,t,p, stored in hashDB leak alone: attacker has salt + tag but not the pepper, and every guess costs a full slow hash

چرا گذرواژه hash می‌شود نه رمز حیاتی ​

به زبان ساده: hash گذرواژه را به اثرانگشتِ هم‌اندازه‌ای تبدیل می‌کند که برگشت ندارد؛ موقع ورود چیزی را که کاربر تایپ کرده hash می‌کنید و اثرانگشت‌ها را مقایسه می‌کنید. رمزنگاری با کلید برگشت‌پذیر است، پس دزدیده‌شدن کلید همه‌چیز را باز می‌کند.

بدفهمی رایج: «hash، encoding و encryption سه مدل درهم‌کردن‌اند.» Encoding (Base64، hex) راز ندارد؛ encryption کلید دارد و برگشت‌پذیر است؛ hash کلید ندارد و برگشت‌ناپذیر است. اشتباه‌گرفتن این‌ها همان چیزی است که «رمزنگاری گذرواژه»ی ارسالی را در واقع Base64 می‌کند.

تعریف: hash گذرواژه خروجی یک تابع عمداً کندِ یک‌طرفهٔ H(password, salt, parameters) است. Verify با همان salt و پارامترها دوباره حساب می‌کند و به‌صورت constant-time مقایسه می‌کند. هرگز نمی‌توانید گذرواژه را بازیابی کنید، پس «فراموشی گذرواژه» یعنی «گذرواژهٔ جدید بگذار».

operation   key?   reversible?   use it for
----------  -----  ------------  ----------------------------------
encoding    no     yes           transport (Base64, hex, URL-encoding)
hashing     no     no            integrity, fingerprints, passwords (slow, salted)
HMAC        yes    no            integrity + authenticity with a shared key
encryption  yes    yes           secrecy you must read back (AES-GCM)
signature   yes    no            authenticity with a key pair (Ed25519, RSA)

سناریوی واقعی: یک dump با MD5 بدون salt: بیشتر ردیف‌ها در چند ثانیه با wordlist می‌افتند (آزمایش پایین سه کاربر از چهار کاربر نمونه را در ۵۰ میکروثانیه می‌شکند). با Argon2id و salt یکتا فقط ضعیف‌ترین گذرواژه‌ها بعد از هفته‌ها GPU کرک می‌شوند.

ToolDoes
Hash::make() (Laravel)Salted, slow, one-way; the right tool for passwords
Crypt::encryptString() (Laravel)Reversible AES with MAC; wrong tool for passwords, right for data you must read back
bcrypt.GenerateFromPassword (Go)Same as Hash::make with bcrypt
hash('sha256', $pw) / sha256.Sum256Fast and unsalted; wrong tool for passwords

Salt حیاتی ​

به زبان ساده: salt مقدار تصادفی‌ای است که کنار هر hash ذخیره می‌شود و با آن مخلوط می‌شود، پس دو کاربر با یک گذرواژه دو hash متفاوت دارند.

بدفهمی رایج: «salt راز است، پس پنهانش کنید.» Salt عمداً عمومی است و داخل رشتهٔ hash می‌نشیند. کارش یکتایی است نه رازداری. جزء رازدار pepper است.

تعریف: مقدار تصادفیِ حداقل ۱۲۸ بیتی به‌ازای هر کاربر (bcrypt: ۱۶ بایت = ۲۲ کاراکتر Base64؛ Argon2 توصیه می‌کند ۱۶ بایت؛ RFC 9106 در مجموعه‌های پیشنهادی salt ۱۲۸ بیتی می‌گیرد)، که به تابع hash داده می‌شود و کنار خروجی ذخیره می‌شود.

without salt                    with a unique salt per user
1  ann: sha256("hunter2") = f52f...    1  ann: H("hunter2", saltA) = 8c1e...
2  bob: sha256("hunter2") = f52f...    2  bob: H("hunter2", saltB) = a97b...
3  one crack opens both, and one      3  precomputed tables are useless,
   rainbow table opens every user        and each user is a separate attack

سناریوی واقعی: در نشت سایتی با hash بدون salt، مهاجم ستون را بر اساس تکرار مرتب می‌کند: پرتکرارترین hash همان 123456 است. با salt هیچ تکراری برای خواندن نیست.

ProblemWithout saltWith salt
Rainbow tablesWorkDefeated (a table per salt is infeasible)
Equal passwords visibleYesNo
Cracking all usersOne passOne pass per user
Parallel cracking costSameMultiplied by the number of users

Go و Laravel: salt را خودتان نمی‌سازید: bcrypt.GenerateFromPassword، کمک‌تابع‌های argon2 در snippetها و Hash::make() همه آن را از CSPRNG سیستم‌عامل می‌گیرند (crypto/rand، random_bytes). هرگز آن را از username نسازید و بین کاربران تکرار نکنید.

Pepper مهم ​

به زبان ساده: pepper یک کلید رازِ مشترک بین همهٔ کاربران است که بیرون از دیتابیس (secrets manager یا HSM) نگه داشته می‌شود. قبل از hashِ کند با گذرواژه مخلوطش می‌کنید، پس دیتابیسِ دزدیده‌شده به‌تنهایی قابل کرک نیست.

بدفهمی رایج: «pepper جای salt را می‌گیرد» یا «pepper گذرواژهٔ ضعیف را قوی می‌کند.» هیچ‌کدام. فقط وقتی کمک می‌کند که مهاجم دیتابیس را دارد ولی کلید را نه؛ اگر روی app server کد اجرا کند، pepper را هم می‌خواند. OWASP هم می‌گوید به‌تنهایی ویژگی امنیتی اضافه نمی‌دهد.

تعریف: tag = SlowHash(HMAC-SHA256(pepper, password), salt, cost) (pepper قبل از hash) یا HMAC(pepper, SlowHash(password, salt)) (pepper بعد از hash). NIST SP 800-63B می‌افزاید verifier باید یک عملیات keyed hash با کلیدی که فقط verifier می‌داند اعمال کند، جدا از hashها نگه دارد و ترجیحاً در سخت‌افزار محافظت‌شده.

1  password "hunter2"
2  HMAC-SHA256(pepper, "hunter2")  -> 32 bytes
3  base64                          -> 44 printable chars (no NUL byte, under 72)
4  bcrypt/Argon2id(step 3, salt, cost)  -> stored string
   attacker with DB only: has salt + tag, no pepper -> cannot even start guessing

سناریوی واقعی: یک SQL injection جدول users را بیرون می‌ریزد؛ pepper در AWS Secrets Manager است و هرگز در دیتابیس نبوده. مهاجم باید لایهٔ app را هم بشکند، یعنی یک نفوذ دومِ پرسروصدا.

Pepper designRotationNotes
Single pepper, pre-hash HMACHard: you need the plaintext to rehashStore a pepper ID; rotate by rehashing at next login
Pepper ID per row (v1, v2)Gradual: new logins use v2Keep old peppers until the last user has moved
Post-hash keyed hash (HMAC of the stored tag)Easy: can re-wrap without the passwordWrapped value is no longer a standard PHC string

Go: pepper/main.go پس از HMAC و Base64، bcrypt را اجرا می‌کند. Laravel: کلاس PepperedHasher دور Hash::make() می‌پیچد تا منطق cost و rehash خودِ framework سالم بماند.

go
// Pepper: HMAC the password with a secret key held outside the database,
// then feed the result to the slow hash.
package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"os"

	"golang.org/x/crypto/bcrypt"
)

// prehash returns base64(HMAC-SHA256(pepper, password)): 44 printable bytes,
// so no NUL byte and under bcrypt's 72-byte limit.
func prehash(pepper []byte, password string) []byte {
	m := hmac.New(sha256.New, pepper)
	m.Write([]byte(password))
	return []byte(base64.StdEncoding.EncodeToString(m.Sum(nil)))
}

func main() {
	pepper := []byte(os.Getenv("PASSWORD_PEPPER"))
	if len(pepper) == 0 {
		pepper = make([]byte, 32) // demo only: real peppers live in a vault or HSM
		if _, err := rand.Read(pepper); err != nil {
			panic(err)
		}
	}
	hash, err := bcrypt.GenerateFromPassword(prehash(pepper, "hunter2"), 12)
	if err != nil {
		panic(err)
	}
	fmt.Println("stored:", string(hash))
	fmt.Println("right pepper:", bcrypt.CompareHashAndPassword(hash, prehash(pepper, "hunter2")) == nil)
	other := make([]byte, 32)
	fmt.Println("stolen DB, wrong pepper:", bcrypt.CompareHashAndPassword(hash, prehash(other, "hunter2")) == nil)
	// A long passphrase is no longer truncated: the prehash is always 44 bytes.
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Hash;

/**
 * Pepper = secret HMAC key kept outside the database (env, secrets manager, HSM).
 * Pre-hash with HMAC-SHA256, base64 it (44 printable bytes: no NUL byte, under
 * bcrypt's 72-byte limit), then run the slow hash.
 */
class PepperedHasher
{
    public function __construct(private readonly string $pepper)
    {
        // config('services.password_pepper') loaded from a secret store, 32+ random bytes.
    }

    private function prehash(string $plain): string
    {
        return base64_encode(hash_hmac('sha256', $plain, $this->pepper, binary: true));
    }

    public function make(string $plain): string
    {
        return Hash::make($this->prehash($plain));
    }

    public function check(string $plain, string $hash): bool
    {
        return Hash::check($this->prehash($plain), $hash);
    }

    public function needsRehash(string $hash): bool
    {
        return Hash::needsRehash($hash);
    }
}

Work factor (cost) حیاتی ​

به زبان ساده: work factor دکمه‌ای است که hash را عمداً کندتر می‌کند و با سریع‌شدن کامپیوترها بالایش می‌برید. کندی برای شما (یک بار در هر ورود) برای مهاجمی که میلیاردها حدس لازم دارد میلیون‌ها برابر است.

بدفهمی رایج: «cost ۱۲ همیشه درست است.» مقدار درست آن است که روی سخت‌افزار production و بار واقعی حدود ۵۰ تا ۲۵۰ میلی‌ثانیه طول بکشد، و این عدد هر چند سال جابه‌جا می‌شود. اندازه بگیرید؛ کپی نکنید.

تعریف: پارامترهای قابل تنظیمِ زمان (و برای Argon2/scrypt حافظهٔ) یک hash. bcrypt: cost لگاریتم دو در مبنای تعداد round است، پس +۱ زمان را دو برابر می‌کند. Argon2: m (حافظه به KiB)، t (تعداد پاس)، p (lane/موازی‌سازی). scrypt: N، r، p. PBKDF2: تعداد iteration.

bcrypt cost   rounds = 2^cost    time on one M5 core (measured in the lab)
10            1,024              46 ms
12            4,096              185 ms
14            16,384             741 ms     (each +1 doubles the time)

سناریوی واقعی: endpoint ورود با cost ۱۴ و ۲۰۰ ورود هم‌زمان همهٔ core‌ها را یک ثانیه می‌گیرد: hash به اهرم denial-of-service تبدیل شد. cost را با اوج نرخ ورود تنظیم کنید، rate limit بگذارید و در صورت نیاز hash را به worker pool ببرید.

KnobIncrease it toEffect on defenderEffect on attacker
bcrypt costResist faster CPUs+CPU time, doubling per stepSame doubling per guess
Argon2 mDefeat GPUs/ASICs+RAM per concurrent loginMemory per parallel guess; limits GPU parallelism
Argon2 tSlow down when RAM is capped+CPU time, linearLinear
Argon2 pUse more cores per hashLower latency, more cores per loginOWASP: parallelism is not a guarantee of slower guessing
PBKDF2 iterationsResist faster CPUsLinearLinear, but cheap on GPUs: no memory hardness

bcrypt حیاتی ​

به زبان ساده: bcrypt همان hash قدیمیِ آزموده است: رشته‌ای ۶۰ کاراکتری که cost و salt خودش را حمل می‌کند. به‌اندازهٔ کافی خوب است؛ ضعف‌هایش سقف ۷۲ بایت و نداشتن memory hardness است.

بدفهمی رایج: «bcrypt هر طولی را hash می‌کند.» فقط ۷۲ بایت اول را می‌خواند. عبارتی ۱۰۰ حرفی که فقط بعد از بایت ۷۲ فرق دارد برای bcrypt یک گذرواژه است. golang.org/x/crypto/bcrypt (نسخهٔ v0.59.0) ورودی بلندتر را با ErrPasswordTooLong رد می‌کند (اندازه‌گیری: bcrypt: password length exceeds 72 bytes) و درایور bcrypt در Laravel گزینهٔ limit دارد که exception می‌اندازد.

تعریف: bcrypt (Provos و Mazières، ۱۹۹۹) بر پایهٔ Blowfish با «expensive key schedule» (eksblowfish) ساخته شده. قالب خروجی: $2<variant>$<cost>$<salt ۲۲ کاراکتری><hash ۳۱ کاراکتری>، ۶۰ کاراکتر، با الفبای Base64 مخصوص خودش (./A-Za-z0-9). پیشوندها: $2a$ (رایج در Go و بسیاری کتابخانه‌ها)، $2b$ (اصلاح OpenBSD پس از یک باگ wraparound)، $2y$ (خروجی password_hash در PHP، همان الگوریتم $2b$). این سه برای گذرواژه‌های معمولی hashِ همدیگر را verify می‌کنند.

$2y$10$Hxin/S1TsLcq/vSX9DawE.fh.4UJWCvQz7bO.JWuu5ggfld50eKSa
 |   |  |                      |
 |   |  22 chars = 16 bytes     31 chars = 23 bytes of the hash (184 bits)
 |   cost: 10 -> 2^10 rounds
 prefix: algorithm 2, variant y
total length = 4 + 2 + 1 + 22 + 31 = 60

سناریوی واقعی: کاربری گذرواژهٔ ۹۰ حرفیِ تولیدشده را در سیستم فقط-bcrypt وارد می‌کند و بعداً با ۷۲ حرف اول وارد می‌شود. کار می‌کند، بی‌صدا. دفاع: سقف ۷۲ بایت (OWASP) یا pre-hash (پایین) با Base64 تا بایت NUL ورودی را قطع نکند.

bcrypt trapCauseFix
Truncation at 72 bytesAlgorithm reads 72 bytes of keyReject longer, or HMAC → Base64 → bcrypt
Pre-hash with raw bytesThe original bcrypt expects a NUL-terminated string; a hash with a leading 0x00 becomes the empty passwordBase64-encode the digest (OWASP warns about this and about "password shucking")
Multi-byte charactersCounted in bytes, not charactersCount len(pw) in bytes
No memory hardness4 KiB of state fits in a GPU core's cachePrefer Argon2id for new systems

Go: bcryptcost/main.go؛ Laravel: Hash::make($pw, ['rounds' => 12]) و گزینهٔ limit در config/hashing.php.

go
// Measure bcrypt cost 10/12/14 on this machine and show the 72-byte limit.
package main

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"golang.org/x/crypto/bcrypt"
)

func main() {
	pw := []byte("correct horse battery staple")

	for _, cost := range []int{10, 12, 14} {
		start := time.Now()
		hash, err := bcrypt.GenerateFromPassword(pw, cost)
		if err != nil {
			panic(err)
		}
		fmt.Printf("cost=%d  %8s  %s\n", cost, time.Since(start).Round(time.Millisecond), hash)
	}

	// The cost is stored inside the hash: Cost() reads it back.
	hash, _ := bcrypt.GenerateFromPassword(pw, 12)
	c, _ := bcrypt.Cost(hash)
	fmt.Println("cost stored in hash:", c)

	// bcrypt only reads the first 72 bytes. x/crypto refuses longer input.
	long := []byte(strings.Repeat("a", 73))
	_, err := bcrypt.GenerateFromPassword(long, 10)
	fmt.Println("73 bytes:", err, errors.Is(err, bcrypt.ErrPasswordTooLong))

	// The classic truncation: two passwords equal in their first 72 bytes.
	h72, _ := bcrypt.GenerateFromPassword([]byte(strings.Repeat("a", 72)), 10)
	fmt.Println("72 a's matches itself:", bcrypt.CompareHashAndPassword(h72, []byte(strings.Repeat("a", 72))) == nil)
}

Argon2id حیاتی ​

به زبان ساده: Argon2id hash مدرن گذرواژه است: کند است و RAM زیاد هم می‌خواهد، که برای دستگاه‌های کرک GPU و ASIC گران است. سه عدد تنظیم می‌کنید: حافظه، پاس و موازی‌سازی.

بدفهمی رایج: «thread بیشتر (p) یعنی hash قوی‌تر.» موازی‌سازی فقط سرورِ خودتان را در تمام‌کردن یک hash سریع‌تر می‌کند؛ OWASP می‌گوید بالا بردن parallelism تضمینی برای کندتر شدن حدس‌زدن نیست. بودجه را اول صرف حافظه کنید، بعد پاس.

تعریف: Argon2 (Biryukov، Dinu، Khovratovich؛ RFC 9106، سپتامبر ۲۰۲۱) سه نوع دارد: Argon2d (دسترسی حافظهٔ وابسته به داده، سریع‌ترین، در برابر side channel آسیب‌پذیر)، Argon2i (مستقل از داده، مقاوم در برابر side channel، در برابر حمله‌های trade-off ضعیف‌تر) و Argon2id که ترکیبی است: نیمهٔ اول پاس اول مستقل از داده و باقی وابسته به داده. توصیه برای گذرواژه Argon2id است.

RFC 9106 وقتی نمی‌توانید برای سخت‌افزارتان تنظیم کنید دو مجموعهٔ «امنِ یکنواخت» می‌دهد: FIRST RECOMMENDED: t=1، p=4، m=2^21 KiB (۲ GiB)، salt ۱۲۸ بیتی، tag ۲۵۶ بیتی. SECOND RECOMMENDED (حافظهٔ بسیار کمتر): t=3، p=4، m=2^16 KiB (۶۴ MiB)، salt ۱۲۸ بیتی، tag ۲۵۶ بیتی. حداقل‌های OWASP عمداً پایین‌تر است: ۱۹ MiB با t=2 و p=1 یا معادل‌هایش در جدول یک‌دقیقه.

Argon2id inputs                         output
password, salt (16 B), m (KiB), t, p, tag length (32 B)   ->   32-byte tag
memory = m KiB split into p lanes; t passes over the memory; each block depends on earlier ones

سناریوی واقعی: وب‌سرور ۴ هسته‌ای با ۴۰ ورود هم‌زمان در m=۶۴ MiB فقط برای hash ۴۰ × ۶۴ MiB = ۲٫۵ GiB لازم دارد. بودجهٔ حافظه، نه CPU، تعیین می‌کند چند ورودِ هم‌زمان را می‌توانید پاسخ دهید. m را با هم‌زمانیِ ورود اندازه کنید.

اندازه‌گیری روی ماشین نویسنده (Apple M5، ۱۰ هسته؛ عددهای شما فرق می‌کند)، argon2bench/main.go:

ParametersTimeNote
m=19 MiB, t=2, p=1 (OWASP minimum)17 mstoo fast on this hardware: raise it
m=46 MiB, t=1, p=1 (OWASP)21 ms
m=64 MiB, t=3, p=4 (RFC 9106 second)37 mson a CPU this fast, step up
m=256 MiB, t=3, p=4156 msin the 50-250 ms target band
m=1 GiB, t=1, p=4182 msneeds 1 GiB of RAM per concurrent login
m=1 MiB, t=2, p=2 (Laravel's ArgonHasher class default)below 1 msthe class default is far weaker than the config default of 65536 KiB; set it yourself
go
// Measure Argon2id with different memory and time costs.
package main

import (
	"crypto/rand"
	"fmt"
	"runtime"
	"time"

	"golang.org/x/crypto/argon2"
)

func main() {
	salt := make([]byte, 16)
	if _, err := rand.Read(salt); err != nil {
		panic(err)
	}
	pw := []byte("correct horse battery staple")
	threads := uint8(4)
	fmt.Println("cpus:", runtime.NumCPU())

	type cfg struct {
		name string
		t, m uint32 // iterations, memory in KiB
		p    uint8
	}
	for _, c := range []cfg{
		{"OWASP min 19 MiB t=2 p=1", 2, 19 * 1024, 1},
		{"OWASP min 46 MiB t=1 p=1", 1, 46 * 1024, 1},
		{"64 MiB t=3 p=4 (RFC 9106 2nd)", 3, 64 * 1024, threads},
		{"256 MiB t=3 p=4", 3, 256 * 1024, threads},
		{"1 GiB t=1 p=4", 1, 1024 * 1024, threads},
		{"Laravel default 1 MiB t=2 p=2", 2, 1024, 2},
	} {
		start := time.Now()
		key := argon2.IDKey(pw, salt, c.t, c.m, c.p, 32)
		fmt.Printf("%-34s %8s  tag=%x...\n", c.name, time.Since(start).Round(time.Millisecond), key[:6])
	}
}

scrypt و PBKDF2 تکمیلی ​

به زبان ساده: scrypt تابع memory-hardِ قدیمی‌تری است (وقتی Argon2id نیست)؛ PBKDF2 تابع قدیمیِ ساده و فقط-CPU است که وقتی مقررات مجبورتان کند استفاده می‌کنید.

بدفهمی رایج: «PBKDF2 با ۱۰٬۰۰۰ iteration خوب است، آموزش‌ها همین را نشان می‌دهند.» کف OWASP برای PBKDF2-HMAC-SHA256 برابر ۶۰۰٬۰۰۰ iteration است؛ ده‌هزار عددِ دههٔ ۲۰۰۰ بود.

تعریف: scrypt پارامترهای N (هزینهٔ CPU/حافظه، توان دو)، r (اندازهٔ block) و p (موازی‌سازی) دارد؛ حداقل OWASP: N=2^17، r=8، p=1. PBKDF2 (RFC 8018، اینجا خوانده نشده) HMAC را iterations بار اعمال می‌کند؛ OWASP می‌گوید وقتی انطباق FIPS-140 لازم است ۶۰۰٬۰۰۰ یا بیشتر با HMAC-SHA-256. هیچ‌کدام مقاومت Argon2 در برابر GPU را ندارند، مگر جملهٔ حافظه‌ای scrypt.

FunctionMemory hard?Where you meet itStatus
Argon2idYesargon2.IDKey (Go), PASSWORD_ARGON2ID (PHP), Laravel argon2id driverFirst choice
scryptYesgolang.org/x/crypto/scrypt, sodium_crypto_pwhash_scryptsalsa208sha256, Node crypto.scryptAcceptable
bcryptBarely (4 KiB)$2y$ everywhereFine, legacy
PBKDF2Nogolang.org/x/crypto/pbkdf2, hash_pbkdf2(), WPA2, many legacy systemsOnly for FIPS
Plain SHA-256/MD5NoThe mistakesNever for passwords

قالب رشتهٔ PHC حیاتی ​

به زبان ساده: hash گذرواژه به‌صورت یک رشتهٔ متنی ذخیره می‌شود که نام الگوریتم، پارامترها و salt را هم دارد. به همین دلیل می‌توانید بعداً cost را بالا ببرید و hashهای قدیمی باز هم verify شوند.

بدفهمی رایج: «salt را باید در ستون جدا بگذارم.» salt در خودِ رشته است؛ ستون جدا زائد است و معمولاً نشانهٔ ساختن طرح دست‌ساز است.

تعریف: قالب رشتهٔ PHC (از Password Hashing Competition) این است: $<id>$[v=<version>$]<param>=<value>,...$<salt>$<hash>، با salt و hash به Base64 بدون padding. hashهای Argon2 در دنیای واقعی: $argon2id$v=19$m=65536,t=3,p=4$<salt>$<tag>. bcrypt قدیمی‌تر از PHC است و قالب ثابت‌عرض خودش را دارد. README مرجع Argon2 همین شکل را نشان می‌دهد: $argon2i$v=19$m=65536,t=2,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG.

آناتومی دو قالبی که با آن‌ها روبه‌رو می‌شوید:

Argon2id, PHC string format (fields separated by $)$argon2idv=19m=65536,t=3,p=4c29tZXNhbHRzb21lc2FsdAgduXp+Z6iReEolm...Fn/AeIalgorithm idversionmemory KiB, passes, lanessalt, 16 bytestag, 32 bytes0x13 = 1964 MiB, 3 passes, 4 threads22 chars Base64, no padding43 chars Base64, no paddingbcrypt, fixed 60 characters$2y$10Hxin/S1TsLcq/vSX9DawE.fh.4UJWCvQz7bO.JWuu5ggfld50eKSaprefixcostsalt, 22 chars (128 bits)hash, 31 chars (184 bits)Everything needed to verify is inside the string: parameters travel with the hash, so they can change later

بایت‌به‌بایت، با salt ثابت ۱۶ بایتی somesaltsomesalt (اندازه‌گیری با phcbytes/main.go):

$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$gduXp+Z6iReEolmbyHn5V8s1EtJzmEvZfYoY/Fn/AeI

field 1  argon2id                  algorithm id (Argon2id; argon2i and argon2d exist)
field 2  v=19                      version 0x13, decimal 19
field 3  m=65536,t=3,p=4           memory 65536 KiB = 64 MiB, 3 passes, 4 lanes
field 4  c29tZXNhbHRzb21lc2FsdA    salt, Base64 without padding, 22 chars
field 5  gduXp+Z6iR...Fn/AeI      tag, Base64 without padding, 43 chars

salt hex (16 bytes): 736f6d6573616c74736f6d6573616c74     "somesaltsomesalt" in ASCII
tag  hex (32 bytes): 81db97a7e67a891784a2599bc879f957cb3512d273984bd97d8a18fc59ff01e2
Base64 check: 16 bytes -> ceil(16*4/3) = 22 chars; 32 bytes -> 43 chars

تلهٔ امضایی: Base64 در PHC الفبای استاندارد (+ و /) بدون = است؛ JWT الفبای URL-safe (- و _) را به کار می‌برد. قاطی‌کردن این دو هنگام decode باگ کلاسیک است؛ Binary-to-Text Encoding را ببینید.

سناریوی واقعی: tag آرگون ۳۲ بایت است و هر ردیف حدود ۹۷ کاراکتر. Verify پارامترهای m، t و p را از رشته می‌خواند نه از config شما؛ پس ردیف‌های ۲۰۲۳ با m=۱۹ MiB بعد از بالا بردن config به ۶۴ MiB هنوز verify می‌شوند و برای rehash علامت می‌خورند.

LibraryOutputReads parameters from the string?
PHP password_hash(..., PASSWORD_ARGON2ID)$argon2id$v=19$m=65536,t=4,p=1$...Yes, password_verify and password_get_info
Go golang.org/x/crypto/argon2Raw tag only: no encodingNo: you write the PHC encode/decode (see phc/main.go)
Go golang.org/x/crypto/bcrypt$2a$10$...Yes, bcrypt.Cost(hash)
libargon2 CLIEncoded: lineYes
passlib, argon2-cffi (Python)PHCYes
go
// Decode a PHC string and a bcrypt string byte by byte, with a fixed salt so
// the output is reproducible.
package main

import (
	"encoding/base64"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	salt := []byte("somesaltsomesalt") // 16 bytes, fixed for the demo only
	tag := argon2.IDKey([]byte("password"), salt, 3, 65536, 4, 32)
	b64 := base64.RawStdEncoding
	phc := fmt.Sprintf("$argon2id$v=19$m=65536,t=3,p=4$%s$%s", b64.EncodeToString(salt), b64.EncodeToString(tag))
	fmt.Println(phc)
	for i, f := range strings.Split(phc, "$")[1:] {
		fmt.Printf("field %d: %s\n", i+1, f)
	}
	fmt.Printf("salt hex (%d bytes): %x\n", len(salt), salt)
	fmt.Printf("tag  hex (%d bytes): %x\n", len(tag), tag)
	fmt.Println("salt chars:", len(b64.EncodeToString(salt)), " tag chars:", len(b64.EncodeToString(tag)))

	h, _ := bcrypt.GenerateFromPassword([]byte("password"), 10)
	s := string(h)
	fmt.Println(s, "length", len(s))
	fmt.Println("prefix:", s[:4], " cost:", s[4:6], " salt(22):", s[7:29], " hash(31):", s[29:])
}
go
// PHC string encode/decode for Argon2id, constant-time verify, and the
// rehash-on-login upgrade path.
package main

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
)

// Params are the tuning knobs stored inside the hash string.
type Params struct {
	Memory      uint32 // KiB
	Time        uint32
	Parallelism uint8
	SaltLen     uint32
	KeyLen      uint32
}

// Current is the policy today. Raise it later; old hashes keep working.
var Current = Params{Memory: 64 * 1024, Time: 3, Parallelism: 4, SaltLen: 16, KeyLen: 32}

var b64 = base64.RawStdEncoding // PHC uses standard Base64 without padding

// Hash returns $argon2id$v=19$m=...,t=...,p=...$salt$hash.
func Hash(password string, p Params) (string, error) {
	salt := make([]byte, p.SaltLen)
	if _, err := rand.Read(salt); err != nil {
		return "", err
	}
	key := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Parallelism, p.KeyLen)
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, p.Memory, p.Time, p.Parallelism, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}

var ErrBadFormat = errors.New("not an argon2id PHC string")

// Decode splits a PHC string into its fields.
func Decode(s string) (p Params, salt, key []byte, err error) {
	parts := strings.Split(s, "$")
	// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash]
	if len(parts) != 6 || parts[1] != "argon2id" {
		return p, nil, nil, ErrBadFormat
	}
	var version int
	if _, err = fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
		return p, nil, nil, ErrBadFormat
	}
	var par uint8
	if _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &par); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	p.Parallelism = par
	if salt, err = b64.DecodeString(parts[4]); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	if key, err = b64.DecodeString(parts[5]); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	p.SaltLen, p.KeyLen = uint32(len(salt)), uint32(len(key))
	return p, salt, key, nil
}

// Verify recomputes the tag with the parameters stored in the hash and
// compares in constant time.
func Verify(password, encoded string) (bool, error) {
	p, salt, want, err := Decode(encoded)
	if err != nil {
		return false, err
	}
	got := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Parallelism, p.KeyLen)
	return subtle.ConstantTimeCompare(got, want) == 1, nil
}

// NeedsRehash is true when the stored hash is weaker than the current policy.
func NeedsRehash(encoded string) bool {
	p, _, _, err := Decode(encoded)
	if err != nil {
		return true // legacy format (bcrypt, md5, ...): upgrade it
	}
	return p.Memory < Current.Memory || p.Time < Current.Time || p.Parallelism != Current.Parallelism
}

// Login shows the upgrade path: verify first, then rehash with the
// plaintext you hold for exactly this one moment.
func Login(password, stored string) (ok bool, newHash string, err error) {
	ok, err = Verify(password, stored)
	if err != nil || !ok {
		return false, "", err
	}
	if NeedsRehash(stored) {
		newHash, err = Hash(password, Current)
	}
	return true, newHash, err
}

func main() {
	old := Params{Memory: 19 * 1024, Time: 2, Parallelism: 1, SaltLen: 16, KeyLen: 32}
	h, _ := Hash("hunter2", old)
	fmt.Println("old:", h)
	p, salt, key, _ := Decode(h)
	fmt.Printf("decoded: %+v salt=%x tag=%x\n", p, salt, key)
	ok, newHash, _ := Login("hunter2", h)
	fmt.Println("login ok:", ok, "rehashed:", newHash != "")
	fmt.Println("new:", newHash)
	ok, _ = Verify("wrong", newHash)
	fmt.Println("wrong password:", ok)
}

اداره‌کردن یک password store ​

Rehash هنگام ورود مهم ​

به زبان ساده: وقتی cost را بالا می‌برید، hashهای قدیمی تا جایگزینی ضعیف می‌مانند. تنها لحظه‌ای که plaintext دستتان است لحظهٔ ورود کاربر است، پس همان‌جا rehash می‌کنید.

بدفهمی رایج: «عوض‌کردن config همه‌چیز را دوباره رمز می‌کند.» config فقط روی hashهای جدید اثر می‌گذارد. ردیف‌هایی که کسی دست نمی‌زند برای همیشه با cost قدیمی می‌مانند و کاربرانی که دیگر وارد نمی‌شوند hash ضعیف را نگه می‌دارند. OWASP هر دو نکته را می‌گوید و پیشنهاد می‌کند در صورت لزوم hashهای قدیمی حذف و کاربر به بازنشانی گذرواژه وادار شود.

تعریف: بعد از verify موفق، پارامترهای ذخیره‌شده در hash را با سیاست فعلی مقایسه کنید (Hash::needsRehash، password_needs_rehash یا مقایسهٔ خودتان) و اگر ضعیف‌تر بود plaintext را دوباره hash و رشتهٔ جدید را بنویسید.

T1 login with old hash                         T2 database
1  SELECT password FROM users WHERE id = 7
2  verify("hunter2", $argon2id$v=19$m=19456,t=2,p=1$...)   -> ok
3  needsRehash? stored m=19456 < policy m=65536 -> yes
4  new = Hash::make("hunter2")      -> $argon2id$v=19$m=65536,t=3,p=4$...
5  UPDATE users SET password = new WHERE id = 7 AND password = old   -- compare-and-set
6  continue the login

سناریوی واقعی: از bcrypt با cost ۱۰ به Argon2id می‌روید. کاربران در شش ماه وارد می‌شوند و هر ورود یک ردیف را بی‌صدا ارتقا می‌دهد. بعد از شش ماه برای بقیه ایمیل می‌زنید یا برای حساب‌های خواب بازنشانی اجباری می‌گذارید. Laravel می‌تواند گام ۳ تا ۵ را خودش انجام دهد: 'rehash_on_login' => true در config/hashing.php (در فایل config خودِ framework که خواندم وجود دارد).

StackHow
LaravelHash::needsRehash($hash) then Hash::make($plain); or rehash_on_login so Auth::attempt() does it
PHPpassword_needs_rehash($hash, PASSWORD_ARGON2ID, $options)
GoDecode the PHC parameters (see phc/main.go) or bcrypt.Cost(hash) and compare to the target
Algorithm changeStore the algorithm in the hash (PHC id, $2y$); detect by prefix; set HASH_VERIFY=false during the migration so Laravel does not throw

مسیر ارتقا در Go و سرویس Laravel هر دو در snippetها هست:

php
<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class PasswordService
{
    /** Validation rule: length first, no composition rules, check the breach list. */
    public static function rule(): Password
    {
        return Password::min(12)->uncompromised();
    }

    public function register(string $email, string $plain): User
    {
        return User::create([
            'email' => $email,
            // Hash::make() reads config/hashing.php; options override per call.
            'password' => Hash::make($plain),
        ]);
    }

    public function attempt(User $user, string $plain): bool
    {
        // Hash::check() is constant-time (password_verify) and, with verify=true,
        // throws a RuntimeException if the stored hash uses a different algorithm.
        if (! Hash::check($plain, $user->password)) {
            return false;
        }

        // Rehash on login: the plaintext is in memory only now.
        if (Hash::needsRehash($user->password)) {
            $user->forceFill(['password' => Hash::make($plain)])->save();
        }

        return true;
    }

    /** Tune cost per call, for example in a benchmark command. */
    public function benchmark(string $plain): array
    {
        $out = [];
        foreach ([10, 12, 14] as $rounds) {
            $start = hrtime(true);
            Hash::driver('bcrypt')->make($plain, ['rounds' => $rounds]);
            $out["bcrypt-{$rounds}"] = (hrtime(true) - $start) / 1e6; // milliseconds
        }
        foreach ([19456, 65536, 262144] as $memory) {
            $start = hrtime(true);
            Hash::driver('argon2id')->make($plain, ['memory' => $memory, 'time' => 3, 'threads' => 1]);
            $out["argon2id-{$memory}KiB"] = (hrtime(true) - $start) / 1e6;
        }

        return $out;
    }
}

وقتی خودِ الگوریتم عوض می‌شود (MD5 به bcrypt به Argon2id)، اول digest قدیمی را wrap کنید و هنگام ورود جایگزین کنید:

php
<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;

/** Upgrade unsalted-MD5 rows lazily: wrap now, replace on the next login. */
class LegacyUpgrade
{
    /** One-off migration: bcrypt(md5) protects every row today without knowing any password. */
    public function wrapAll(): void
    {
        User::where('hash_scheme', 'md5')->chunkById(500, function ($users) {
            foreach ($users as $u) {
                $u->forceFill([
                    'password' => Hash::make($u->password), // $u->password holds the md5 hex
                    'hash_scheme' => 'bcrypt-md5',
                ])->save();
            }
        });
    }

    public function attempt(User $user, string $plain): bool
    {
        $candidate = $user->hash_scheme === 'bcrypt-md5' ? md5($plain) : $plain;

        if (! Hash::check($candidate, $user->password)) {
            return false;
        }

        if ($user->hash_scheme === 'bcrypt-md5' || Hash::needsRehash($user->password)) {
            $user->forceFill(['password' => Hash::make($plain), 'hash_scheme' => 'current'])->save();
        }

        return true;
    }
}
php
<?php

// config/hashing.php (publish with: php artisan config:publish hashing)

return [
    // "bcrypt", "argon" (Argon2i) or "argon2id"
    'driver' => env('HASH_DRIVER', 'argon2id'),

    'bcrypt' => [
        'rounds' => env('BCRYPT_ROUNDS', 12),
        'verify' => env('HASH_VERIFY', true),
        // Reject passwords longer than this many bytes instead of silently truncating at 72.
        'limit' => env('BCRYPT_LIMIT', 72),
    ],

    // Argon2 options. memory is in KiB: 65536 = 64 MiB.
    'argon' => [
        'memory' => env('ARGON_MEMORY', 65536),
        'threads' => env('ARGON_THREADS', 1),
        'time' => env('ARGON_TIME', 4),
        'verify' => env('HASH_VERIFY', true),
    ],

    // Rehash transparently during Auth::attempt() when the work factor changed.
    'rehash_on_login' => true,
];

مقایسهٔ constant-time حیاتی ​

به زبان ساده: مقایسهٔ معمولیِ رشته‌ها در اولین بایت متفاوت می‌ایستد، پس زمانش لو می‌دهد چند بایتِ اول درست بود. مقایسهٔ constant-time همیشه همهٔ بایت‌ها را می‌بیند.

بدفهمی رایج: «jitter شبکه پنهانش می‌کند، پس == مشکلی ندارد.» حمله‌های timing با میانگین‌گیری چندین نمونه حتی روی شبکه نشان داده شده‌اند. جایی که رایگان است درستش کنید: تابع constant-time.

تعریف: مقایسه‌ای که زمان اجرایش فقط به طول بستگی دارد نه به محل اولین تفاوت. Go: crypto/subtle.ConstantTimeCompare، hmac.Equal. PHP: hash_equals()، password_verify(). hasCorrectSignature در Laravel از hash_equals استفاده می‌کند و findToken در Sanctum هم.

naive ==                                 constant time
sig_expected  3f a9 c1 77 ...            diff = 0
sig_received  3f a9 00 ...               for i in 0..n-1: diff |= a[i] XOR b[i]
   stops at byte 3 -> fast               return diff == 0   (always n steps)
   attacker learns "two bytes right"

سناریوی واقعی: endpoint یک webhook هدر X-Signature را با == می‌سنجد. مهاجم زمان پاسخ را به‌ازای هر بایتِ حدسی اندازه می‌گیرد و HMAC را بایت‌به‌بایت بازسازی می‌کند بی‌آنکه کلید را بداند.

LanguageUseNot
Gosubtle.ConstantTimeCompare(a, b) == 1, hmac.Equalbytes.Equal, ==, strings.EqualFold
PHPhash_equals($known, $user) (known string first)===, strcmp
LaravelHash::check, hash_equals for HMACs== on tokens

نکته: وقتی API key را با digest مربوط به SHA-256 در دیتابیس جست‌وجو می‌کنید، lookup روی index نشتِ timing از راز نیست، چون مهاجم بدون دانستن پیش‌تصویر ۲۵۶ بیتی نمی‌تواند پیشوند digest را انتخاب کند.

سیاست گذرواژه و فهرست‌های نشتی مهم ​

به زبان ساده: بلند و غیرنشت‌کرده بهتر از «باید نماد داشته باشد» است. NIST حالا وقتی گذرواژه تنها عامل است حداقل ۱۵ کاراکتر می‌خواهد و هیچ قاعدهٔ ترکیبی نمی‌گذارد.

بدفهمی رایج: «قاعده‌های پیچیدگی (یک حرف بزرگ، یک رقم، یک نماد) گذرواژه را قوی می‌کند.» نتیجه‌اش Password1! است. NIST SP 800-63B-4: "Other composition requirements for passwords SHALL NOT be imposed" و گذرواژه‌ای که در blocklist مقادیر رایج، قابل‌انتظار یا نشت‌شده باشد باید رد شود.

تعریف: سیاست = حداقل طول (NIST: ۱۵ کاراکتر برای single-factor، ۸ وقتی فقط بخشی از multi-factor است؛ دست‌کم ۶۴ مجاز باشد)، همهٔ ASCII چاپ‌شدنی، فاصله و Unicode پذیرفته شود، blocklist رد شود، چرخش اجباری نباشد. HIBP Pwned Passwords یک range API با k-anonymity می‌دهد: ۵ نویسهٔ hex اول SHA-1 را می‌فرستید، همهٔ suffixهای آن پیشوند را با شمارش می‌گیرید و محلی تطبیق می‌دهید؛ گذرواژه و hash کامل هرگز سرور شما را ترک نمی‌کنند.

password "password"
SHA-1  = 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
prefix = 5BAA6                         <- sent: GET https://api.pwnedpasswords.com/range/5BAA6
suffix = 1E4C9B93F3F0682250B6CF8331B7EE68FD8   <- stays local, matched against the response lines
response line: 1E4C9B93F3F0682250B6CF8331B7EE68FD8:<count>

سناریوی واقعی: ثبت‌نام Summer2026! را رد می‌کند چون در یک نشت هست؛ بررسی یک فراخوانی HTTPS است و اگر HIBP قطع بود fail-open می‌کند تا ثبت‌نام متوقف نشود.

ItemBehaviour
LaravelPassword::min(12)->uncompromised() uses the same range API (validation rule in the Laravel docs)
Gohibp/main.go: SHA-1, prefix, Add-Padding: true, parse suffix lines
UnicodeNormalise (NFKC) before hashing so the same visible password hashes the same on every keyboard; see Bits, Bytes & Text Encoding
Maximum lengthAt least 64 allowed; with bcrypt cap at 72 bytes or pre-hash
go
// Pwned Passwords range API with k-anonymity: send 5 hex chars, never the
// password or the full hash.
package main

import (
	"bufio"
	"crypto/sha1"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

// Split returns the 5-char prefix sent to the API and the 35-char suffix kept local.
func Split(password string) (prefix, suffix string) {
	sum := sha1.Sum([]byte(password))
	h := strings.ToUpper(fmt.Sprintf("%x", sum))
	return h[:5], h[5:]
}

// Count parses a range response ("SUFFIX:COUNT" per line).
func Count(body io.Reader, suffix string) int {
	sc := bufio.NewScanner(body)
	for sc.Scan() {
		s, n, ok := strings.Cut(strings.TrimSpace(sc.Text()), ":")
		if ok && strings.EqualFold(s, suffix) {
			var c int
			fmt.Sscanf(n, "%d", &c)
			return c
		}
	}
	return 0
}

func main() {
	pw := "password"
	prefix, suffix := Split(pw)
	fmt.Println("send to API  :", "https://api.pwnedpasswords.com/range/"+prefix)
	fmt.Println("keep locally :", suffix)

	if os.Getenv("HIBP_ONLINE") == "" {
		fmt.Println("set HIBP_ONLINE=1 to call the API")
		return
	}
	c := &http.Client{Timeout: 10 * time.Second}
	req, _ := http.NewRequest(http.MethodGet, "https://api.pwnedpasswords.com/range/"+prefix, nil)
	req.Header.Set("Add-Padding", "true") // pad the response so its size leaks nothing
	resp, err := c.Do(req)
	if err != nil {
		fmt.Println("api unreachable: fail open, do not block signup:", err)
		return
	}
	defer resp.Body.Close()
	fmt.Println("seen in breaches:", Count(resp.Body, suffix), "times")
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

/** k-anonymity lookup: only the first 5 hex chars of SHA-1 leave your server. */
class PwnedPasswords
{
    public function count(string $plain): int
    {
        $sha1 = strtoupper(sha1($plain));
        $prefix = substr($sha1, 0, 5);
        $suffix = substr($sha1, 5);

        $response = Http::timeout(3)
            ->withHeaders(['Add-Padding' => 'true'])
            ->get("https://api.pwnedpasswords.com/range/{$prefix}");

        if ($response->failed()) {
            return 0; // fail open: an outage must not block sign-ups
        }

        foreach (explode("\n", $response->body()) as $line) {
            [$hashSuffix, $count] = array_pad(explode(':', trim($line)), 2, '0');
            if (hash_equals($suffix, strtoupper($hashSuffix))) {
                return (int) $count;
            }
        }

        return 0;
    }
}

hash کردن رازهای دیگر: API key، توکن بازیابی، session ​

توکن تصادفی: SHA-256، ذخیره، یک بار نمایش حیاتی ​

به زبان ساده: اگر راز از قبل ۲۵۶ بیت تصادفی است، هیچ‌کس نمی‌تواند حدسش بزند، پس hashِ کند لازم نیست. digest مربوط به SHA-256 را ذخیره کنید، plaintext را یک بار به کاربر نشان دهید و نشت دیتابیس دیگر ورود نیست.

بدفهمی رایج: «API key را باید مثل گذرواژه با bcrypt hash کرد.» کندی از انتخاب‌های ضعیف انسان محافظت می‌کند. توکن تصادفی ۲۵۶ بیتی با هر سرعتی brute-force نمی‌شود؛ bcrypt فقط ۱۰۰ میلی‌ثانیه به هر درخواست API اضافه می‌کند.

تعریف: token = prefix + base64url(32 بایت تصادفی از CSPRNG)؛ stored = hex(SHA-256(token))؛ جست‌وجو با digest و unique index؛ اختیاری: last_four، name، expires_at، abilities، last_used_at.

issue                                       use
1  token = "sk_live_" + b64url(random 32)    1  client sends  Authorization: Bearer sk_live_...
2  store sha256(token), last_four            2  server computes sha256(presented)
3  show token ONCE, never again              3  SELECT ... WHERE token_hash = ?    -> found: authenticated

سناریوی واقعی: Laravel Sanctum دقیقاً همین را می‌کند: مستندات می‌گوید توکن‌های API پیش از ذخیره با SHA-256 hash می‌شوند و PersonalAccessToken::findToken قالب id|token را می‌شکند، بخش token را hash می‌کند و با hash_equals می‌سنجد (کد از سورس Sanctum خوانده شد). توکن بازیابی گذرواژه و تأیید ایمیل همین الگو را با expiry کوتاه و یک‌بارمصرف دارند.

TokenEntropyStoreLifetime
API key / personal access token256 bitsSHA-256Until revoked (or expiry)
Password-reset token128+ bitsSHA-256 + expiry + single-use flag15 to 60 minutes
Email verification token128+ bitsSHA-25624 hours
Session ID128+ bitsSHA-256 in the session storeIdle + absolute timeout
Remember-me token256 bitsSHA-256, rotated on useDays to weeks
Human-typed code (6-digit OTP)about 20 bitsRate-limited, short expiry, HMAC with a keySeconds to minutes

ردیف آخر استثناست: کد شش‌رقمی کم‌آنتروپی است، پس دفاعش rate limit و expiry ۳۰ تا ۳۰۰ ثانیه‌ای است نه hash.

go
// API keys: random token, store only SHA-256, show the plaintext once.
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"encoding/hex"
	"fmt"
)

// New returns the plaintext to show once and the digest to store.
func New(prefix string) (plaintext, digest string, err error) {
	raw := make([]byte, 32) // 256 bits from the OS CSPRNG
	if _, err = rand.Read(raw); err != nil {
		return "", "", err
	}
	plaintext = prefix + "_" + base64.RawURLEncoding.EncodeToString(raw)
	return plaintext, Digest(plaintext), nil
}

// Digest is a plain SHA-256: the input already has 256 bits of entropy, so
// there is nothing for a slow hash to protect.
func Digest(plaintext string) string {
	sum := sha256.Sum256([]byte(plaintext))
	return hex.EncodeToString(sum[:])
}

// Check is the constant-time compare of two digests.
func Check(presented, storedDigest string) bool {
	return subtle.ConstantTimeCompare([]byte(Digest(presented)), []byte(storedDigest)) == 1
}

func main() {
	plain, digest, _ := New("sk_live")
	fmt.Println("show once :", plain)
	fmt.Println("store     :", digest)
	fmt.Println("valid     :", Check(plain, digest))
	fmt.Println("tampered  :", Check(plain+"x", digest))
}
php
<?php

namespace App\Services;

use App\Models\ApiKey;
use Illuminate\Support\Str;

/** Store SHA-256 of a random token; show the plaintext once (Sanctum does the same). */
class ApiKeyService
{
    /** @return array{id: int, plaintext: string} */
    public function issue(int $userId, string $name, ?\DateTimeInterface $expiresAt = null): array
    {
        // 40 random chars (about 238 bits) from random_bytes via Str::random.
        $plain = 'sk_live_'.Str::random(40);

        $key = ApiKey::create([
            'user_id' => $userId,
            'name' => $name,
            'token_hash' => hash('sha256', $plain),
            'last_four' => substr($plain, -4),
            'expires_at' => $expiresAt,
        ]);

        return ['id' => $key->id, 'plaintext' => $plain];
    }

    public function find(string $presented): ?ApiKey
    {
        // Index lookup on the digest. The digest is not a secret an attacker can use,
        // and the lookup key is a hash of a 238-bit secret, so no timing oracle on the secret.
        $key = ApiKey::where('token_hash', hash('sha256', $presented))->first();

        if ($key === null || ($key->expires_at !== null && $key->expires_at->isPast())) {
            return null;
        }

        return $key;
    }

    public function revoke(int $id): void
    {
        ApiKey::whereKey($id)->delete();
    }
}
sql
-- api_keys: the plaintext never exists in the database
CREATE TABLE api_keys (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id     bigint      NOT NULL REFERENCES users(id),
    name        text        NOT NULL,
    token_hash  char(64)    NOT NULL UNIQUE,          -- hex SHA-256
    last_four   char(4)     NOT NULL,                 -- for display: sk_live_...a1b2
    abilities   text[]      NOT NULL DEFAULT '{}',
    expires_at  timestamptz,
    last_used_at timestamptz,
    created_at  timestamptz NOT NULL DEFAULT now()
);
-- password_resets: single use, short life
CREATE TABLE password_resets (
    token_hash  char(64)    PRIMARY KEY,
    user_id     bigint      NOT NULL REFERENCES users(id),
    expires_at  timestamptz NOT NULL,
    used_at     timestamptz
);
-- consume atomically: only one request can win
UPDATE password_resets SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;

مقدار و URL امضاشده با HMAC ​

HMAC حیاتی ​

به زبان ساده: HMAC اثرانگشتی است که کلید می‌خواهد. بدون کلید هیچ‌کس نمی‌تواند برای یک پیام اثرانگشت معتبر بسازد، حتی اگر چندین جفت معتبر دیده باشد.

بدفهمی رایج: «sha256(secret + message) همان HMAC است.» الحاق ساده برای hashهای Merkle-Damgard مثل SHA-256 ضعف length-extension دارد؛ HMAC (RFC 2104) ساختاری است که از آن پرهیز می‌کند. از تابع کتابخانه استفاده کنید، هرگز دستی نسازید.

تعریف: HMAC(K, m) = H((K' xor opad) || H((K' xor ipad) || m)) که K' کلیدِ padشده تا اندازهٔ block (۶۴ بایت برای SHA-256) است، ipad بایت 0x36 تکرارشده و opad بایت 0x5c تکرارشده (RFC 2104). خروجی برای HMAC-SHA256 برابر ۳۲ بایت است. HMAC یکپارچگی و اصالت می‌دهد نه رازداری، و هر کس کلید را دارد هم می‌سازد هم verify می‌کند، پس برای یک دامنهٔ اعتماد مناسب است.

HMAC-SHA256("a-string-secret-at-least-256-bits-long",
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwiZXhwIjoxOTAwMDAwMDAwfQ")
= 05f78f8d3c83afb64d135ced86ded832f5255359ec8aa2b727cae19a042e2adc     (Go and openssl agree)
Use of HMACWhere
Signed cookies/sessionsLaravel encrypted cookies carry a MAC (Crypt), Rails/Django signed cookies
Signed URLsLaravel URL::signedRoute, S3 presigned URLs (HMAC-SHA256 SigV4), CDN signed URLs
Webhook signaturesX-Hub-Signature-256, Stripe Stripe-Signature: compute HMAC over the raw body, compare in constant time
JWT HS256HMAC over header.payload
PepperHMAC(pepper, password)
HKDF/PBKDF2Built from HMAC

Signed URL و signedRoute در Laravel حیاتی ​

به زبان ساده: signed URL اثبات خودش را همراه دارد: سرور یک HMAC به لینک اضافه می‌کند و وقتی لینک برمی‌گردد دوباره حسابش می‌کند. می‌توانید آن را به کسی بدهید که login نیست (unsubscribe، دانلود فاکتور) و باز بدانید از شما صادر شده، برای همان id و تا زمان مشخص.

بدفهمی رایج: «signed URL محرمانه است.» نیست: هر کس لینک را دارد تا expiry می‌تواند استفاده کند؛ امضا فقط جلوی ویرایش را می‌گیرد. فقط URL را امضا می‌کند: مستندات Laravel هشدار می‌دهد بدنهٔ درخواست امضا نمی‌شود و آزادانه قابل تغییر است.

تعریف: Laravel URL را با پارامترهای مرتب‌شده (ksort) می‌سازد، برای مسیرهای موقت expires اضافه می‌کند، hash_hmac('sha256', $url, $key) را روی URL کامل بدون signature حساب می‌کند و بعد signature=<hex> را می‌چسباند. Validation رشته را از درخواست ورودی منهای signature بازسازی می‌کند، HMAC را برای هر کلید پیکربندی‌شده (کلید برنامه و کلیدهای قبلی) حساب می‌کند، با hash_equals می‌سنجد و بعد expires را با ساعت چک می‌کند. این کد Illuminate\Routing\UrlGenerator است که از سورس framework خوانده شد.

چرخهٔ عمر یک لینک امضاشده و آنچه مهاجم بدون کلید می‌تواند یا نمی‌تواند:

1. Issue (server, has key)url = path + sorted query + expiressig = HMAC-SHA256(key, url)link = url + &signature=sig2. Client clicks the linkanyone holding the link can use ituntil expires; no login needed3. Verify (server)strip signature, rebuild urlhash_equals(HMAC(key,url), sig) then now <= expiresAttacker without the keyedits id or expires: HMAC differsguesses sig: 2^256 possibilities
issue   URL::temporarySignedRoute('invoices.download', now()->plus(minutes: 10), ['invoice' => 42])
  1  params = ksort([invoice=42, expires=1795627380])
  2  url    = https://app.test/invoices/42/download?expires=1795627380
  3  sig    = hex(HMAC-SHA256(APP_KEY, url))                       (64 hex chars)
  4  link   = url + "&signature=" + sig
verify
  5  strip signature from the received query; rebuild url
  6  hash_equals(hex(HMAC(APP_KEY, url)), received_sig)   -> else 403
  7  now > expires -> 403

سناریوی واقعی: ایمیل صورتحساب لینک /invoices/42/download?expires=...&signature=... دارد. عوض‌کردن ۴۲ به ۴۳ HMAC را می‌شکند. صبر تا بعد از expires هم رد می‌شود. فوروارد ایمیل به گیرنده هم دسترسی می‌دهد، که معاملهٔ هر bearer link است.

FeatureLaravelGo (signedurl/main.go)
CreateURL::signedRoute, URL::temporarySignedRouteSign(key, url, ttl, now)
Verify in a route->middleware('signed'), signed:relativeVerify(key, url, now)
Verify by hand$request->hasValidSignature(), hasValidSignatureWhileIgnoring(['page'])strip + recompute
Exclude host from the signed stringsignedRoute(..., absolute: false) + signed:relativesign the path only
KeyAPP_KEY (APP_PREVIOUS_KEYS accepted when verifying)any 32+ byte secret
Failure403 / InvalidSignatureExceptionerror values
ClockCarbon::now()->getTimestamp() > $expiresnow.Unix() > exp

خروجی اندازه‌گیری‌شدهٔ نسخهٔ Go (آزمایشگاه را ببینید): لینک معتبر می‌گذرد؛ در +۱۱ دقیقه expired or missing expires؛ ویرایش id باعث invalid signature می‌شود؛ امضا با کلید غلط هم invalid signature.

go
// HMAC-signed URLs with expiry: the same idea as Laravel's signed routes.
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/url"
	"strconv"
	"time"
)

// Sign appends expires and signature to a URL. Query keys are sorted by
// url.Values.Encode, which gives a canonical string to sign.
func Sign(key []byte, rawURL string, ttl time.Duration, now time.Time) (string, error) {
	u, err := url.Parse(rawURL)
	if err != nil {
		return "", err
	}
	q := u.Query()
	q.Set("expires", strconv.FormatInt(now.Add(ttl).Unix(), 10))
	u.RawQuery = q.Encode()
	q.Set("signature", mac(key, u.String()))
	u.RawQuery = q.Encode()
	return u.String(), nil
}

func mac(key []byte, msg string) string {
	m := hmac.New(sha256.New, key)
	m.Write([]byte(msg))
	return hex.EncodeToString(m.Sum(nil))
}

// Verify strips the signature, recomputes, compares in constant time, then
// checks expiry.
func Verify(key []byte, signed string, now time.Time) error {
	u, err := url.Parse(signed)
	if err != nil {
		return err
	}
	q := u.Query()
	got := q.Get("signature")
	q.Del("signature")
	u.RawQuery = q.Encode()
	if !hmac.Equal([]byte(mac(key, u.String())), []byte(got)) {
		return fmt.Errorf("invalid signature")
	}
	exp, err := strconv.ParseInt(q.Get("expires"), 10, 64)
	if err != nil || now.Unix() > exp {
		return fmt.Errorf("expired or missing expires")
	}
	return nil
}

func main() {
	key := []byte("0123456789abcdef0123456789abcdef") // demo key: use APP_KEY-style secret in real life
	now := time.Now()
	signed, _ := Sign(key, "https://app.test/invoices/42/download?user=7", 10*time.Minute, now)
	fmt.Println(signed)
	fmt.Println("valid        :", Verify(key, signed, now))
	fmt.Println("in 11 minutes:", Verify(key, signed, now.Add(11*time.Minute)))

	// Change the invoice id: the signature no longer matches.
	forged := "https://app.test/invoices/43/download?user=7" + signed[len("https://app.test/invoices/42/download?user=7"):]
	fmt.Println("edited id    :", Verify(key, forged, now))

	// Forge from scratch without the key: guess the HMAC with a wrong key.
	fake, _ := Sign([]byte("wrong key wrong key wrong key!!!"), "https://app.test/invoices/43/download?user=7", time.Hour, now)
	fmt.Println("wrong key    :", Verify(key, fake, now))
}
php
<?php

use App\Http\Controllers\InvoiceController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;

// routes/web.php: the middleware returns 403 for a bad or expired signature.
Route::get('/invoices/{invoice}/download', [InvoiceController::class, 'download'])
    ->name('invoices.download')
    ->middleware('signed');

// Ten-minute link for one invoice. Adds ?expires=<unix>&signature=<hex>.
$link = URL::temporarySignedRoute(
    'invoices.download',
    now()->plus(minutes: 10),
    ['invoice' => 42, 'user' => 7],
);

// A link with no expiry (e.g. unsubscribe).
$forever = URL::signedRoute('unsubscribe', ['user' => 7]);

// Relative variant: the host is not part of the signed string (useful behind changing hostnames).
$relative = URL::signedRoute('unsubscribe', ['user' => 7], absolute: false);
// ...and the route then needs ->middleware('signed:relative').

// Manual check, allowing a client-side parameter to be appended without breaking the signature.
Route::get('/export', function (Request $request) {
    abort_unless($request->hasValidSignatureWhileIgnoring(['page']), 403);

    return 'ok';
})->name('export')->middleware('throttle:30,1');

// What Laravel computes (Illuminate\Routing\UrlGenerator::signedRoute):
//   ksort($parameters);                     // sort query params by key
//   $url = route($name, $parameters);       // build the URL WITHOUT the signature
//   $signature = hash_hmac('sha256', $url, $appKey);   // $appKey is APP_KEY
//   return route($name, $parameters + ['signature' => $signature]);
// Verification rebuilds $url from the request (minus `signature`), recomputes the HMAC for APP_KEY
// and every APP_PREVIOUS_KEYS entry, and compares with hash_equals(); then checks `expires`.
function manualSignedUrl(string $url, string $key): string
{
    return $url.(str_contains($url, '?') ? '&' : '?').'signature='.hash_hmac('sha256', $url, $key);
}

امضای JWT ​

سه بخش، به‌صورت بایت حیاتی ​

به زبان ساده: JWT سه تکهٔ Base64url است که با نقطه به هم می‌چسبند: header که می‌گوید چگونه امضا شده، payload از claimها و signature روی دو تکهٔ اول. هر کس می‌تواند بخواندش؛ فقط صاحب کلید می‌تواند معتبرش را بسازد.

بدفهمی رایج: «امضا روی JSON decode‌شده است.» روی متن ASCII دقیق base64url(header) + "." + base64url(payload) است. برای همین serialize مجدد JSON (ترتیب یا فاصلهٔ متفاوت) token را باطل می‌کند و verify باید روی بایت‌های اصلی انجام شود.

تصویر اول: سه بخش، یک signing input، یک signature.

header{"alg":"EdDSA","kid":"2026-11"}payload (claims){"sub":"user-42","exp":1795627683,...}signature64 raw bytes, Base64urlsigning input = b64url(header) + "." + b64url(payload)ASCII bytes of the text, dot includedsign(key)HMAC / RSA / ECDSA / Ed25519Verifierpinned alg list, key by kid, check sig, then exp/nbf/iss/audNot encryptedanyone can Base64url-decode header and payloadtoken = header . payload . signature

تعریف: JSON Web Token مطابق RFC 7519. Compact serialization: BASE64URL(UTF8(header)) . BASE64URL(UTF8(payload)) . BASE64URL(signature). الگوریتم امضا با header به نام alg اعلام می‌شود (RFC 7518 برای HS/RS/ES/PS و RFC 8037 برای EdDSA). claimهای ثبت‌شده: iss صادرکننده، sub موضوع، aud مخاطب، exp زمان انقضا («on or after which the JWT MUST NOT be accepted»)، nbf not-before، iat issued-at و jti شناسهٔ token.

eyJhbGciOiJFZERTQSIsImtpZCI6IjIwMjYtMTEiLCJ0eXAiOiJKV1QifQ    header
 -> {"alg":"EdDSA","kid":"2026-11","typ":"JWT"}
eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwi...   payload
 -> {"iss":"https://auth.example.com","sub":"user-42","aud":["orders-api"],"exp":1795627683,"nbf":1795626783,"iat":1795626783}
irYKfOKdqtC6tVyGrH86zUjt1-kAtGfzOcC5ZELnpq3yXohLHalMbysbvADWSUWvfNj4fmqLHkRyIVMlMS5VDw   signature = 64 raw bytes (Ed25519)

JWT بدون امنیتِ RFC 7519 بخش ۶٫۱ حالت حدی است: header برابر {"alg":"none"} به eyJhbGciOiJub25lIn0 encode می‌شود و بخش signature رشتهٔ خالی است. طبق RFC قانونی است و اگر verifier بپذیردش فاجعه.

سناریوی واقعی: سرویس orders هدر Authorization: Bearer <jwt> را می‌گیرد، کلید عمومی را با kid پیدا می‌کند، verify می‌کند و بعد iss، aud و exp/nbf را با چند ثانیه leeway برای clock skew چک می‌کند. هیچ‌وقت سرویس auth را صدا نمی‌زند.

AlgorithmalgKeySignature sizeNotes
HMAC-SHA256HS256Shared secret, 32+ random bytes32 BFast; every verifier can also forge. RFC 7519: HS256 and none are the only MUST-implement algorithms
RSASSA-PKCS1-v1_5 SHA-256RS256RSA 2048+ pair256 B (2048-bit)Widest compatibility; large tokens
RSASSA-PSSPS256RSA pair256 BProbabilistic padding; less common
ECDSA P-256 SHA-256ES256P-256 pair64 B (r and s concatenated)Small; needs a good random k
EdDSA Ed25519EdDSAEd25519 pair64 BFast, deterministic, no per-signature random; RFC 8037

RFC 7519 می‌گوید HS256 و none را "MUST implement" و RS256 و ES256 را "RECOMMENDED" کرده؛ EdDSA اختیاری است و از RFC 8037 می‌آید، پس قبل از انتخاب، کتابخانهٔ خودتان و شرکایتان را بررسی کنید.

go
// Build an HS256 JWT by hand with stdlib only, to show the signature is
// HMAC-SHA256(key, base64url(header) + "." + base64url(payload)).
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
)

func main() {
	enc := base64.RawURLEncoding
	key := []byte("a-string-secret-at-least-256-bits-long")
	header := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
	payload := enc.EncodeToString([]byte(`{"sub":"user-42","exp":1900000000}`))
	signingInput := header + "." + payload
	m := hmac.New(sha256.New, key)
	m.Write([]byte(signingInput))
	sig := m.Sum(nil)
	fmt.Println("signing input:", signingInput)
	fmt.Printf("hmac hex     : %x\n", sig)
	fmt.Println("token        :", signingInput+"."+enc.EncodeToString(sig))
}
go
// JWT with EdDSA (Ed25519) using github.com/golang-jwt/jwt/v5: sign, verify,
// tamper, algorithm pinning, kid lookup.
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)
	keys := map[string]ed25519.PublicKey{"2026-11": pub} // kid -> public key (a tiny JWKS)

	claims := jwt.RegisteredClaims{
		Issuer:    "https://auth.example.com",
		Subject:   "user-42",
		Audience:  jwt.ClaimStrings{"orders-api"},
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		NotBefore: jwt.NewNumericDate(time.Now()),
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(15 * time.Minute)),
	}
	tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
	tok.Header["kid"] = "2026-11"
	signed, err := tok.SignedString(priv)
	if err != nil {
		panic(err)
	}
	fmt.Println(signed)

	// The three parts are just Base64url.
	parts := strings.Split(signed, ".")
	for i, name := range []string{"header", "payload", "signature"} {
		raw, _ := base64.RawURLEncoding.DecodeString(parts[i])
		if i < 2 {
			fmt.Printf("%-9s %s\n", name, raw)
		} else {
			fmt.Printf("%-9s %d bytes (Ed25519 = 64)\n", name, len(raw))
		}
	}

	keyFunc := func(t *jwt.Token) (any, error) {
		kid, _ := t.Header["kid"].(string)
		if k, ok := keys[kid]; ok {
			return k, nil
		}
		return nil, fmt.Errorf("unknown kid %q", kid)
	}
	parse := func(s string) error {
		_, err := jwt.Parse(s, keyFunc,
			jwt.WithValidMethods([]string{"EdDSA"}), // algorithm pinning
			jwt.WithIssuer("https://auth.example.com"),
			jwt.WithAudience("orders-api"),
			jwt.WithExpirationRequired(),
			jwt.WithLeeway(30*time.Second),
		)
		return err
	}
	fmt.Println("valid        :", parse(signed))

	// Tamper: change sub to admin in the payload, keep the old signature.
	payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
	evil := strings.Replace(string(payload), "user-42", "admin", 1)
	tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString([]byte(evil)) + "." + parts[2]
	fmt.Println("tampered     :", parse(tampered))

	// alg none: the classic attack. The pinned method list rejects it.
	none := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT","kid":"2026-11"}`)) + "." + parts[1] + "."
	fmt.Println("alg none     :", parse(none))

	// Expired token.
	old := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.RegisteredClaims{
		Issuer: "https://auth.example.com", Audience: jwt.ClaimStrings{"orders-api"},
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
	})
	old.Header["kid"] = "2026-11"
	oldSigned, _ := old.SignedString(priv)
	fmt.Println("expired      :", parse(oldSigned))
}

همان token با github.com/lestrrat-go/jwx/v3: الگوریتم و کلید در jwt.WithKey(jwa.EdDSA(), pub) به هم بسته می‌شوند، پس tokenی که الگوریتم دیگری را ادعا کند verify نمی‌شود. اندازه‌گیری: token دست‌کاری‌شده با signature verification failed for EdDSA: invalid EdDSA signature رد می‌شود.

go
// The same EdDSA token with github.com/lestrrat-go/jwx/v3: the key is bound
// to the algorithm at verification time via jwt.WithKey.
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"fmt"
	"time"

	"github.com/lestrrat-go/jwx/v3/jwa"
	"github.com/lestrrat-go/jwx/v3/jwt"
)

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)

	tok, err := jwt.NewBuilder().
		Issuer("https://auth.example.com").
		Subject("user-42").
		Audience([]string{"orders-api"}).
		IssuedAt(time.Now()).
		Expiration(time.Now().Add(15 * time.Minute)).
		Build()
	if err != nil {
		panic(err)
	}
	signed, err := jwt.Sign(tok, jwt.WithKey(jwa.EdDSA(), priv))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(signed))

	_, err = jwt.Parse(signed,
		jwt.WithKey(jwa.EdDSA(), pub), // algorithm and key are fixed here, not read from the token
		jwt.WithIssuer("https://auth.example.com"),
		jwt.WithAudience("orders-api"),
	)
	fmt.Println("valid   :", err)

	bad := append([]byte{}, signed...)
	bad[len(bad)-3] ^= 1
	_, err = jwt.Parse(bad, jwt.WithKey(jwa.EdDSA(), pub))
	fmt.Println("tampered:", err)
}
php
<?php

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

/** composer require firebase/php-jwt (EdDSA needs ext-sodium). */
class JwtEdDsa
{
    /** @param string $secretKey base64 of sodium_crypto_sign_secretkey() */
    public function __construct(
        private readonly string $secretKey,
        private readonly string $publicKey, // base64 of sodium_crypto_sign_publickey()
        private readonly string $kid = '2026-11',
    ) {
    }

    public function issue(int $userId): string
    {
        $now = time();

        return JWT::encode([
            'iss' => 'https://auth.example.com',
            'sub' => (string) $userId,
            'aud' => 'orders-api',
            'iat' => $now,
            'nbf' => $now,
            'exp' => $now + 900,
        ], $this->secretKey, 'EdDSA', $this->kid);
    }

    public function verify(string $jwt): object
    {
        // The algorithm comes from the Key object, never from the token header.
        $claims = JWT::decode($jwt, new Key($this->publicKey, 'EdDSA'));

        if ($claims->iss !== 'https://auth.example.com' || $claims->aud !== 'orders-api') {
            throw new \UnexpectedValueException('wrong issuer or audience');
        }

        return $claims;
    }

    public static function newKeyPair(): array
    {
        $pair = sodium_crypto_sign_keypair();

        return [
            'secret' => base64_encode(sodium_crypto_sign_secretkey($pair)),
            'public' => base64_encode(sodium_crypto_sign_publickey($pair)),
        ];
    }
}

حمله‌های alg: none و key confusion حیاتی ​

به زبان ساده: token می‌گوید برای بررسی‌اش از کدام الگوریتم استفاده شود. کتابخانهٔ بی‌دقت باور می‌کند و مهاجم ضعیف‌ترین گزینه را می‌نویسد.

بدفهمی رایج: «کتابخانه خودش مراقب است.» بعضی کتابخانه‌ها header را باور می‌کردند، بعضی سال‌ها پیش اصلاح شدند؛ و فراخوانی jwt.decode(token) خودتان بدون فهرست الگوریتم مجاز هنوز همان باگ است. RFC 8725 بخش ۳٫۱: کتابخانه‌ها "MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms" و "each key MUST be used with exactly one algorithm".

تعریف: RFC 8725 بخش ۲٫۱ دو حملهٔ کلاسیک را می‌آورد: الگوریتم "can be changed to 'none' by an attacker, and some libraries would trust this value and 'validate' the JWT without checking any signature"؛ و token با RS256 را می‌شود به HS256 تغییر داد تا verifier کلید عمومی RSA (که عمومی است) را راز HMAC بگیرد و مهاجم با آن token جعل کند (CVE-2015-9235 ذکر شده).

RS256 service, public key P is published at /.well-known/jwks.json
1  attacker: header {"alg":"HS256"}, payload {"sub":"admin"}
2  attacker: signature = HMAC-SHA256(key = P (public!), header.payload)
3  vulnerable verifier: key = P, alg = HS256 (from header) -> HMAC matches -> accepted
fix: verifier pins alg = RS256 for this key; HS256 never allowed with an RSA key

سناریوی واقعی: یک تست امنیتی {"alg":"none"} جعل می‌کند و سرویس می‌پذیرد. راه‌حل یک آرگومان است: jwt.WithValidMethods([]string{"EdDSA"}) در Go، new Key($pub, 'EdDSA') در firebase/php-jwt (الگوریتم در Key است نه در token).

خروجی اندازه‌گیری‌شده (jwtdemo): payload دست‌کاری‌شده token signature is invalid: ed25519: verification error می‌دهد؛ token با alg: none پیام token signature is invalid: signing method none is invalid؛ token منقضی token has invalid claims: token is expired.

AttackSymptomDefence
alg: noneToken with empty signature acceptedPin allowed algorithms; reject none
RS256 to HS256 key confusionPublic key used as HMAC secretOne algorithm per key; separate key types
Weak HS256 secretOffline brute force of the secret from one token32+ random bytes, not a word
Missing exp, aud, iss checksToken accepted by the wrong service or foreverRequire and validate them (WithExpirationRequired, WithAudience, WithIssuer)
kid injectionkid used in a file path or SQL queryTreat kid as a map key into a fixed set
jku / x5u header trustVerifier downloads the attacker's keyIgnore these headers; fetch keys only from configured URLs
Cross-JWT confusionAn ID token accepted as an access tokenDifferent aud, typ, and validation rules per token kind (RFC 8725 sections 2.8 and 3.12)

kid، JWKS و چرخش کلید مهم ​

به زبان ساده: kid («شناسهٔ کلید») می‌گوید کدام کلید شما این token را امضا کرده، تا بتوانید کلید را بچرخانید بی‌آنکه tokenهای زنده بشکنند. JWKS فایل JSON است که کلیدهای عمومی را در آن منتشر می‌کنید.

بدفهمی رایج: «چرخش یعنی کلید را عوض کن.» عوض‌کردن همهٔ tokenهای زنده را می‌کشد. چرخش یعنی: کلید جدید را اضافه کن، با آن امضا را شروع کن، کلید عمومی قدیمی را به‌اندازهٔ بیشینهٔ عمر token نگه دار، بعد حذفش کن.

تعریف: JWKS (RFC 7517) شکل {"keys":[{"kty":"OKP","crv":"Ed25519","kid":"2026-11","x":"..."}]} دارد و معمولاً در /.well-known/jwks.json است. Verifierها آن را cache می‌کنند و با دیدن kid ناشناخته دوباره می‌گیرند. header در JWT kid را می‌دهد؛ verifier آن را به کلیدی از یک مجموعهٔ ثابت نگاشت می‌کند و باز هم الگوریتم را چک می‌کند.

T0   keys = {k1}                       sign with k1
T1   keys = {k1, k2}  publish k2       verifiers fetch the JWKS
T2   sign with k2; k1 stays published  tokens signed by k1 still verify
T3   after max token lifetime + cache TTL: remove k1
ItemRule
Token lifetime5 to 15 minutes for access tokens; rotation cadence much longer than that
JWKS cacheHonour Cache-Control; refetch on unknown kid, with a rate limit
Emergency rotationRemove the key at once; accept that live tokens fail

امضا رمزنگاری نیست؛ JWE در یک نگاه مهم ​

به زبان ساده: token امضاشده مثل کارت‌پستالی با مهر ضدتقلب است: همهٔ مسیر می‌توانند بخوانندش. اگر claimها محرمانه‌اند، رمزشان کنید (JWE) یا در token نگذارید.

بدفهمی رایج: «JWT یعنی رمزشده.» تقریباً هر JWT در عمل JWS (امضاشده) است. JWE قالبِ پنج‌بخشیِ دیگری است.

تعریف: JWS = امضاشده (۳ بخش). JWE = رمزشده (۵ بخش: protected header، encrypted key، IV، ciphertext، tag). RFC 8725 بخش ۳٫۶ می‌گوید ورودی رمزنگاری را فشرده نکنید و دربارهٔ نشت plaintext از طول ciphertext هشدار می‌دهد. «nested JWT» اول امضا و بعد رمز می‌کند.

FormatPartsConfidentialityIntegrityWhere
JWS compact3noyesAlmost every access token
JWE compact5yesyes (AEAD)OIDC encrypted ID tokens, some B2B APIs
Opaque token1n/a (random, looked up)via the databaseSanctum, session IDs
PASETO v4.local3yesyesSee below

جایگزین‌های JWT: PASETO، Branca، Macaroons ​

PASETO مهم ​

به زبان ساده: PASETO همان JWT است که تله‌هایش برداشته شده: بدون فیلد alg، بدون none، بدون انتخاب الگوریتم. نسخه (v4) و هدف (local رمزشده، public امضاشده) دو بخش اول جداشده با نقطه‌اند و هر نسخه رمزنگاری را ثابت می‌کند.

بدفهمی رایج: «PASETO فقط یک serialization دیگر است.» نکته‌اش این است که token نمی‌تواند به verifier بگوید از چه الگوریتمی استفاده کند، پس حمله‌های downgrade و confusion وجود ندارند؛ خودِ کلید به یک هدف گره خورده است.

تعریف: v4.public.<base64url(message || signature)>[.<footer>] با Ed25519 امضا می‌کند؛ v4.local.<base64url(nonce || ciphertext || tag)>[.<footer>] با XChaCha20 رمز و با BLAKE2b دارای کلید احراز هویت می‌کند (spec کلید را با domain separation به paseto-encryption-key و paseto-auth-key-for-aead می‌شکند). footer اختیاری فراداده‌ای رمزنشده ولی احراز‌شده مثل kid دارد؛ «implicit assertion» زمینه‌ای را که در token نیست به آن گره می‌زند. سند rationale می‌گوید v4.local به‌خاطر key و message commitment از XChaCha20-Poly1305 به XChaCha20 به‌علاوهٔ BLAKE2b دارای کلید رفت: وقتی چند کلید متقارن وجود دارد "random-key robustness" مهم است.

v4.public.eyJleHAiOiIyMDI2LTEx...  .  eyJraWQiOiIyMDI2LTExIn0
 |  |      |                           |
 |  |      message + 64-byte signature  footer (base64url JSON {"kid":"2026-11"})
 |  purpose: public (signed) | local (encrypted)
 version: v4 = Ed25519 / XChaCha20 + BLAKE2b

اندازه‌گیری با aidanwoods.dev/go-paseto v1.6.0 (pasetodemo): token معتبر verify می‌شود (NewParser() قاعدهٔ NotExpired را اجرا می‌کند)؛ آخر token دست‌کاری‌شده با bad signature رد می‌شود؛ token نوع v4.local که به parser نوع public داده شود با message header `v4.local.' is not valid, expected `v4.public.' رد می‌شود.

QuestionJWTPASETO v4
Who picks the algorithm?The token header (must be pinned in code)The version string, fixed by the spec
Signed/encryptedJWS vs JWE, many algorithmspublic / local, one algorithm each
EcosystemEverywhere (gateways, IdPs, OIDC)Smaller; not part of OAuth/OIDC
Use it whenYou must interoperate: OIDC, third-party verifiersYou control both ends and want fewer ways to fail
go
// PASETO v4.public with aidanwoods.dev/go-paseto: no alg field to attack.
package main

import (
	"fmt"
	"strings"
	"time"

	"aidanwoods.dev/go-paseto"
)

func main() {
	secret := paseto.NewV4AsymmetricSecretKey()
	public := secret.Public()

	t := paseto.NewToken()
	t.SetSubject("user-42")
	t.SetIssuedAt(time.Now())
	t.SetNotBefore(time.Now())
	t.SetExpiration(time.Now().Add(15 * time.Minute))
	t.SetFooter([]byte(`{"kid":"2026-11"}`))
	signed := t.V4Sign(secret, nil)
	fmt.Println(signed)
	fmt.Println("prefix:", strings.SplitN(signed, ".", 3)[0]+"."+strings.SplitN(signed, ".", 3)[1])

	parser := paseto.NewParser() // checks exp/nbf/iat by default
	got, err := parser.ParseV4Public(public, signed, nil)
	fmt.Println("valid   :", err, string(got.ClaimsJSON()))

	tampered := signed[:len(signed)-4] + "AAAA"
	_, err = parser.ParseV4Public(public, tampered, nil)
	fmt.Println("tampered:", err)

	// A v4.local token cannot be fed to a public-key parser.
	local := paseto.NewV4SymmetricKey()
	enc := t.V4Encrypt(local, nil)
	_, err = parser.ParseV4Public(public, enc, nil)
	fmt.Println("wrong purpose:", err)
}

Branca و Macaroons، کوتاه تکمیلی ​

به زبان ساده: Branca یک token رمزشدهٔ ساده است (XChaCha20-Poly1305 با timestamp)، شبیه v4.local ولی spec دیگر. Macaroon یک bearer token است که می‌توانید بدون تماس با صادرکننده با افزودن caveat (محدودیت) باریکش کنید.

بدفهمی رایج: «Macaroon فقط JWT شیک است.» ویژگی تعریفی‌اش attenuation است: هر کس macaroon را دارد می‌تواند محدودیتی اضافه کند («فقط این فایل»، «تا ساعت ۱۷») و ردش کند؛ هرگز نمی‌تواند محدودیتی را بردارد. دارندهٔ JWT نمی‌تواند آن را باریک کند.

تعریف: Macaroonها از یک مقالهٔ پژوهشی گوگل می‌آیند («Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud»)؛ هر caveat یک زنجیرهٔ HMAC را ادامه می‌دهد و verify به کلید ریشه نیاز دارد و زنجیره را دوباره حساب می‌کند. صفحهٔ مقاله قابل دریافت نبود (HTTP 403)، پس این بند از آن نقل نشده است.

TokenCore ideaWhen
BrancaEncrypt + authenticate, timestamp insideOpaque but self-contained tokens in one org
MacaroonsHMAC chain, holder-added caveatsDelegation between services, capability-style access
BiscuitPublic-key tokens with Datalog policiesOffline-verifiable, attenuable (not covered here)

ذخیره و ابطال token، اشاره‌ها ​

QuestionShort answerLonger answer
Where does the browser keep it?HttpOnly, Secure, SameSite cookieWeb Sessions, Cookies & CORS
Can I revoke a JWT?Not directly: keep lifetimes short and add a denylist keyed by jti or a per-user "not before"JWT Deep Dive
Access vs refreshShort-lived access token, rotating refresh token stored hashedAuthentication, OAuth2, OIDC & SSO
Where do the keys live?KMS/HSM; the app asks to sign, never reads the keyCryptography, TLS, PKI & Secrets

رفتار هر محصول ​

Product / libraryPasswordsTokens and signaturesDefaults and gotchas
Laravel 13 Hash facadeHash::make/check/needsRehash/info; drivers bcrypt, argon, argon2idURL::signedRoute, temporarySignedRoute, signed middlewaredriver default bcrypt; bcrypt.rounds 12 (BCRYPT_ROUNDS); argon config 65536 KiB, 1 thread, time 4; class defaults 1024 KiB/2/2; verify true throws on algorithm mismatch; rehash_on_login true
Laravel Sanctumn/aPersonal access tokens: SHA-256 stored, `idplainformat,abilities, expires_at`
PHP corepassword_hash, password_verify, password_needs_rehash, PASSWORD_BCRYPT, PASSWORD_ARGON2IDhash_hmac, hash_equals, sodium_crypto_sign_*$2y$; Argon2 depends on how PHP was built
firebase/php-jwtn/aJWT::encode/decode, Key($k, 'EdDSA'), kid as 4th argumentAlgorithm is bound to the Key; EdDSA needs libsodium
Go x/crypto/bcryptGenerateFromPassword, CompareHashAndPassword, Costn/aDefault cost 10 (bcrypt.DefaultCost); ErrPasswordTooLong over 72 bytes; prefix $2a$
Go x/crypto/argon2IDKey(password, salt, time, memory, threads, keyLen)n/aRaw tag, no PHC encoding; memory in KiB
Go crypto/hmac, crypto/subtlen/ahmac.New, hmac.Equal, ConstantTimeCompareAlways compare MACs with hmac.Equal
golang-jwt/jwt/v5n/ajwt.Parse, WithValidMethods, WithAudience, WithIssuer, WithExpirationRequired, WithLeeway; SigningMethodEdDSAWithout WithValidMethods the Keyfunc must check t.Method
lestrrat-go/jwx/v3n/ajwt.Sign, jwt.Parse, jwt.WithKey(jwa.EdDSA(), key), JWKS and JWE support in the same moduleKey and algorithm are bound together at verification
aidanwoods.dev/go-paseton/aV4Sign, ParseV4Public, V4Encrypt, footer, implicit assertionNewParser() checks exp only; NewParserForValidNow() also checks nbf and iat
OpenSSL CLIopenssl passwd (legacy crypt/MD5/SHA-512 forms)openssl dgst -sha256 -hmac, openssl genpkey -algorithm ed25519Not a password-hashing tool for modern systems
htpasswd (Apache)-B bcrypt ($2y$), -C costn/aDefault is not bcrypt: pass -B
HIBP Pwned Passwordsk-anonymity range/{5 hex}n/aSend Add-Padding: true
Argon2 reference CLI/libargon2`echo -n pw./argon2 salt -id -t 3 -m 16 -p 4`n/a

سازوکار ​

درون bcrypt، Argon2 و HMAC ​

StepbcryptArgon2idHMAC-SHA256
Inputpassword (max 72 B), 16 B salt, costpassword, 16 B salt, m, t, p, tag lengthkey, message
SetupBlowfish "expensive key schedule" run 2^cost times over salt and keyFill m KiB of memory in p lanes with BLAKE2b-derived blocksPad key to 64 B, XOR with 0x36 and 0x5c
CoreEncrypt the constant "OrpheanBeholderScryDoubt" 64 timest passes; each 1 KiB block depends on earlier blocks (the first half of pass one data-independent, the rest data-dependent)`H(opad-key
Output23-byte hash printed as 31 charstagLength bytes (32 recommended)32 B
Why attackers sufferCost doubles per +1; small fixed memoryMemory per guess limits parallel GPU coresn/a: HMAC is fast, so only use it with high-entropy keys or inputs

ثابت رشته‌ای bcrypt و تاریخچهٔ پیشوند $2b$/$2y$ از تاریخچهٔ پیاده‌سازی OpenBSD و PHP است، نه از منابعی که برای این صفحه دریافت شد؛ ساختار Argon2 از RFC 9106 است (نمودار فشرده‌سازی G/GB و بخش‌های پارامتر خوانده شد).

نمای بایتی یک token نوع HS256 ​

signing input (ASCII, 83 bytes):
  65 79 4a 68 62 47 63 69 4f 69 4a 49 55 7a 49 31 4e 69 49 73 ...      "eyJhbGciOiJIUzI1NiIs..."
  ...2e...                                                              "." (0x2e)
  65 79 4a 7a 64 57 49 69 4f 69 4a 31 63 32 56 79 4c 54 51 79 ...      "eyJzdWIiOiJ1c2VyLTQy..."
HMAC-SHA256(key, signing input) = 05 f7 8f 8d 3c 83 af b6 4d 13 5c ed 86 de d8 32
                                  f5 25 53 59 ec 8a a2 b7 27 ca e1 9a 04 2e 2a dc
b64url(signature) = BfePjTyDr7ZNE1ztht7YMvUlU1nsiqK3J8rhmgQuKtw   (43 chars, no padding)

پیام‌های خطایی که می‌بینید ​

WhereMessage or codeMeaningFix
Go bcryptbcrypt: password length exceeds 72 bytesInput over 72 bytesCap length or pre-hash with Base64
Go bcryptcrypto/bcrypt: hashedSecret too short to be a bcrypted passwordNot a bcrypt hash (e.g. an MD5 row)Detect by prefix and route to the legacy path
Go bcryptcrypto/bcrypt: hashedPassword is not the hash of the given passwordWrong passwordReturn a generic login error
LaravelRuntimeException: This password does not use the Argon2i algorithm. (or bcrypt wording)verify is true and the stored hash uses another algorithmSet HASH_VERIFY=false during a migration
LaravelInvalidArgumentException: Value is too long to hash. Value must be less than 72 bytes.bcrypt.limit set and exceededValidate max length at the form
LaravelHTTP 403 InvalidSignatureExceptionSignature wrong or expiredCheck APP_KEY, host (signed:relative), ignored query parameters, clock
golang-jwttoken signature is invalid: signing method none is invalidalg: none rejectedExpected
golang-jwttoken signature is invalid: ed25519: verification errorPayload or signature changed, or wrong keyCheck key id and rotation
golang-jwttoken has invalid claims: token is expiredexp in the pastRefresh, check server clocks and leeway
golang-jwttoken is malformedNot three Base64url partsCheck for stripped Bearer, whitespace, URL-encoding
go-pasetomessage header `v4.local.' is not valid, expected `v4.public.'Wrong purpose for this parserUse the matching parser and key type
go-pasetobad signatureTampered or wrong keyAs for JWT

تنظیم cost روی ماشین خودتان ​

1  measure     go run ./bcryptcost      go run ./argon2bench
2  target      50-250 ms per hash on the production CPU, under realistic concurrency
3  memory      peak_concurrent_logins x m KiB must fit in RAM next to the app
4  set         BCRYPT_ROUNDS / ARGON_MEMORY / ARGON_TIME / ARGON_THREADS
5  deploy      new hashes use it; old ones are flagged by needsRehash and upgrade on login
6  protect     rate-limit login, bound the worker pool, so the hash cannot become a DoS lever

راه‌حل مسئله‌های کلاسیک ​

ProblemSolutionHowCost / limit
Legacy unsalted MD5/SHA-1 columnWrap now, replace on loginbcrypt(md5) or Argon2id(sha1) over the stored digest immediately; swap to Hash::make($plain) at next loginWrapped rows stay weak against a good wordlist until login
Raising the costRehash on loginneedsRehash then Hash::makeDormant users stay old: expire or force reset
bcrypt 72-byte limitReject or pre-hashbase64(HMAC-SHA256(pepper, pw)) before bcrypt; enforce max length otherwisePre-hash adds a key to manage
Pepper rotationPepper ID per rowStore pepper_id; verify with the stored ID, rehash with the newest at loginKeep old peppers until the last user moves
Password resetRandom token, hash, expire, single-useSQL UPDATE ... WHERE used_at IS NULL AND expires_at > now() RETURNINGEmail is the weak link
Email magic linktemporarySignedRoute with the user id15-minute expiry, one-time flag in the databaseSignature alone allows replay until expiry: add a nonce
Webhook verificationHMAC over the raw bodyConstant-time compare; reject timestamps older than 5 minutesNeed the exact raw bytes before JSON parsing
JWT key rotationkid plus JWKSAdd key, sign with new, retire old after max lifetimeCache TTL must be shorter than the overlap
JWT revocationShort life plus denylist by jtiRedis set with TTL equal to the remaining lifetimeA lookup per request defeats statelessness
Many verifiers, one issuerAsymmetric signatureEdDSA/ES256; verifiers get public keys onlySlightly larger tokens, key distribution
Login flood costs CPURate limit first, hash secondPer-IP and per-account throttles; bounded worker poolLegitimate users can be locked out
Leaked API keyRevoke and rotateDelete the digest row; the plaintext was never storedClients must be updated

جریان کامل توکن بازیابی ​

T1 user                                  T2 server
1  POST /forgot {email}
2                                         token = random(32 bytes); store sha256(token), expires_at = +30 min
3                                         email link https://app/reset?token=<token>
4  GET link, POST /reset {token, new_pw}
5                                         UPDATE password_resets SET used_at = now()
                                           WHERE token_hash = sha256($token) AND used_at IS NULL AND expires_at > now()
                                           RETURNING user_id
6                                         user_id returned? Hash::make(new_pw) ; revoke sessions
7                                         always answer "if the address exists we sent a mail"

مدیریت خطا و عیب‌یابی ​

SymptomLikely causeCheck
Every Laravel login throws after a driver changeHASH_VERIFY true and old rows use the previous algorithmPrefix of stored hashes ($2y$ vs $argon2id$)
Logins slow down at peakCost too high for concurrency, or Argon2 memory causes swappingCPU and RSS during a login burst; lower m or add workers
Argon2 memory seems ignored in PHPPHP built without Argon2 or memory below the library minimumphp -r 'var_dump(PASSWORD_ARGON2ID);'
Same password hashes differently every timeExpected: random saltUse Hash::check, never compare strings
Hash from PHP or htpasswd -B ($2y$) "fails" in GoUsually not the prefix (measured: Go verifies $2y$ hashes) but the stored value was truncated, re-encoded or longer than the columnCompare lengths: must be exactly 60 characters; use varchar(255)
Signed URL fails only in productionHost/scheme differs behind a proxy, or trailing slash, or key mismatch across serversTrusted proxies, signed:relative, same APP_KEY on all nodes
Signed URL fails after adding ?page=2Extra query parameter changed the signed stringhasValidSignatureWhileIgnoring(['page'])
JWT expired for fresh tokensClock skew between issuer and verifierNTP; add 30 to 60 seconds of leeway
JWT fails right after key rotationVerifier did not refetch JWKSRefetch on unknown kid, shorten cache
Token verifies in one service and not anotherDifferent aud or iss expectations, or algorithm listPrint the claims; compare validation options
Webhook signature never matchesHMAC computed over parsed JSON instead of the raw bodyHash the raw bytes

انتخاب ​

SituationUseExtra techniqueReason
New system, passwordsArgon2id, m at least 19 MiB, tuned to 50-250 msPepper in a vault, breach list, rehash on loginMemory-hard, current guidance
Existing bcrypt systemKeep bcrypt at cost 12 or higherCap at 72 bytes, migrate to Argon2id on loginMigrating costs little, staying is still acceptable
FIPS-only environmentPBKDF2-HMAC-SHA256, 600,000+ iterationsPepper, long minimum lengthOnly approved primitives
API keys, reset and session tokens256 random bits + SHA-256Show once, prefix, expiry, last-fourNothing to guess
Short-lived public linkHMAC-signed URL with expiresOne-time flag for sensitive actionsStateless, tamper-proof
Tokens between your own servicesEdDSA JWT or PASETO v4.publickid, JWKS, short lifeVerifiers cannot forge
Tokens to third parties / OIDCJWT with RS256 or ES256Publish JWKS, follow RFC 8725Interoperability
One process verifies its own tokensHS256 or PASETO v4.local32+ random bytes in a vaultSimplest
Claims must be secretDo not put them in a token, or use JWE / v4.localOpaque token with server-side dataSigning is not encryption

در معماری: از یک process تا سیستم توزیع‌شده ​

مونولیت (یک process، یک دیتابیس) ​

یک برنامهٔ Laravel: Hash::make هنگام ثبت‌نام، Hash::check به‌علاوهٔ needsRehash هنگام ورود، middleware signed روی مسیرهای unsubscribe و دانلود، توکن‌های Sanctum برای اپ موبایل. APP_KEY تنها رازی است که برای signed URL و کوکی رمزشده مهم است؛ پس باید روی همهٔ نودهای وب یکسان باشد و بیرون از repository بماند. مثال روزمره: لینک ایمیل فاکتور با URL::temporarySignedRoute('invoices.download', now()->plus(minutes: 30), ['invoice' => $id]). مثال production: فروشگاهی با ۵ ورود در ثانیه در اوج و Argon2id با ۶۴ MiB و ۴ thread؛ حدود ۲۰ hash هم‌زمان ۱٫۳ GiB RAM می‌خواهد، پس hash در workerهای php-fpm با pm.max_children محدود اجرا می‌شود.

مونولیت ماژولار / چند دیتابیس ​

ماژول identity مالک جدول users، تنظیمات hasher و pepper است؛ ماژول‌های دیگر هرگز hash نمی‌بینند، از identity می‌پرسند «این credential معتبر است؟» و user id می‌گیرند. کلیدها به‌ازای هر ماژول: کلید امضای token داخلی در config همان ماژول است نه .env مشترک. اگر ماژول‌ها دیتابیس مشترک دارند، فقط نقش identity حق SELECT روی password را بدهید. مثال روزمره: ماژول billing یک user id از identity می‌گیرد. مثال production: ستون pepper ID تا pepper جدید ماژول‌به‌ماژول بدون روز صفر پخش شود.

میکروسرویس‌ها ​

یک سرویس auth مرکزی JWT با EdDSA صادر می‌کند؛ هر سرویس دیگر آن را آفلاین با کلید عمومی از endpoint مربوط به JWKS verify می‌کند (JWT Deep Dive). فراخوانی بین سرویس‌ها mTLS اضافه می‌کند (mTLS Service Security)، چون token امضاشده ثابت می‌کند کاربر کیست نه اینکه کدام سرویس صدا می‌زند. جریان: gateway امضا، iss، aud و exp را verify می‌کند، X-User-Id تزریق می‌کند و سرویس‌های پایین‌دست یا فقط به gateway اعتماد می‌کنند یا دوباره verify می‌کنند. مثال روزمره: orders-service مقدار aud=orders-api را اعتبارسنجی می‌کند. مثال production: دریافت‌کنندهٔ webhook که HMAC-SHA256 را روی بدنهٔ خام با رازِ هر شریک و پنجرهٔ ۵ دقیقه‌ای timestamp verify می‌کند.

client -> gateway   Authorization: Bearer v4.public... or JWT(EdDSA, kid=2026-11)
gateway -> JWKS cache (refetch on unknown kid)  -> verify alg pinned, sig, iss, aud, exp
gateway -> orders-svc   X-User-Id: 42   (mTLS)
orders-svc -> payments-svc  service token (aud=payments-api, 60 s)

دادهٔ توزیع‌شده: replica، cache و ساعت ​

hashها مثل هر ستون دیگر replicate می‌شوند؛ خطرها جای دیگرند. Read replicaها lag دارند، پس گذرواژهٔ تازه‌تغییرکرده ممکن است لحظه‌ای هنوز با hash قدیمی verify شود: credential را از primary بخوانید و هنگام تغییر sessionها را باطل کنید. cache تصمیم‌های «token معتبر است» revocation را بی‌اثر می‌کند: TTL آن را از تحمل revocation کوتاه‌تر نگه دارید. ساعت برای exp، nbf و expiry لینک امضاشده مهم است: NTP همه‌جا و ۳۰ تا ۶۰ ثانیه leeway. در چندمنطقه‌ای، کلیدهای امضا در KMS هر منطقه یا KMS جهانی‌اند؛ JWKS را همهٔ مناطق سرو می‌کنند؛ چرخش کلید باید پیش از اولین token امضاشده با کلید جدید به همهٔ مناطق برسد. مثال روزمره: تغییر گذرواژه روی primary و ورود روی replicaِ عقب‌مانده. مثال production: denylist مربوط به JWT در Redis که به همهٔ مناطق با TTL برابر عمر باقی‌ماندهٔ token replicate می‌شود.

مسیر مقیاس ​

LoadWhat changes
1x: hundreds of usersFramework hasher, signed middleware, one APP_KEY
10x: tens of thousandsRate limits and a bounded hash worker pool; Argon2 memory sized to concurrency; Redis for throttling and denylists
100x: millionsDedicated auth service; EdDSA tokens and JWKS; pepper in KMS/HSM; hash on dedicated nodes so a login storm cannot starve the API; key rotation automated and observable
BeyondHardware-backed passkeys (WebAuthn) reduce password hashing to a legacy path; see Authentication

آزمایشگاه ​

همهٔ دستورها روی ماشین نویسنده اجرا شده‌اند (macOS، Apple M5، ۱۰ هسته، Go 1.27، OpenSSL 3). زمان‌های شما فرق می‌کند؛ همین هدف است. از پوشهٔ snippet یعنی docs/snippets/foundations/password-hashing-signed-tokens/go:

۱. اندازه‌گیری bcrypt با cost ۱۰، ۱۲ و ۱۴.

bash
go run ./bcryptcost
# cost=10      46ms  $2a$10$6Jr6H6anAOpl3fOqJFbmdeaJ6vHYPSQG4TrGrB8B9F5bSw2wVQ4IS
# cost=12     185ms  $2a$12$iNBODMKq...
# cost=14     741ms  $2a$14$QbhYKTC.w4...
# cost stored in hash: 12
# 73 bytes: bcrypt: password length exceeds 72 bytes true

هر +۲ زمان را حدود ۴ برابر می‌کند (۴۶، ۱۸۵، ۷۴۱ میلی‌ثانیه). cost با bcrypt.Cost از hash خوانده می‌شود.

۲. اندازه‌گیری Argon2id با حافظه‌های مختلف.

bash
go run ./argon2bench
# OWASP min 19 MiB t=2 p=1               17ms
# 64 MiB t=3 p=4 (RFC 9106 2nd)          37ms
# 256 MiB t=3 p=4                       156ms
# 1 GiB t=1 p=4                         182ms
# Laravel default 1 MiB t=2 p=2            0s

روی سخت‌افزار سریع، حداقل OWASP خیلی زیر هدف ۵۰ میلی‌ثانیه است: m را بالا ببرید تا زمان به بازه‌ای برسد که می‌توانید بپردازید.

۳. decode رشتهٔ PHC و مسیر ارتقا.

bash
go run ./phcbytes
# $argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$gduXp+Z6iReEolmbyHn5V8s1EtJzmEvZfYoY/Fn/AeI
# salt hex (16 bytes): 736f6d6573616c74736f6d6573616c74
go run ./phc
# old: $argon2id$v=19$m=19456,t=2,p=1$...   login ok: true rehashed: true
# new: $argon2id$v=19$m=65536,t=3,p=4$...   wrong password: false
echo -n 'c29tZXNhbHRzb21lc2FsdA==' | base64 -d | xxd     # 736f 6d65 7361 6c74 ... (add == back: the shell tool wants padding)
htpasswd -nbB -C 10 u hunter2      # u:$2y$10$...  (PHP-style prefix; Go's CompareHashAndPassword verifies it)

۴. شکستن یک فهرست MD5 ضعیف (فقط برای توضیح، فقط روی داده‌های نمونهٔ خودتان).

bash
go run ./crack
# bob  cracked: password
# cy   cracked: qwerty
# dee  not in wordlist          <- the 15-character random password survives
# ann  cracked: 123456
# md5 attack took 50.25µs
# bcrypt cracked: letmein
# bcrypt attack took 926ms for 8 guesses     <- every guess costs a full cost-12 hash

سه کاربر از چهار کاربرِ MD5 بدون salt در میکروثانیه می‌افتند؛ در برابر bcrypt با cost ۱۲ حتی هشت حدس حدود یک ثانیه است. مقیاس: wordlist مهاجم واقعی میلیاردها خط دارد.

۵. دست‌کاری JWT و دیدن شکست verify.

bash
go run ./jwtdemo
# header    {"alg":"EdDSA","kid":"2026-11","typ":"JWT"}
# payload   {"iss":"https://auth.example.com","sub":"user-42","aud":["orders-api"],"exp":...}
# signature 64 bytes (Ed25519 = 64)
# valid        : <nil>
# tampered     : token signature is invalid: ed25519: verification error
# alg none     : token signature is invalid: signing method none is invalid
# expired      : token has invalid claims: token is expired
printf '%s' 'eyJhbGciOiJub25lIn0' | base64 -d     # {"alg":"none"}

token نوع HS256 دست‌ساز را با OpenSSL مقایسه کنید: go run ./hs256 مقدار 05f78f8d...2adc را چاپ می‌کند؛ دستور printf '%s' 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwiZXhwIjoxOTAwMDAwMDAwfQ' | openssl dgst -sha256 -hmac 'a-string-secret-at-least-256-bits-long' همان ۶۴ نویسهٔ hex را می‌دهد.

۶. جعل signed URL بدون کلید.

bash
go run ./signedurl
# https://app.test/invoices/42/download?expires=1795627380&signature=dfa902d3...&user=7
# valid        : <nil>
# in 11 minutes: expired or missing expires
# edited id    : invalid signature
# wrong key    : invalid signature

۷. PASETO و پیشوند HIBP.

bash
go run ./pasetodemo     # valid / bad signature / wrong purpose
go run ./hibp           # send: .../range/5BAA6   keep: 1E4C9B93F3F0682250B6CF8331B7EE68FD8
printf '%s' password | openssl dgst -sha1     # 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

بدفهمی‌های رایج ​

باورواقعیت
«hash و رمزنگاری یکی‌اند»رمزنگاری با کلید برگشت‌پذیر است؛ hash گذرواژه یک‌طرفه است
«SHA-256 به‌علاوهٔ salt hash خوب گذرواژه است»salt جلوی جدول‌ها را می‌گیرد؛ سرعت هنوز به GPU میلیاردها حدس در ثانیه می‌دهد. hashِ کند و memory-hard بگیرید
«salt باید محرمانه باشد»عمومی است و در رشتهٔ hash ذخیره می‌شود؛ pepper رازدار است
«pepper از همه‌چیز محافظت می‌کند»فقط در برابر سرقتِ فقط-دیتابیس؛ اجرای کد روی app server آن را هم می‌خواند
«bcrypt هر طولی را می‌پذیرد»۷۲ بایت می‌خواند؛ بقیه نادیده گرفته (یا در Go رد) می‌شود
«$2y$ الگوریتم دیگری از $2a$ است»همان الگوریتم؛ پیشوند ثبت یک اصلاح پیاده‌سازی است و کتابخانه‌های جدید هر دو را می‌پذیرند
«thread بیشتر در Argon2 یعنی امنیت بیشتر»موازی‌سازی hash خودتان را سریع‌تر می‌کند؛ روی حافظه و پاس خرج کنید
«API key باید bcrypt شود»۲۵۶ بیت تصادفی فقط SHA-256 می‌خواهد؛ hash کند از انتخاب‌های ضعیف انسان محافظت می‌کند
«JWT رمزشده است»JWS فقط امضاشده است؛ هر کس payload را decode می‌کند
«header به نام alg می‌گوید چطور verify کنم»ورودیِ تحت کنترل مهاجم است؛ الگوریتم را در کد ثابت کنید
«== برای مقایسهٔ امضا کافی است»از hash_equals، hmac.Equal، subtle.ConstantTimeCompare استفاده کنید
«signed URL خصوصی است»bearer link است: در برابر ویرایش امضا شده، نه در برابر فوروارد
«قاعده‌های پیچیدگی گذرواژه را قوی می‌کنند»NIST ترکیب را ممنوع می‌کند؛ طول و فهرست نشتی
«با پاک‌کردن JWT می‌توانم آن را revoke کنم»دارنده تا exp امضای معتبر دارد؛ عمر کوتاه و denylist

چکیده ​

موضوعچه چیزی را به خاطر بسپارید
ذخیرهٔ گذرواژهکند، salt‌دار، memory-hard: Argon2id (حداقل ۱۹ MiB، t=2، p=1)، bcrypt با cost ۱۰+ برای میراث
Salt۱۶ بایت تصادفی برای هر کاربر، عمومی، داخل رشتهٔ hash
Pepperیک کلید HMAC رازی در vault؛ از نشت فقط-دیتابیس محافظت می‌کند؛ برای چرخش pepper ID ذخیره کنید
bcrypt۶۰ کاراکتر: $2y$10$ + ۲۲ salt + ۳۱ hash؛ سقف ۷۲ بایت؛ cost با +۱ دو برابر
قالب PHC در Argon2id$argon2id$v=19$m=65536,t=3,p=4$salt$tag، Base64 بدون padding
RFC 9106اول: t=1، p=4، ۲ GiB. دوم: t=3، p=4، ۶۴ MiB؛ salt ۱۲۸ بیتی، tag ۲۵۶ بیتی
RehashHash::needsRehash / password_needs_rehash پس از ورود موفق
مقایسههمیشه constant-time (hash_equals، hmac.Equal)
سیاست۱۵+ کاراکتر برای single-factor، بدون قاعدهٔ ترکیبی، ۶۴+ مجاز، نشتی‌ها رد (HIBP با k-anonymity، پیشوند ۵ کاراکتری)
توکن تصادفی۳۲ بایت تصادفی، یک بار نمایش، SHA-256 ذخیره، expiry، یک‌بارمصرف
Signed URLHMAC-SHA256 روی URL مرتب‌شده به‌علاوهٔ expires؛ signedRoute / temporarySignedRoute در Laravel؛ بدنه امضا نمی‌شود
JWTb64url(header).b64url(payload).b64url(sig)؛ امضا روی متن ASCII
الگوریتم‌های JWTHS256 راز مشترک؛ RS256/ES256/EdDSA جفت‌کلید؛ ثابتشان کنید؛ هرگز به alg اعتماد نکنید
بررسی‌های JWTامضا، exp، nbf، iss، aud، الگوریتم، kid از مجموعهٔ ثابت
PASETOv4.public (Ed25519) / v4.local (XChaCha20 + BLAKE2b)؛ بدون alg
امضا رمزنگاری نیستاگر claimها محرمانه‌اند JWE یا v4.local یا token مات

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چرا رمزکردن گذرواژه بدتر از hash کردن آن است؟ حیاتی ​

پاسخ

پاسخ: رمزنگاری برگشت‌پذیر است و کلید نزدیک داده است؛ دزدیده‌شدن یک کلید همهٔ گذرواژه‌ها را لو می‌دهد. hash یک‌طرفه مهاجم را مجبور می‌کند هر گذرواژه را حدس بزند.

۲ — در جدولِ نشت‌کرده دو کاربر hash یکسان دارند. چه چیزی کم بود؟ حیاتی ​

پاسخ

پاسخ: salt یکتا برای هر کاربر. با salt تصادفیِ یکتا همان گذرواژه hash متفاوت می‌دهد.

۳ — pepper را چه کسی باید بداند و کجا باشد؟ مهم ​

پاسخ

پاسخ: فقط لایهٔ برنامه، بیرون از دیتابیس در secrets manager یا HSM. از نشت فقط-دیتابیس محافظت می‌کند.

۴ — bcrypt با cost ۱۲ را ۱۸۵ میلی‌ثانیه اندازه گرفتید. برای cost ۱۳ چه انتظاری دارید و چرا؟ تکمیلی ​

پاسخ

پاسخ: حدود ۳۷۰ میلی‌ثانیه: cost لگاریتم دو تعداد roundهاست، پس هر +۱ کار را دو برابر می‌کند.

۵ — رشتهٔ $argon2id$v=19$m=65536,t=3,p=4$<salt>$<tag> را رمزگشایی کنید. تکمیلی ​

پاسخ

پاسخ: Argon2id، نسخهٔ 0x13 (۱۹)، ۶۴ MiB حافظه، ۳ پاس، ۴ lane، بعد salt به Base64 (بدون padding) و tag به Base64. salt ۱۶ بایتی ۲۲ کاراکتر است و tag ۳۲ بایتی ۴۳ کاراکتر.

۶ — ورود با hashی که پارامترهایش ضعیف‌تر از سیاست امروز است چگونه برخورد کند؟ مهم ​

پاسخ

پاسخ: بعد از verify موفق needsRehash را صدا بزنید و plaintext را با سیاست فعلی دوباره hash و رشتهٔ جدید را (به‌صورت compare-and-set) بنویسید. Laravel با rehash_on_login این را خودش انجام می‌دهد.

۷ — چرا برای API key SHA-256 و نه bcrypt؟ مهم ​

پاسخ

پاسخ: کلید ۲۵۶ بیت آنتروپی دارد، پس هیچ‌کس با هر سرعتی حدسش نمی‌زند؛ hash کند فقط هر درخواست را کند می‌کند.

۸ — signed URL در Laravel دقیقاً چه چیزی را امضا می‌کند و از چه چیزی محافظت نمی‌کند؟ حیاتی ​

پاسخ

پاسخ: HMAC-SHA256 روی URL کامل (query مرتب‌شده به‌علاوهٔ expires) با کلید برنامه. بدنهٔ درخواست را امضا نمی‌کند و جلوی استفادهٔ مجدد گیرنده از لینک تا قبل از انقضا را نمی‌گیرد.

۹ — حملهٔ key confusion از RS256 به HS256 و راه‌حلش را توضیح دهید. حیاتی ​

پاسخ

پاسخ: مهاجم alg را به HS256 تغییر می‌دهد و با کلید عمومی RSA به‌عنوان راز HMAC امضا می‌کند؛ verifierی که به header اعتماد کند می‌پذیرد. برای هر کلید یک الگوریتم را در کد ثابت کنید.

۱۰ — چرا alg: none خطرناک است و چگونه جلویش را بگیریم؟ حیاتی ​

پاسخ

پاسخ: RFC 7519 JWT بدون امنیت را تعریف کرده؛ verifierی که آن را بپذیرد tokenهای بدون امضا را قبول می‌کند. فهرست روش‌های مجاز (WithValidMethods) بدهید یا الگوریتم را در Key ثابت کنید.

۱۱ — دو دلیل وجود PASETO را بگویید. تکمیلی ​

پاسخ

پاسخ: فیلد alg برای حمله ندارد (نسخه رمزنگاری را ثابت می‌کند) و کلیدها به هدف (local یا public) گره خورده‌اند. v4.local ساختار key-committing هم دارد.

۱۲ — payload یک token حاوی ایمیل است؛ خصوصی است؟ حیاتی ​

پاسخ

پاسخ: نه. JWS متن Base64url است؛ از JWE یا v4.local استفاده کنید یا داده شخصی را در token نگذارید.

واژه‌نامه ​

اصطلاحمعنی
Hash (چکیده)اثرانگشت یک‌طرفهٔ هم‌اندازه از ورودی
Salt (نمک)مقدار تصادفی عمومی هر کاربر که با hash گذرواژه مخلوط می‌شود
Pepper (فلفل)کلید رازِ مشترک برای همهٔ hashها که بیرون از دیتابیس نگه داشته می‌شود
Work factor / cost (ضریب کار)زمان (و حافظه)ِ قابل تنظیم یک hash گذرواژه
bcrypthash تطبیقی گذرواژه بر پایهٔ Blowfish با سقف ورودی ۷۲ بایت
Argon2idhash memory-hard گذرواژه (RFC 9106)، ترکیب Argon2i و Argon2d
scryptKDF memory-hard با پارامترهای N، r، p
PBKDF2KDF تکرارشوندهٔ مبتنی بر HMAC، فقط CPU
PHC string (رشتهٔ PHC)قالب خودتوصیف $id$v=..$params$salt$hash
Rainbow table (جدول رنگین‌کمان)جدول پیش‌محاسبه‌شدهٔ hash به گذرواژه
Rehash on loginارتقای hashهای ذخیره‌شده وقتی کاربر دوباره احراز هویت می‌کند
Constant-time compare (مقایسهٔ زمان‌ثابت)مقایسه‌ای که مدتش به تعداد بایت‌های مطابق بستگی ندارد
HMAChash کلیددار (RFC 2104) برای یکپارچگی و اصالت
Signed URL (URL امضاشده)URL با امضای HMAC و انقضای اختیاری
k-anonymity range APIفقط پیشوند ۵ کاراکتری hash را بفرست و بقیه را محلی تطبیق بده
JWT / JWS / JWEقالب token؛ شکل امضاشده؛ شکل رمزشده
alg: noneJWT بدون امنیت با signature خالی
Key confusion (اشتباه کلید)استفاده از کلید عمومی به‌عنوان راز HMAC با عوض‌کردن alg
kidشناسهٔ کلید در header توکن
JWKSمجموعهٔ JSON کلیدهای عمومی منتشرشده
EdDSA / Ed25519امضای سریع و قطعی با امضای ۶۴ بایتی
exp / nbf / iatclaimهای انقضا، not-before و زمان صدور
PASETOتوکن‌های مستقل از پلتفرم: v4.public، v4.local
Brancaقالب ساده برای token رمزشده
Macaroonbearer token با زنجیرهٔ HMAC و caveatهای محدودکننده
Opaque token (توکن مات)شناسهٔ تصادفی که سمت سرور جست‌وجو می‌شود
Password shuckingاستفاده از hashهای سریعِ نشت‌کرده برای حمله به hashهای قوی‌تر ساخته‌شده روی آن‌ها

منابع ​

همه در ۲۰۲۶-۱۱-۲۵ دریافت و خوانده شده و در پوشهٔ sources به نام password-hashing-signed-tokens ذخیره شده‌اند.

ساخته‌شده توسط Morteza Negahi