Skip to content

Binary-to-Text Encoding: Base64, Base32, Hex, Percent-Encoding, Data URIs ​

"Base encoding visually hides otherwise easily recognized information, such as passwords, but does not provide any computational confidentiality." — S. Josefsson, RFC 4648, The Base16, Base32, and Base64 Data Encodings, Security Considerations (October 2006)

خلاصه (Summary): کدگذاری باینری-به-متن (Binary-to-Text Encoding) بایت‌های دلخواه را به الفبایی محدود از نویسه‌های قابل‌چاپ تبدیل می‌کند تا از کانال‌هایی که فقط متن حمل می‌کنند رد شوند؛ هزینه‌اش حجم است، هیچ‌وقت محرمانگی نمی‌آورد، و هر مرز (URL، JSON، header، ایمیل، HTML) نسخه و باگ مخصوص خودش را دارد. تمرکز (Focus): Hex، Base64 و base64url، Base32 (Crockford و z-base-32)، Base58، Base85، percent-encoding و تله‌ٔ + در برابر %20، IRI و Punycode، data URI، quoted-printable، escape در HTML و JSON، رفتار Go و PHP و JavaScript و Laravel، و باگ‌های کلاسیک. هدف یادگیری (Learning goal): برای هر مرز کدگذاری درست را انتخاب کنید، حجم خروجی را پیش‌بینی کنید، ورودی نامطمئن را امن decode کنید، یک مقدار Base64 را در JWT و Kubernetes Secret و header Authorization تشخیص بدهید، و باگ «plus تبدیل شد به space» را در کمتر از یک دقیقه درست کنید.

این صفحه مرجع کامل کدگذاری‌هایی است که بین بایت خام و کانال متنی می‌نشینند. خودِ کدگذاری‌ها و تله‌هایشان اینجا است؛ بایت و UTF-8 در Bits, Bytes & Text Encoding، قالب داده در Serialization Formats، فشرده‌سازی در Compression، اثر انگشت داده در Checksums & Hashing، رمزنگاری در Cryptography Fundamentals، امضای token در Password Hashing & Signed Tokens و حل نام‌های Punycode در DNS Resolution for Developers آمده است. معرفی API زبان Go در JSON, XML, Struct Tags, Encoder/Decoder, Base64 است.

نقشهٔ صفحه (Page map) ​

If you are looking forGo to
One table to memorise: encoding, alphabet, size cost, where it is usedEverything in one minute
Why bytes cannot just be pasted into JSON, URLs or headersWhy it exists
uuencode, MIME, RFC 4648, RFC 3986, Punycode, JWSWhere it comes from
Hex and Base16Hex
6-bit groups, alphabet, = padding, 33% overhead, 76-column linesBase64, Padding
- and _, padding in URLs, JWT segmentsBase64url
Why two libraries disagree on the same stringDecoding leniency
TOTP secrets, Crockford, z-base-32, base32hexBase32
Bitcoin addresses, no 0OIlBase58
Ascii85, git binary patches, PDFBase85
Reserved vs unreserved, UTF-8 bytes, %XXPercent-encoding
+ vs %20, double encoding, path vs query vs fragmentPlus vs space, Double encoding, Components
Persian characters in URLs and domains, IDNAIRI and Punycode
HTML entities, JSON string escapesHTML and JSON
data: URLs, size, CSPData URIs
MIME bodies and headersQuoted-printable, uuencode
"It is encoded, so it is safe"Not encryption
JWT, Kubernetes Secrets, Basic auth, src, Git LFS, ProtobufWhere each one shows up
Go, PHP, JavaScript, Laravel, CLI tools side by sidePer-language behaviour
Bit math, lengths, speed, error messagesMechanics
Code for every classic bugSolving the classic problems
Which encoding for which jobChoosing
Monolith to distributed systemsIn architecture
Symptom to causeTroubleshooting
Hands-onLab
Wrong beliefs, cheat sheet, definitionsMisconceptions, Cheat sheet, Self-check, Glossary

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

کدگذاری‌ها. هر ردیف در فهرست مفاهیم باز می‌شود. نسبت‌ها یعنی حجم خروجی تقسیم بر حجم ورودی؛ جاهایی که اندازه‌گیری شده روی همین ماشین و روی رشتهٔ ۱۷ بایتی فارسی بوده است.

EncodingAlphabetOutput sizeTypical home
Hex / Base160-9A-F (or lower case)2.00xHashes, colours, byte dumps, UUIDs, Laravel signature
Base64A-Z a-z 0-9 + /, pad =4 chars per 3 bytes, about 1.33x (1.37x with MIME lines)JSON, XML, e-mail, Authorization: Basic, Kubernetes Secrets, data URIs
Base64 raw (unpadded)same, no =about 1.33xCompact tokens
Base64urlA-Z a-z 0-9 - _about 1.33xJWT, URL parameters, cookies, filenames
Base32A-Z 2-7, pad =8 chars per 5 bytes, 1.6xTOTP secrets, case-insensitive systems
Crockford / z-base-32no ILOU, or a shuffled alphabet1.6xHuman-typed IDs, ULID
Base58no 0 O I l + /about 1.37xBitcoin addresses, short IDs
Base85 / Ascii8585 printable characters5 chars per 4 bytes, 1.25xPDF, PostScript, git binary patches
Percent-encoding%XX per byte1x to 3x (3x for each non-unreserved byte)URLs, forms
Quoted-printablemostly literal, =XX otherwise1x to 3xMIME text bodies and headers
HTML entities / JSON escapes&, \n, \uXXXXdepends on contentHTML text, JSON strings
Punycodexn-- + ASCIIabout 1xInternationalized domain names

سه چیزی که باید به خاطر بسپارید.

SituationDo this
Putting bytes in a URL, cookie, filename or JWTbase64url without padding, and still percent-encode if the value goes in a query string you build by hand
Putting bytes in JSON, XML or e-mailstandard Base64; expect +33%
Someone says "it is encoded, so it is safe"It is not. Base64 is a reversible spelling, not a lock (Not encryption)

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

کامپیوترها بایت جابه‌جا می‌کنند، اما خیلی از لوله‌ها برای متن ساخته شده‌اند. ایمیل در اینترنت اولیه ۷ بیتی (7-bit) و US-ASCII بود و طول خط محدود داشت؛ یک بایت صفر یا خطی که فقط یک نقطه باشد می‌توانست پیام را خراب کند. رشتهٔ JSON باید Unicode معتبر باشد و بایت خام 0xFF در آن جا نمی‌شود. URL مجموعهٔ کوچکی نویسهٔ مجاز و چند نویسهٔ «ساختاری» دارد. header در HTTP یک خط متن است؛ مقدار cookie فاصله، نقل‌قول، ویرگول، نقطه‌ویرگول و backslash نمی‌پذیرد. متغیر محیطی یک رشتهٔ C است و در اولین بایت صفر تمام می‌شود. RFC 4648 انگیزهٔ اولیه را این‌طور می‌گوید: کدگذاری پایه برای ذخیره یا انتقال داده در محیط‌هایی است که «شاید به دلایل قدیمی» به US-ASCII محدودند، و در برنامه‌های جدید هم چون امکان کار با ویرایشگر متن را می‌دهد.

کدگذاری باینری-به-متن همان قراردادی است که این را امن می‌کند: الفبایی انتخاب کن که همهٔ کانال‌ها آن را داده‌ٔ ساده ببینند و بایت‌ها را برگشت‌پذیر به آن نگاشت کن. بهایش حجم است و معاملهٔ اصلی بین محدود بودن الفبا و تعداد بایت‌های هدررفته است.

Bigger alphabet (fewer characters)Smaller alphabet (more characters)
Base85: 1.25x, but uses quotes, backslash, angle bracketsHex: 2x, but only 0-9a-f, the safest alphabet there is
Base64: 1.33x, but +, /, = are special in URLsBase32: 1.6x, but case-insensitive and typeable
Shorter outputSurvives more channels, fewer escaping rules
Needs a second layer when a delimiter is in the alphabetWorks almost everywhere unchanged

تمثیلی که در این صفحه تکرار می‌کنیم: پیکی که فقط نامهٔ چاپی می‌پذیرد. می‌خواهید یک آجر بفرستید. پیک آجر نمی‌برد، فقط کاغذ. پس نامه‌ای می‌نویسید که آجر را تکه‌تکه با یک الفبای ثابت توصیف می‌کند و گیرنده از روی نامه آجر را بازسازی می‌کند. هیچ چیز در نامه آجر را پنهان نمی‌کند: هر کس نامه را بخواند می‌تواند آجر را بسازد. هر پیک نامهٔ متفاوتی می‌خواهد (پیک URL نامه‌ای با / را رد می‌کند؛ پیک ایمیل خط‌های زیر ۷۶ نویسه می‌خواهد)، پس باید بدانید از کدام پیک استفاده می‌کنید.

سه بدفهمی رایج، از همان ابتدا ​

  1. «Base64 داده را امن یا محرمانه می‌کند.» فقط آن را قابل‌انتقال می‌کند. هر کس با یک دستور آن را برمی‌گرداند. هرگز برای رمز عبور، token محرمانه یا «مبهم‌سازی» کلید API استفاده نکنید.
  2. «Base64 یک چیز است.» دست‌کم پنج املا هست: استاندارد با padding، استاندارد بدون padding، base64url با و بدون padding، و نسخهٔ MIME با خط‌شکن. مقدار یکی در decoder دیگری خطا می‌دهد یا بی‌صدا خراب می‌شود.
  3. «URL encoding یک چیز است.» %20 در path و RFC 3986 درست است؛ + برای فاصله فقط در application/x-www-form-urlencoded (فرم‌های HTML و query که مثل فرم خوانده می‌شود) درست است. قاطی کردنشان رایج‌ترین باگ کدگذاری در وب است.

از کجا آمده ​

YearEventSource
1980uuencode/uudecode written by Mary Ann Horton at UC Berkeley so binary files could pass through e-mail and UsenetWikipedia (secondary source; not verified against a primary text)
1996MIME (RFC 2045, November 1996) defines the Content-Transfer-Encoding header with the Base64 and quoted-printable encodings, and the 76-character line limitRFC 2045
1998data: URL scheme (RFC 2397, August 1998), "only useful for short values"RFC 2397
2003Punycode (RFC 3492, March 2003) for Internationalized Domain Names in ApplicationsRFC 3492
2003 to 2006RFC 3548 (July 2003) then RFC 4648 (October 2006) standardise Base16, Base32, Base64 and add the URL and filename safe alphabetRFC 3548, RFC 4648
2005RFC 3986 (January 2005) defines URI syntax, reserved and unreserved characters and percent-encoding; RFC 3987 (January 2005) adds IRIsRFC 3986, RFC 3987
2015JSON Web Signature (RFC 7515, May 2015) fixes JWT segments as base64url without padding; RFC 7617 (September 2015) defines Basic auth as Base64 of user:passwordRFC 7515, RFC 7617
2025 to 2026JavaScript gains native Uint8Array.prototype.toBase64 and toHex; Node 26 on this machine reports both as functionsobserved with node -e (Node v26.10.0)

دو واژه برای ادامه لازم است. RFC 4648 بازگروه‌بندی ۶ بیتی را quantum می‌نامد و RFC 3986 شکل %XX را pct-encoded: pct-encoded = "%" HEXDIG HEXDIG. استاندارد WHATWG URL آن چیزی است که مرورگرها واقعاً پیاده می‌کنند؛ جایی که با RFC 3986 فرق دارد (مثلاً + برای فاصله در فرم) صریح گفته می‌شود.

3 input bytes = 24 bits = 4 groups of 6 bits = 4 output characters0100110101100001011011100x4D 'M'0x61 'a'0x6E 'n'010011= 19alphabet[19]T010110= 22alphabet[22]W000101= 5alphabet[5]F101110= 46alphabet[46]u1 byte left over: 2 chars + "==" · 2 bytes left over: 3 chars + "=" · output length = 4 x ceil(n / 3)Base64url swaps "+" (62) and "/" (63) for "-" and "_" and usually drops the "=".

نمودار بالا چیدمان بیتی را نشان می‌دهد: سه بایت M a n که ۲۴ بیت‌اند، به چهار گروه ۶ بیتی با مقدارهای ۱۹ و ۲۲ و ۵ و ۴۶ تقسیم می‌شوند و هرکدام اندیس یک نویسه در الفبا است: TWFu.

فهرست مفاهیم ​

هر بلوک همین ترتیب را دارد: به زبان ساده، بدفهمی رایج، تعریف دقیق، یک timeline کوتاه، سناریوهای واقعی، رفتار هر محصول و راه‌حل که به کد در حل مسئله‌های کلاسیک لینک می‌شود.

Hex / Base16 حیاتی ​

به زبان ساده: هر بایت را با دو نویسه از 0-9 و a-f بنویسید. بایت 0xD8 می‌شود متن d8.

بدفهمی رایج: «Hex مال عددها است.» ارزان‌ترین راه نمایش هر بایتی است: یک بایت همیشه دقیقاً دو نویسه است، پس آفست‌ها را با چشم می‌خوانید و هیچ بایتی با ساختار اشتباه نمی‌شود. حروف بزرگ و کوچک یک مقدارند؛ RFC 4648 می‌گوید Base16 همان hex «بدون حساسیت به حروف» است و padding نمی‌خواهد چون «همیشه یک کلمهٔ کد کامل در دست است».

تعریف: Base16 (بخش ۸ از RFC 4648) هر nibble چهاربیتی را به یکی از 0123456789ABCDEF می‌برد؛ دو nibble یک بایت است؛ خروجی دقیقاً دو برابر ورودی است.

text
input bytes      4d 61 6e              "Man"
as hex           4d616e                (6 chars for 3 bytes)
upper-case       4D616E                same value
persian "سلام"   d8b3 d984 d8a7 d985   (8 bytes in UTF-8, 16 hex chars)

سناریوهای واقعی: digest مثل SHA-256 در ۶۴ نویسهٔ hex؛ رنگ‌های CSS مثل #1e90ff؛ UUID؛ خروجی xxd و hexdump؛ MAC address؛ پارامتر signature در signed URL لاراول؛ فعل %x در Go؛ شناسه‌های شیء Git؛ دیباگ پروتکل در Wireshark.

ProductHex helpersCase
Goencoding/hex (EncodeToString, DecodeString, Dump), fmt %xEncodes lower case; decodes both
PHPbin2hex, hex2bin, dechexbin2hex lower case; hex2bin accepts both
JavaScriptUint8Array.prototype.toHex (a function in Node 26 here), Buffer.toString('hex')lower case
PostgreSQLencode(bytea, 'hex'), \x input formatlower case
CLIxxd, xxd -p, hexdump -C, openssl dgstlower case

راه‌حل / نحوهٔ استفاده: digestها را بی‌توجه به حروف و در زمان ثابت مقایسه کنید؛ رشتهٔ hex محرمانه را با == ساده مقایسه نکنید. Go: encodings. PHP: hash_equals(strtolower($a), strtolower($b)).

Base64 حیاتی ​

به زبان ساده: بایت‌ها را به تکه‌های ۶ بیتی ببرید و هر تکه را با یک نویسه از الفبای ۶۴ حرفی بنویسید. سه بایت (۲۴ بیت) دقیقاً چهار نویسه می‌شود.

بدفهمی رایج: «علامت‌های = بخشی از داده‌اند.» نه؛ پرکننده‌اند تا طول مضرب ۴ شود. داده فقط در حرف‌هاست.

تعریف (بخش ۴ از RFC 4648): الفبا A-Z (۰ تا ۲۵)، a-z (۲۶ تا ۵۱)، 0-9 (۵۲ تا ۶۱)، + (۶۲)، / (۶۳) و = برای pad است. سه بایت ورودی یک گروه ۲۴ بیتی است که به چهار مقدار ۶ بیتی تقسیم می‌شود. طول خروجی برای n بایت 4 * ceil(n / 3) است، یعنی حدود 1.33 * n.

text
bytes   M=0x4D      a=0x61      n=0x6E
bits    01001101    01100001    01101110
6-bit   010011 010110 000101 101110
value   19     22     5      46
char    T      W      F      u        -> "TWFu"

سناریوهای واقعی: تصویر داخل پاسخ JSON؛ پیوست PDF در ایمیل؛ گواهی TLS در فایل PEM؛ کلید عمومی SSH؛ مقدار Kubernetes Secret؛ فیلد auth در Docker config؛ header Authorization: Basic؛ تگ img با data: URL؛ فیلد bytes در Protobuf که به JSON می‌رود.

ProductStandard encoderOutput has line breaks?
Go encoding/base64StdEncodingNo (the decoder skips CR and LF)
PHPbase64_encodeNo
JavaScript browserbtoa (binary string only), Uint8Array.toBase64()No
Node.jsBuffer.from(x).toString('base64')No
Pythonbase64.b64encodeNo (encodebytes adds \n every 76)
GNU coreutils base64wraps at 76 by default; -w 0 disablesYes
macOS base64no wrapping by default (measured here)No
openssl base64wraps at 64; -A for one lineYes
JavaBase64.getEncoder() plain, getMimeEncoder() 76 with CRLFOnly for MIME

راه‌حل / نحوهٔ استفاده: همیشه به طرف مقابل بگویید کدام base64 را استفاده کرده‌اید (استاندارد، url-safe، با padding، خط‌شکسته). در API در schema مستند کنید. کد: encodings.

Padding و Base64 «خام» (Raw) مهم ​

به زبان ساده: وقتی طول ورودی مضرب ۳ نیست، گروه آخر کوتاه است و نویسه‌های = خروجی را تا مضرب ۴ پر می‌کنند. بعضی سیستم‌ها = را حذف می‌کنند چون decoder طول گم‌شده را حساب می‌کند.

بدفهمی رایج: «padding الزامی است، پس رشتهٔ بدون آن خراب است.» RFC 4648 بخش ۳.۲ می‌گوید پیاده‌سازی‌ها باید pad بگذارند «مگر آنکه مشخصهٔ ارجاع‌دهنده صریحاً چیز دیگری بگوید»؛ و JWS صریحاً چیز دیگری می‌گوید. هر دو شکل مشروع‌اند؛ هر decoder فقط همان را می‌پذیرد که تنظیم شده است.

تعریف: با ۱ بایت باقی‌مانده خروجی ۲ نویسه به‌علاوهٔ == است؛ با ۲ بایت باقی‌مانده ۳ نویسه به‌علاوهٔ =؛ با صفر باقی‌مانده هیچ padding نیست. طول شکل بدون padding ceil(4n / 3) است. طول بدون padding به پیمانهٔ ۴ همیشه ۰ یا ۲ یا ۳ است؛ باقی‌مانده ۱ هرگز معتبر نیست.

text
input   "hi!"  3 bytes   -> aGkh     (no pad)
input   "hi"   2 bytes   -> aGk=     (1 pad)
input   "h"    1 byte    -> aA==     (2 pads)
unpadded forms           -> aGk   aA
decoder sees "aGk" and the length 3 mod 4 -> it knows exactly one '=' is missing

سناریوهای واقعی: JWT که در یک کتابخانه رد می‌شود چون = می‌خواهد؛ امضایی در URL که = باید %3D می‌شد؛ hash که با و بدون padding در دو جدول ذخیره شده و lookup خطا می‌دهد؛ secret webhook که برنامهٔ چت = آخرش را برداشته.

DecoderPadded inputUnpadded input
Go StdEncodingacceptedrejected (illegal base64 data)
Go RawStdEncodingrejectedaccepted
PHP base64_decode (also strict)acceptedaccepted (the php-src source says it accepts zero padding)
WHATWG atobacceptedaccepted unless length mod 4 is 1
Python b64decodeacceptedbinascii.Error: Incorrect padding
Node Buffer.from(s, 'base64')acceptedaccepted
Java Base64.getDecoder()acceptednot tested here (no JDK on this machine); check the Javadoc of your version

راه‌حل: در مرز خودتان نرمال کنید: با گونه‌ای که مستند کرده‌اید decode کنید و پیش از مقایسه دوباره pad کنید یا بردارید. حل مسئله‌های کلاسیک.

Base64url (امن برای URL و نام فایل) حیاتی ​

به زبان ساده: همان کدگذاری، با - به جای + و _ به جای /، معمولاً بدون =، تا نتیجه بدون escape در URL و نام فایل بنشیند.

بدفهمی رایج: «base64url الگوریتم دیگری است.» همان نگاشت بیتی است با دو نویسهٔ عوض‌شده. RFC 4648 بخش ۵ می‌گوید این کدگذاری را نباید فقط «base64» نامید.

تعریف: الفبای جدول ۲ از RFC 4648: A-Z a-z 0-9 - _. همان RFC می‌گوید = در URI معمولاً percent-encode می‌شود، اما اگر طول داده ضمنی معلوم باشد می‌شود padding را حذف کرد. JWS شکلی را که JWT استفاده می‌کند ثابت کرده: base64url با حذف همهٔ = پایانی و بدون خط‌شکن و فاصله.

text
standard : ++++//4=            <- '+' becomes a space in a query string, '/' splits a path
base64url: ----__4             <- safe in a path, query, cookie, filename
JWT      : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiI0MiJ9 . D7xYjF12...
             header (base64url)                      payload          signature

سناریوهای واقعی: سه بخش JWT؛ code_challenge در OAuth PKCE (RFC 7636)؛ لینک‌های کوتاه با شناسهٔ تصادفی؛ token بازیابی رمز در لینک ایمیل؛ کلید شیء‌هایی که از hash ساخته می‌شوند.

Productbase64url API
Gobase64.URLEncoding, base64.RawURLEncoding (no padding)
PHPno built-in: rtrim(strtr(base64_encode($s), '+/', '-_'), '=')
JavaScript / NodeBuffer.toString('base64url'); Uint8Array.toBase64({alphabet: 'base64url'})
Pythonbase64.urlsafe_b64encode (pads)
JavaBase64.getUrlEncoder().withoutPadding()
PostgreSQLencode(x, 'base64url') appears in the PostgreSQL 19 documentation I read

راه‌حل: برای هر چیزی که به URL، cookie یا نام فایل می‌رسد base64url بگیرید؛ Base64 استاندارد را برای بدنه نگه دارید. کد: urlbug.

Binary bytes must travel as textWho/what reads it?A human types itBase32 (RFC 4648) / CrockfordA URL, cookie, filenamebase64url, no paddingJSON, e-mail, data URIstandard base64 (+33%)Hash or ID printed for debugging: hex (+100%)Can you avoid text? Use bytes (Protobuf, multipart)typed by peoplein mail / JSONin URL

سخت‌گیری decoder (Leniency): یک رشته، چند جواب مهم ​

به زبان ساده: decoderها در چیزهایی که می‌بخشند فرق دارند: فاصله، خط‌شکن، = گم‌شده، نویسهٔ اضافی، الفبای اشتباه و بیت‌های ته‌مانده‌ٔ غیرصفر.

بدفهمی رایج: «اگر decode شد، معتبر است.» بعضی decoderها نویسه‌های ناشناس را بی‌صدا دور می‌ریزند، پس ورودی خراب یا مخرب ممکن است به چیز کوتاه‌تر یا متفاوتی decode شود و بررسی امضا یا مقایسهٔ رشته را بشکند.

تعریف: RFC 4648 بخش ۳.۳ می‌گوید پیاده‌سازی‌ها باید ورودی دارای نویسهٔ خارج از الفبا را رد کنند، مگر مشخصهٔ ارجاع‌دهنده صریحاً چیز دیگری بگوید؛ MIME چیز دیگری می‌گوید («در پذیرش آزاد باش»). forgiving-base64 decode استاندارد WHATWG که atob استفاده می‌کند سیاست سوم است: فاصله‌های ASCII را بردار، یک یا دو = پایانی را اگر طول مضرب ۴ است بردار، اگر طول به پیمانهٔ ۴ برابر ۱ است شکست بده، و با هر نویسهٔ خارج از الفبا شکست بده.

text
Input "aGk"  decoded as standard base64:
  Go StdEncoding    -> error
  Go RawStdEncoding -> "hi"
  Python b64decode  -> binascii.Error: Incorrect padding
  PHP strict        -> "hi"
  atob / Node       -> "hi"
Input "-_-_" (url alphabet) decoded as standard:
  Go StdEncoding    -> error         Python b64decode -> b'' (silently empty)
  atob              -> InvalidCharacterError    Node Buffer -> bytes fbffbf (accepts both)

سناریوهای واقعی: امضایی که در یک سرویس تأیید و در دیگری رد می‌شود؛ WAF که payload را یک‌طور decode می‌کند و برنامه طور دیگر (راه دور زدن کلاسیک)؛ newline انتهای مقدار Kubernetes Secret که ورود را می‌شکند؛ کلید cache که بسته به padding فرق می‌کند.

BehaviourGoPHPWHATWG atob / browsersPythonNode BufferJava
Skips CR and LFYesYes (php-src: strict mode skips whitespace, non-strict skips every unknown character)Yes (all ASCII whitespace)Default yes; validate=True noYesBasic decoder rejects; MIME decoder ignores
Skips other junkNo (error)Non-strict: silently discards; strict: falseNo (error)Default: discards; validate=True: errorYes (measured: aG$k= decodes to hi)Basic: error (Javadoc: rejects characters outside the alphabet)
Accepts missing paddingOnly Raw*YesYes (unless length mod 4 is 1)NoYesYes
Accepts the other alphabetNoNoNob64decode no, urlsafe_b64decode accepts bothYes (both)No
Rejects non-zero trailing bitsOnly .Strict()NoNoNoNoNo

راه‌حل: یک گونه را که مشخص کرده‌اید decode کنید، فاصلهٔ ناخواسته را رد کنید، و امضا را روی رشتهٔ دریافتی بررسی کنید نه روی مقدار دوباره-کدگذاری‌شده. کد: safedecode.

Base32 مهم ​

به زبان ساده: مثل Base64 ولی فقط ۳۲ نویسه (A-Z و 2-7)؛ پس هر نویسه ۵ بیت می‌برد و ۸ نویسه ۵ بایت. بلندتر است اما حرف کوچک، + و / ندارد و ارقام شبیه حروف نیستند.

بدفهمی رایج: «Base32 فقط Base64ِ بدتر است.» ارزشش در این است که از تبدیل حروف به هم (نام DNS، فایل‌سیستم‌های macOS و Windows) جان سالم به در می‌برد و می‌شود آن را بلند خواند. RFC 4648 دلیلش را می‌گوید: شکلی که باید به حروف حساس نباشد ولی لازم نیست برای انسان خوانا باشد.

تعریف: الفبای بخش ۶ RFC 4648 یعنی ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 و pad = تا مضرب ۸. بخش ۷ گونهٔ base32hex با 0-9A-V را تعریف می‌کند که ترتیب بایت‌ها را نگه می‌دارد. گونه‌های مخصوص انسان:

VariantAlphabetRulesOrigin
RFC 4648 Base32A-Z 2-7upper-case, = padIETF; TOTP key URIs
base32hex0-9 A-Vsort-order preservingRFC 4648 section 7
Crockford0-9 A-Z without I L O Udecode accepts lower case, I/L as 1, O as 0, hyphens ignored, optional check symbol modulo 37Douglas Crockford
z-base-32ybndrfg8ejkmcpqxot1uwisza345h769lower case, shuffled so common characters are easyZooko Wilcox-O'Hearn

Crockford می‌نویسد ۴ حرف از ۲۶ حرف کنار گذاشته شده‌اند: I L O U؛ چون I و L با 1 اشتباه می‌شوند، O با 0، و U «ناسزای تصادفی» می‌سازد. ULID از Crockford Base32 استفاده می‌کند؛ ID generation.

text
bytes "hello" = 68 65 6c 6c 6f   (40 bits = exactly 8 groups of 5 bits)
RFC 4648 : NBSWY3DP
Crockford: D1JPRV3F
z-base-32: pb1sa5dx
TOTP secret JBSWY3DPEHPK3PXP -> 48 65 6c 6c 6f 21 de ad be ef   (10 bytes, 16 chars, no padding needed)

سناریوهای واقعی: پارامتر secret در URI به شکل otpauth:// (طبق wiki گوگل: کلیدی دلخواه که در Base32 کدگذاری شده)؛ DNSSEC NSEC3 (RFC 5155 از «Base 32 Encoding with Extended Hex Alphabet» نام می‌برد)؛ ULID؛ کدهای بازیابی که کاربر تایپ می‌کند.

ProductBase32 API
Goencoding/base32 (StdEncoding, HexEncoding, NewEncoding(alphabet).WithPadding)
PHPnone built in; see the Base32 class in Solving or a library
JavaScriptnone native; libraries
Pythonbase64.b32encode, b32hexencode
PostgreSQLencode(x, 'base32hex') in the version 19 docs

راه‌حل: برای کدهای تایپ‌شده توسط انسان، چهارتا چهارتا گروه کنید و بی‌توجه به حروف decode کنید؛ برای TOTP فاصله و = را بردارید. کد: alphabets.

Base58 تکمیلی ​

به زبان ساده: الفبایی شبیه Base64 که نویسه‌های مشابه را ندارد تا از روی کاغذ یا صفحه بدون خطا کپی شود، و + و / ندارد تا دابل‌کلیک کل آن را انتخاب کند.

بدفهمی رایج: «Base58 هم مثل Base64 بیت‌بُر است.» ۵۸ توان ۲ نیست؛ مثل تبدیل یک عدد بسیار بزرگ به مبنای دیگر کار می‌کند، به تقسیم اعداد بزرگ نیاز دارد و نسبت به طول درجه‌دوم است. برای مقدارهای کوتاه (کلید، hash، شناسه) است، نه مگابایت.

تعریف: الفبای Bitcoin یعنی 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz؛ طبق توضیح کد Bitcoin: نویسه‌های 0OIl استفاده نمی‌شوند چون در بعضی فونت‌ها یکسان‌اند. هر بایت صفر ابتدایی به یک 1 ابتدایی تبدیل می‌شود. Base58Check پیش از کدگذاری یک checksum چهاربایتی (SHA-256 دوبار) اضافه می‌کند.

text
bytes  00 00 01 02 03 ff ee
b58    117bX9dP         (two leading zero bytes -> two leading '1')

سناریوهای واقعی: آدرس و کلید WIF در Bitcoin؛ شناسه‌های کوتاه کپی‌شونده توسط انسان.

ProductBase58
Gogithub.com/btcsuite/btcutil/base58 or the 40-line math/big version in alphabets
PHPlibraries (stephen-hill/base58php) or the class in Solving
VariantsBitcoin, Flickr (swapped case), Ripple (different order): same idea, different alphabet; never mix them

Base85 / Ascii85 تکمیلی ​

به زبان ساده: چهار بایت می‌شود پنج نویسه از الفبای ۸۵ تایی: فقط ۲۵٪ بزرگ‌تر، نه ۳۳٪.

بدفهمی رایج: «Base85 همان Base64ِ بهتر است.» نویسه‌هایی (<، >، '، "، \، &) دارد که در HTML و JSON و shell و XML اذیت می‌کنند؛ پس بیشتر به قالب فایل می‌خورد تا به پروتکل سیمی. چند الفبای ناسازگار وجود دارد.

تعریف: Ascii85 (Adobe PostScript و PDF، و btoa پل راتر) چهار بایت را عدد ۳۲ بیتی big-endian می‌گیرد، پنج بار بر ۸۵ تقسیم می‌کند و به هر رقم ۳۳ می‌افزاید، یعنی ! تا u؛ چهار بایت صفر را می‌شود با z نوشت (منبع ثانویه: Wikipedia). Git در binary patch جدول ۸۵ نویسه‌ای base85.c را با یک نویسهٔ طول در ابتدای هر خط استفاده می‌کند؛ همان جدولی که b85encode پایتون دارد. Z85 (ZeroMQ) و RFC 1924 گونه‌های دیگرند.

text
$ git diff --binary          (real output)
GIT binary patch
literal 11
ScmZQzWODNKa}0|7{|^8Ro&&}J        <- 'S' encodes the line length, then Base85 of the (compressed) data

سناریوهای واقعی: streamهای PDF با /ASCII85Decode؛ git diff --binary و git format-patch --binary؛ PostScript؛ ZeroMQ (Z85).

ProductBase85
Goencoding/ascii85 (Adobe variant)
PHPnone built in (libraries)
Pythonbase64.a85encode, base64.b85encode (its alphabet, read from base64._b85alphabet, is 0-9A-Za-z then !#$%&()*+-;<=>?@^_{
Gitinternal base85.c: the 85-character table above, a length byte per line

Percent-encoding (URL encoding) حیاتی ​

به زبان ساده: بایتی که در URL مجاز نیست با % و دو رقم hex نوشته می‌شود. فاصله %20 است و é (دو بایت در UTF-8) می‌شود %C3%A9.

بدفهمی رایج: «کل URL را پیش از استفاده percent-encode کن.» کدگذاری برای هر component و هر بایت است؛ کدگذاری URL آماده همان : / ? # را که ساختار را نگه می‌داشتند escape می‌کند و کدگذاری دوباره %20 را به %2520 می‌برد.

تعریف (RFC 3986): pct-encoded = "%" HEXDIG HEXDIG؛ نویسه‌های unreserved یعنی ALPHA / DIGIT / "-" / "." / "_" / "~" هیچ‌وقت encode نمی‌شوند. مجموعهٔ reserved شامل gen-delims (: / ? # [ ] @) و sub-delims (! $ & ' ( ) * + , ; =) است که «نویسه‌های جداکننده‌ای فراهم می‌کنند که از داده در URI قابل‌تشخیص‌اند». RFC 3986 توصیه می‌کند رقم‌های hex بزرگ نوشته شوند، اما %2f و %2F معادل‌اند. برای متن، اول با UTF-8 نویسه‌ها به بایت تبدیل می‌شوند و بعد هر بایت encode می‌شود.

text
"سلام دنیا"  UTF-8 bytes d8 b3 d9 84 d8 a7 d9 85 20 d8 af d9 86 db 8c d8 a7
path    : %D8%B3%D9%84%D8%A7%D9%85%20%D8%AF%D9%86%DB%8C%D8%A7     (51 chars, 3x)
query   : %D8%B3%D9%84%D8%A7%D9%85+%D8%AF%D9%86%DB%8C%D8%A7       (49 chars)

سناریوهای واقعی: query جست‌وجو با کلمه‌های فارسی؛ نام فایل با فاصله در لینک دانلود؛ پارامتر redirect_uri که خودش یک URL کامل است؛ state در OAuth؛ پارامترهای ردیابی.

FunctionEncodesSpace becomesLeaves alone
Go url.QueryEscapeeverything outside A-Za-z0-9 - _ . ~+unreserved only
Go url.PathEscapefor one path segment: escapes / ; , ? # and non-ASCII (measured)%20$ & + : = @ stay literal
PHP urlencodenon-alphanumeric except -_.+so ~ becomes %7E
PHP rawurlencodeRFC 3986%20-_.~
PHP http_build_querydefault PHP_QUERY_RFC1738+pass PHP_QUERY_RFC3986 for %20
JavaScript encodeURIComponentall but A-Za-z0-9 - _ . ! ~ * ' ( )%20for one component
JavaScript encodeURIwhole URL; keeps ; , / ? : @ & = + $ #%20for a full URL only
Python urllib.parse.quote / quote_pluspath-style / form-style%20 / +/ kept by default in quote

راه‌حل: برای هر component از کتابخانهٔ استاندارد استفاده کنید (urlbug) و هرگز "?q=" + value ننویسید.

+ در برابر %20 و باگ آن حیاتی ​

به زبان ساده: در query بسیاری از سرورها + را فاصله می‌خوانند؛ پس مقدار Base64 یا ایمیلی مثل a+b@example.test در راه + خود را از دست می‌دهد.

بدفهمی رایج: «در URL، + یعنی فاصله.» فقط در application/x-www-form-urlencoded. در path، + خودِ plus است. RFC 3986 در query اصلاً معنایی به + نمی‌دهد (sub-delimiter است)؛ استاندارد WHATWG URL کدگذاری فرم را تعریف می‌کند که بایت 0x20 را + می‌کند و در decode می‌گوید هر 0x2B را با 0x20 (SP) عوض کن. خود مستندات PHP می‌گوید urlencode «همان‌طور کدگذاری می‌کند که دادهٔ پست‌شدهٔ فرم WWW».

text
client builds    GET /verify?token=++++//4=         (raw standard base64, not encoded)
server parses    token = "    //4="                  (each '+' -> space)
signature check  FAILS (the bytes changed)           -> 401 / "invalid token"
fix A            token=%2B%2B%2B%2B%2F%2F4%3D         (percent-encode on the client)
fix B            token=----__4                        (base64url: no '+' to lose)

سناریوهای واقعی: لینک تأیید ایمیل؛ امضای webhook در query؛ token های Base64 که در نوار آدرس چسبانده می‌شوند؛ ایمیل‌هایی با +tag در query؛ URL داشبورد Kubernetes که token دارد.

Where+ means%20 means
URL patha plus signa space
URL query read as form data (PHP $_GET, Go Query(), Express req.query, Laravel $request->query())a spacea space
application/x-www-form-urlencoded bodya spacea space
multipart/form-data bodya plus sign (no percent decoding)not decoded as such
JavaScript encodeURIComponent outputnever produced; + becomes %2Bspace

راه‌حل: هر مقدار query را encode کنید (url.Values.Encode، http_build_query، URLSearchParams) یا با base64url اصلاً + و / به سیم نفرستید. کد: urlbug؛ آزمایش: Lab.

Double encoding (کدگذاری مضاعف) مهم ​

به زبان ساده: کدگذاری مقداری که قبلاً کدگذاری شده، تا خود % به %25 تبدیل شود، یا decode دوباره‌ای که %2520 را به فاصله می‌رساند به جای %20.

بدفهمی رایج: «کدگذاری اضافه بی‌ضرر است، سرور decode می‌کند.» ضرر دارد: RFC 3986 می‌گوید پیاده‌سازی‌ها نباید یک رشته را بیش از یک بار percent-encode یا decode کنند، چون decode رشتهٔ decode‌شده ممکن است % دادهٔ واقعی را آغاز یک percent-encoding بپندارد. و یک دور زدن امنیتی کلاسیک است: فیلتر یک بار decode می‌کند و %2e%2e%2f می‌بیند؛ برنامه بار دوم decode می‌کند و ../ را راه می‌رود.

text
raw        a b&c=d
once       a%20b%26c%3Dd
twice      a%2520b%2526c%253Dd       <- a link that works only after two decodes
server decodes once -> a%20b%26c%3Dd  <- user sees literal '%20' on the page

سناریوهای واقعی: redirect_uri که فریم‌ورک دوباره encode می‌کند؛ CDN یا proxy که path را نرمال می‌کند و بعد برنامه decode می‌کند؛ پیام صفی که payload از قبل escape شده؛ لینکی که یک helper ساخته و e() دوباره escape کرده؛ دور زدن path traversal با %252e%252e%252f.

LayerWho decodesRule
Reverse proxy / WAFmay normalise %2e, %2fdecode once at the edge, not again downstream
Framework routerdecodes the pathroute parameters are already decoded
Applicationdecodes querydo not call urldecode on a value the framework already decoded

راه‌حل: دقیقاً یک بار در مرزی که مقدار وارد URL می‌شود encode کنید و دقیقاً یک بار در جایی که بیرون می‌آید decode کنید. کد: urlbug.

path، query و fragment: سه مجموعه قاعده مهم ​

به زبان ساده: یک نویسه در یک بخش URL مجاز است و در بخش دیگر باید encode شود.

بدفهمی رایج: «یک encoder برای همهٔ بخش‌ها کافی است.» RFC 3986 برای هر component مجموعهٔ مجاز جداگانه دارد (pchar برای segmentهای path، و pchar / "/" / "?" برای query و fragment) و استاندارد WHATWG چند percent-encode set جدا (fragment، query، path، userinfo، component، form) تعریف می‌کند.

تعریف: نحو عمومی scheme://userinfo@host:port/path?query#fragment است. host با IDNA/Punycode (یا IP literal)؛ path به‌ازای هر segment (یک / داخل segment باید %2F باشد)؛ query معمولاً جفت‌های name=value با & که هر بخش با قاعدهٔ فرم encode می‌شود؛ و fragment هرگز به سرور فرستاده نمی‌شود.

text
https://user:p%40ss@xn--mgbh0fb.xn--mgba3a4f16a:8443/%D9%85%D9%82%D8%A7%D9%84%D9%87/a%2Fb?q=a%2Bb+c&n=x%26y#%D8%A8%D8%AE%D8%B4-2
scheme    https
userinfo  user : p%40ss        '@' in the password is %40
host      xn--... (Punycode)
port      8443
path      %D9%85... / a%2Fb    segment "a/b" is one segment
query     q = "a+b c"   n = "x&y"
fragment  بخش-2 (browser only)
Same URL, different encoding per componenthttps://user:pw@مثال.ایران:8443/files/گزارش 1?q=a+b&n=x%26y#بخش-2schemeASCII letters onlyuserinfopercent-encode ':' '@'hostIDNA: xn--mgbh0fb...portdigitspath%20 for space, never +query+ means space (forms)fragmentnot sent to serverEncode each component separately, once, from raw text to bytes (UTF-8) to %XX. Never encode a whole URL.Reserved delimiters (: / ? # [ ] @ ! $ & ' ( ) * + , ; =) keep their meaning only in their own component.Unreserved (A-Z a-z 0-9 - . _ ~) never need encoding.

سناریوهای واقعی: کلید شیء S3 با اسلش و فاصله؛ منابع REST با ایمیل به‌جای شناسه (/users/a%40b.test)؛ رابط جست‌وجو با query فارسی؛ SPA‌هایی که state را در fragment نگه می‌دارند؛ token های جریان implicit در OAuth.

ComponentWhich characters must you encodeGoPHP
Path segment/ ? # %, space, non-ASCIIurl.PathEscaperawurlencode
Query value& = + # %, space, non-ASCIIurl.QueryEscape, url.Valueshttp_build_query, rawurlencode
Fragmentspace, non-ASCII, % (# only matters before it)u.Fragment, u.EscapedFragment()rawurlencode
Userinfo: @ / ? #url.UserPasswordrawurlencode per part
HostIDNA to xn--idna.Lookup.ToASCIIidn_to_ascii

راه‌حل: URL را با نوع URL (net/url، League\Uri، route()/url() لاراول) بسازید، نه با الصاق رشته.

IRI، URLهای فارسی و Punycode مهم ​

به زبان ساده: در مرورگر می‌توانید https://مثال.ایران/مقاله/سلام بنویسید؛ روی سیم ASCII می‌شود. host با Punycode (xn--mgbh0fb.xn--mgba3a4f16a) و path و query با UTF-8 percent-encoded.

بدفهمی رایج: «URL می‌تواند حروف فارسی داشته باشد.» URI نه؛ IRI بله. RFC 3987 IRI را دنباله‌ای از نویسه‌های Universal Character Set می‌داند همراه یک نگاشت از IRI به URI، و مرورگرها پیش از ارسال همین نگاشت را انجام می‌دهند. لاگ سرور معمولاً شکل percent را نشان می‌دهد. ضمناً متن فارسی حروف راست‌به‌چپ و چپ‌به‌راست را قاطی می‌کند و ترتیب نمایش URLِ مختلط ممکن است به‌هم‌ریخته به نظر برسد در حالی که ترتیب ذخیره درست است.

تعریف: Punycode (RFC 3492) «نحو انتقال ساده و کارآمدی است که برای IDNA طراحی شده» و رشتهٔ Unicode را «یکتا و برگشت‌پذیر» به رشتهٔ ASCII تبدیل می‌کند. هر label که غیر ASCII دارد به xn-- به‌علاوهٔ شکل Punycode تبدیل می‌شود. مستند golang.org/x/net/idna می‌گوید IDNA2008 را با پردازش سازگاری UTS #46 پیاده می‌کند. متن فارسی در path و query اول UTF-8 و بعد percent-encoded می‌شود؛ ارقام فارسی و ZWNJ (نیم‌فاصله، U+200C) نویسهٔ معتبرند اما منبع پرتکرار ناهمخوانی (نرمال‌سازی در Bits, Bytes & Text Encoding است).

text
مثال.ایران            -> xn--mgbh0fb.xn--mgba3a4f16a      (real output of x/net/idna)
bücher.example        -> xn--bcher-kva.example
IRI  https://مثال.ایران/مقاله/سلام?q=دنیا
URI  https://xn--mgbh0fb.xn--mgba3a4f16a/%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85?q=دنیا

(url.URL استاندارد Go نویسه‌های غیر ASCII را در RawQuery دست‌نخورده نگه می‌دارد؛ برای ساخت %D8... روی سیم از url.Values.Encode() استفاده کنید.)

سناریوهای واقعی: سایت خبری فارسی با slug فارسی در path؛ sitemap و canonical که باید روی یک شکل توافق کنند؛ لینکی در تلگرام که decode‌شده دیده می‌شود ولی encode‌شده paste می‌شود؛ phishing با دامنهٔ شبیه‌نویس (homograph)، که مرورگرها برای ترکیب مشکوک Punycode نشان می‌دهند؛ slugهایی که Str::slug فارسی را به ASCII برمی‌گرداند مگر language برابر null باشد.

ProductIDNA / IRI support
Gogolang.org/x/net/idna (Lookup, Registration, Display profiles); net/url does not convert hosts
PHPidn_to_ascii / idn_to_utf8 (ext-intl) with INTL_IDNA_VARIANT_UTS46
LaravelStr::slug($title, language: null) skips ASCII transliteration and keeps letters (\pL) such as Persian (framework source), Str::ascii; URL helpers percent-encode paths
Browsersshow Unicode hosts when the script mix looks safe, Punycode otherwise
curlconverts Unicode hosts to Punycode when built with IDN support; give paths already percent-encoded

راه‌حل: شکل canonical را که با آن مقایسه می‌کنید (معمولاً URI کدگذاری‌شده) ذخیره کنید، در لبه تبدیل کنید و هرگز اجازه ندهید host یونیکد کاربر از IDNA رد شود (حل مسئله‌های کلاسیک). سمت DNS: DNS Resolution for Developers.

HTML entity و escape در JSON به‌عنوان «کدگذاری» مهم ​

به زبان ساده: &lt; در HTML و \n یا " در JSON همان ایدهٔ %20 است: راهی برای نوشتن نویسه‌ای که در آن جا خام مجاز نیست.

بدفهمی رایج: «یک بار escape کردم، پس همه‌جا امن است.» escape وابسته به زمینهٔ خروجی است: متن HTML، attribute، رشتهٔ JavaScript، رشتهٔ JSON، URL، CSS. هر خروجی یک escaper.

تعریف: متن HTML به &amp; و &lt; نیاز دارد (و &quot; در attribute)؛ نویسه را می‌شود &#1587; یا &#x633; هم نوشت. رشتهٔ JSON (RFC 8259): همهٔ نویسه‌های Unicode می‌توانند داخل نقل‌قول بیایند مگر آنهایی که باید escape شوند: نقل‌قول، reverse solidus و نویسه‌های کنترلی (U+0000 تا U+001F)؛ هر نویسه را می‌شود \uXXXX نوشت.

text
HTML  <a href="/?q=1&x=2">Tom & "Jerry"</a>
   -> &lt;a href=&#34;/?q=1&amp;x=2&#34;&gt;Tom &amp; &#34;Jerry&#34;&lt;/a&gt;       (Go html.EscapeString)
JSON  {"s":"line1\nline2 \"q\" <tag> & سلام"}
   -> Go encoding/json default: <tag> &   (escapes <, >, & for HTML safety)

سناریوهای واقعی: XSS از ورودی escape‌نشده در echo بدون escape در Blade؛ JSON داخل تگ script؛ نام فارسی که به شکل &#1575;... نمایش داده می‌شود؛ JSON با 
 که parserهای قدیمی JavaScript را می‌شکست؛ escape مضاعف که &amp;amp; در صفحه نشان می‌دهد.

ProductHTML escapeJSON escape controls
Gohtml.EscapeString, html/template (contextual)encoding/json escapes <, >, &, U+2028/2029; Encoder.SetEscapeHTML(false)
PHP / Laravelhtmlspecialchars, Blade's double-brace echo (escapes automatically)JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_HEX_TAG
JavaScripttextContent, templating librariesJSON.stringify (does not escape <)

راه‌حل: از escaper زمینه‌ای موتور template استفاده کنید؛ هرگز HTML یا JSON را دستی نچسبانید. کد: boundaries.

Data URI مهم ​

به زبان ساده: data: URL کل فایل را داخل خود URL می‌گذارد: data:image/png;base64,iVBORw0KGgo.... درخواست دوم لازم نیست.

بدفهمی رایج: «تصویر inline همیشه سریع‌تر است.» حجم یک‌سوم زیاد می‌شود، جدا از صفحه cache نمی‌شود، HTML حاوی آن را سنگین می‌کند و از CDN رد می‌شود. خود RFC 2397 می‌گوید: طرح data: «فقط برای مقدارهای کوتاه مفید است».

تعریف (RFC 2397): dataurl := "data:" [ mediatype ] [ ";base64" ] "," data. بدون ;base64 داده با percent-encoding نوشته می‌شود؛ اگر mediatype نباشد پیش‌فرض text/plain;charset=US-ASCII است. MDN: مرورگرها موظف به پشتیبانی از هیچ حداکثر طولی نیستند؛ Chromium و Firefox تا ۵۱۲ مگابایت و Safari تا ۲۰۴۸ مگابایت می‌پذیرند. مرورگرها data URL را origin کدر (opaque) می‌دانند.

text
data:text/plain;charset=UTF-8,%D8%B3%D9%84%D8%A7%D9%85%20%26%20hello         (percent form)
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQ...                 (base64 form, 86 B -> 138 chars)
CSP:  img-src 'self' data:        <- without 'data:' this inline image is BLOCKED

سناریوهای واقعی: آیکون‌های SVG کوچک و placeholder تار تصویر؛ لوگوی inline در HTML ایمیل؛ QR code که API به‌شکل data URL برمی‌گرداند؛ گزارشی که در JavaScript ساخته و دانلود می‌شود؛ اسکرین‌شات داخل یک issue.

AspectBehaviourProduct note
Sizebase64 form is +33%; prefix data:image/png;base64, adds 22 bytesmeasured: 86-byte PNG became 138 characters
Cachingnone separate from the documentuse files plus HTTP caching instead for big or reused images
CSPimg-src must allow data: explicitly; the CSP3 note says a non-HTTP(S) scheme "has to be ... explicitly specified (e.g. default-src * data:...)"; the CSP3 text also says developers "SHOULD NOT include either 'unsafe-inline', or data: as valid sources" for scriptsdata: in script-src enables XSS
E-mail clientssupport for data: images varies and some clients block them (not verified per client here)use cid: attachments or hosted images
OriginMDN: data URLs are treated as unique opaque originsdo not rely on same-origin access to inline content

راه‌حل: فقط دارایی‌های کوچک و یک‌بارمصرف (چند صد بایت تا چند KB) را inline کنید؛ وقتی data URI را از کاربر می‌پذیرید حجم decode‌شده را محدود کنید (datauri).

Quoted-printable و encoded-word در MIME تکمیلی ​

به زبان ساده: متن خوانا را همان‌طور نگه دارید و فقط بایت‌های دردسرساز را =XX کنید. برای متنی که بیشترش ASCII است و چند حرف اعراب‌دار دارد خوب است و برای باینری بد.

بدفهمی رایج: «پیوست ایمیل quoted-printable است.» پیوست‌ها base64 هستند؛ quoted-printable برای بدنهٔ متنی است. headerهای غیر ASCII (Subject، نام فرستنده) نحو دیگری دارند، یعنی encoded-word در RFC 2047: =?utf-8?b?2LPZhNin2YU=?= (B یعنی base64) یا =?utf-8?q?=D8=B3...?= (Q شبیه quoted-printable).

تعریف: RFC 2045 بخش ۶.۷: اکتت‌ها در بازهٔ قابل‌چاپ را می‌شود با نویسهٔ ASCII متناظر نوشت، بقیهٔ بایت‌ها = به‌علاوهٔ دو رقم hex، با soft line break (یک = آخر خط) چون خط‌های کدگذاری‌شده نباید از ۷۶ نویسه بلندتر باشند. header ‏Content-Transfer-Encoding آن را برمی‌گزیند (7bit، 8bit، binary، quoted-printable، base64).

text
Café = 5€   ->   Caf=C3=A9 =3D 5=E2=82=AC          (the literal "=" itself becomes =3D)
long line   ->   ...text...=<CRLF>...more text...    (soft break after 76 chars)
Subject: =?utf-8?b?2LPZhNin2YU=?=                    (RFC 2047, Persian "سلام")

سناریوهای واقعی: بدنهٔ HTML ایمیل از mailerها (Postfix، Symfony Mailer، PHPMailer)؛ فایل‌های .eml که به جای = علامت =3D نشان می‌دهند؛ dumpهای خام MIME در لاگ؛ Subject که در کلاینتِ ناتوان به شکل =?UTF-8?B?... دیده می‌شود.

ProductAPI
Gomime/quotedprintable, mime.QEncoding / mime.BEncoding, mime.WordDecoder
PHPquoted_printable_encode / _decode, mb_encode_mimeheader, iconv_mime_encode
LaravelSymfony Mailer (underlying) picks base64 or quoted-printable per part

uuencode و کدگذاری‌های تاریخی تکمیلی ​

به زبان ساده: جد Base64: سه بایت به چهار نویسه در بازهٔ ۳۲ تا ۹۵ (از فاصله تا underscore)، با یک نویسهٔ طول در ابتدای هر خط.

بدفهمی رایج: «uuencode منسوخ است، پس کسی نمی‌بیندش.» هنوز در آرشیو Usenet، بلوک‌های begin 644 file داخل ایمیل قدیمی و دستور uuencode -m در macOS (که در واقع Base64 می‌نویسد) می‌بینیدش.

تعریف: uuencode طبق Wikipedia (منبع ثانویه) از برنامه‌های uuencode و uudecode مری‌آن هورتون در دانشگاه برکلی در ۱۹۸۰ پدید آمد. استفاده‌اش از فاصله، backquote و backslash آن را شکننده می‌کرد؛ Base64 حروف، ارقام، + و / را برگزید. خویشاوندان: BinHex (Mac کلاسیک)، yEnc (Usenet، ۸ بیتی، سربار حدود ۱ تا ۲٪، هرگز استاندارد نشد)، Base91، Z85.

text
$ printf hello | uuencode hello.txt      (real output, macOS)
begin 644 hello.txt
%:&5L;&\`
`
end

راه‌حل: به Base64 تبدیل کنید (uudecode file | base64)؛ uuencode جدید تولید نکنید.

Base64 رمزنگاری نیست حیاتی ​

به زبان ساده: Base64 راهی برای املا کردن بایت‌هاست. هر کس decoder داشته باشد (هر زبانی دارد و base64 -d یک دستور است) می‌خواندش.

بدفهمی رایج: «شبیه آشغال تصادفی است، پس محافظت‌شده است.» پنهان کردن در دید همگان مبهم‌سازی (Obfuscation) است، نه امنیت؛ RFC 4648 هشدار می‌دهد که این باور باعث حوادث امنیتی شده، مثلاً وقتی کاربری جزئیات یک تبادل پروتکل را گزارش می‌کند و ندانسته رمز را فاش می‌کند چون نمی‌داند کدگذاری پایه آن را محافظت نمی‌کند. همچنین «هیچ entropy به متن اضافه نمی‌کند ولی حجم داده را زیاد می‌کند».

تعریف: راز به کلید نیاز دارد؛ کدگذاری کلید ندارد. Cryptography Fundamentals برای AES-GCM و Password Hashing & Signed Tokens برای رمز عبور. مستندات Kubernetes همین را دربارهٔ Secret می‌گوید: Secretها به‌طور پیش‌فرض در data store زیرین API server (یعنی etcd) بدون رمزگذاری ذخیره می‌شوند؛ و دربارهٔ فیلد auth در Docker: مقدار «base64 encoded است؛ مبهم است اما محرمانه نیست».

text
$ echo -n 'p@ss/w+rd' | base64
cEBzcy93K3Jk
$ echo cEBzcy93K3Jk | base64 -d
p@ss/w+rd                               <- one command, no key
Authorization: Basic bW9ydGV6YTpwQHNzOndvcmQ=   -> morteza:p@ss:word

سناریوهای واقعی: کلید API «محافظت‌شده» با base64 در اپ موبایل (در چند دقیقه استخراج می‌شود)؛ HTTP Basic روی HTTP ساده (اعتبارنامه روی سیم خوانا است)؛ YAML مربوط به Kubernetes Secret که در Git commit شده (راز در مخزن است)؛ لاگ کردن header Authorization؛ payload در JWT که دادهٔ شخصی دارد (هر کس token را دارد می‌خواند).

ClaimReality
"Base64 hides it"reversible by anyone, no key
"JWT is encrypted"a normal JWT (JWS) is signed, not encrypted: base64url only; JWE is a different thing
"Kubernetes Secret is secure by default"stored unencrypted in etcd unless encryption at rest is enabled; RBAC controls access
"HTTP Basic is OK over HTTPS"yes over TLS; base64 adds nothing; credentials are visible to the server and any log that records the header

راه‌حل: با رمز واقعی رمزگذاری کنید، رمز عبور را با password hash نگه دارید، رازها را از Git و لاگ دور کنید و هر چیز base64 را متن ساده بدانید.

هر کدام کجا دیده می‌شود مهم ​

به زبان ساده: دانستن اینکه یک سیستم کدام کدگذاری را استفاده می‌کند، خواندنش را در یک نگاه ممکن می‌کند.

بدفهمی رایج: «همهٔ این رشته‌های base64 از یک نوع‌اند.» الفبا و padding فرق دارند؛ نشانهٔ سریع: - یا _ یعنی base64url، + یا / یعنی استاندارد، = آخر یعنی با padding.

WhereEncodingDetail
JWT (JWS compact)base64url, no padding, three segments joined by .RFC 7515; header and payload are JSON, signature is raw bytes; eyJ is the tell-tale start of {"
Kubernetes Secret data:standard Base64 of the raw bytesstringData: takes plain text and the API server encodes it; Secrets are limited to 1 MiB
HTTP Basicstandard Base64 of user:password (RFC 7617)first colon splits, so user names cannot contain a colon
Docker config.json authBase64 of user:passwordobscured, not secret
E-mail attachmentsBase64 with 76-char lines (RFC 2045)Content-Transfer-Encoding: base64
HTML img srcdata URI (RFC 2397)CSP img-src data:
PEM files (certificates, keys)Base64 body, 64-char lines between -----BEGIN ...----- markerssee TLS in Practice
Git LFS pointer filetext file: version, oid sha256:<64 hex>, sizethe oid is hex of the content hash; pointers must be under 1024 bytes
Git binary patchGit's Base85git diff --binary
Protobuf JSON mappingbytes field becomes a Base64 string"JSON value will be the data encoded as a string using standard base64"; parsers accept both alphabets
Cookie valuesRFC 6265 allows + / =, forbids space, comma, semicolon, quote, backslash; at least 4096 bytes per cookieLaravel's session and encrypted cookies are Base64 of JSON
Laravel Encrypter payloadBase64 of a JSON object with base64 iv, value, mac, tagread in the framework source
TOTP secretBase32otpauth://totp/...?secret=JBSWY3DPEHPK3PXP
Laravel signed URLsignature= lower-case hex of HMAC-SHA256 over the URLnot base64
SSH, WireGuard keysBase6432-byte key = 44 characters with padding

راه‌حل: وقتی مطمئن نیستید با گونهٔ متناسب decode کنید و بررسی کنید؛ Lab.

Every boundary has its own escaping ruleClientbrowser, app,curl, Go, PHPServerdecodes eachlayer once, inthe right orderURL path/querypercent-encoding (UTF-8)Form bodyx-www-form-urlencoded: + for spaceJSON body\" \\ \n \uXXXX escapes; binary as base64HeadersBasic: base64; Cookie: base64url or hexHost namePunycode xn-- (IDNA)HTML responseentities: &lt; &amp; &quot;E-mail / MIMEbase64 or quoted-printable, 76 colsBug pattern: decode at the wrong boundary, twice, or not at all (a "+" that became a space, "%2520", &amp;amp;).

نمودار بالا نقشهٔ مرزها را نشان می‌دهد: در یک درخواست، URL، فرم، بدنهٔ JSON، headerها، نام host، پاسخ HTML و ایمیل هر کدام قاعدهٔ escape خود را دارند و سرور باید هر لایه را یک بار و به ترتیب درست decode کند.

رفتار هر زبان و ابزار ​

Go (encoding/base64، encoding/hex، encoding/base32، encoding/ascii85، net/url، mime/quotedprintable، html و golang.org/x/net/idna):

NeedAPINotes
Standard paddedbase64.StdEncodingdecoder ignores \r and \n only
Unpadded standardbase64.RawStdEncoding
URL-safe padded / unpaddedbase64.URLEncoding / base64.RawURLEncodingJWT uses RawURLEncoding
Custom alphabet / paddingbase64.NewEncoding(alphabet).WithPadding(rune); base64.NoPaddingalphabet must be 64 distinct bytes without \r \n
Reject non-zero trailing bitsenc.Strict()
Streamingbase64.NewEncoder(enc, w) (must Close), base64.NewDecoder(enc, r)
SizesEncodedLen, DecodedLen, AppendEncodeallocate buffers exactly
JSON[]byte fields become standard padded base64 stringsencoding/json
Hexhex.EncodeToString, hex.DecodeString, hex.Dump
Percenturl.QueryEscape, url.PathEscape, url.Values.Encode, url.ParseQuery

PHP (۸.۴) و Laravel 13:

NeedAPINotes
Base64base64_encode, base64_decode($s, strict: true)non-strict silently discards invalid characters
Base64urlrtrim(strtr(base64_encode($s), '+/', '-_'), '=')no built-in
Hexbin2hex, hex2bin
Percent (form)urlencode, urldecode, http_build_queryspace is +
Percent (RFC 3986)rawurlencode, rawurldecode, http_build_query($d, '', '&', PHP_QUERY_RFC3986)space is %20
Laravel string helpersStr::toBase64($s), Str::fromBase64($s, $strict = false)thin wrappers over base64_encode and base64_decode (framework source)
Laravel query buildingArr::query($array)calls http_build_query with PHP_QUERY_RFC3986
Laravel signed URLsURL::signedRoute, URL::temporarySignedRoute, $request->hasValidSignature(), signed middlewaresignature is hex hash_hmac('sha256', ...)
Laravel encryptionCrypt::encryptStringoutput is Base64 of JSON
Quoted-printablequoted_printable_encode
IDNidn_to_ascii, idn_to_utf8ext-intl

JavaScript (مرورگر و Node):

NeedAPIPitfall
Base64 of a binary stringbtoa, atobbtoa('سلام') throws InvalidCharacterError because characters above 0xFF do not fit in a byte; MDN: "necessary to first convert the string to its constituent bytes in UTF-8, and then encode the bytes"
Base64 of bytesUint8Array.prototype.toBase64(), Uint8Array.fromBase64(); Node Buffer.from(x).toString('base64')Node 26 here reports Uint8Array.prototype.toBase64 as a function
PercentencodeURIComponent (component), encodeURI (whole URL), URLSearchParams (form rules, + for space)escape/unescape are deprecated; do not use
UTF-8 bytesnew TextEncoder().encode(str)

ابزارهای خط فرمان:

ToolCommandBehaviour on this machine
base64 (macOS)printf hello | base64no wrapping; -b 76 wraps; echo hello adds \n and changes the output (aGVsbG8K)
base64 (GNU coreutils)base64 -w 0wraps at 76 by default: "The default is to wrap after 76 characters. Use the value 0 to disable line wrapping"
openssl base64openssl base64 -Awraps at 64 (measured); -A single line
xxdxxd -p, xxd -r -phex dump and reverse
curl--data-urlencode 'q=a+b'percent-encodes (lower-case hex: %2b)
kubectlkubectl get secret x -o jsonpath='{.data.password}' | base64 -ddecode a value
gitgit diff --binaryBase85 patches
PostgreSQLencode(x, 'hex' / 'base64' / 'escape'), decode(...)base64url and base32hex are in the 19 docs
sql
-- PostgreSQL: encode and decode bytea (documented: encode('123\000\001', 'base64') -> MTIzAAE=)
SELECT encode('\xd8b3d984d8a7d985'::bytea, 'hex')    AS hex,
       encode('\xd8b3d984d8a7d985'::bytea, 'base64') AS b64,
       convert_from(decode('2LPZhNin2YU=', 'base64'), 'UTF8') AS text_back;

سازوکار (Mechanics) ​

ریاضی بیت و طول‌ها ​

EncodingBits per charGroup (input to output)Encoded length for n bytes
Base1641 byte to 2 chars2n
Base3255 bytes to 8 chars8 * ceil(n / 5) padded
Base6463 bytes to 4 chars4 * ceil(n / 3) padded; ceil(4n / 3) unpadded
Base64 MIME6plus CRLF every 76 chars4 * ceil(n/3) + 2 * ceil(4*ceil(n/3) / 76)
Base85about 6.44 bytes to 5 chars5 * ceil(n / 4)
Base58about 5.86big-integer divisionabout 1.37n
Percentvariable1 byte to 3 chars when escapedn to 3n

اندازه‌گیری‌شده روی همین ماشین: فایل ۱۰۰ مگابایتی با خط‌شکن MIME به ۱۴۳٬۴۸۹٬۳۵۰ بایت رسید (۱٫۳۶۸ برابر)، دقیقاً 4/3 * 78/76؛ ۱۷ بایت متن فارسی ۲۴ نویسه Base64 با padding، ۳۴ نویسه hex و ۴۹ تا ۵۱ نویسه percent-encoding شد.

خط‌شکن، quantum و بیت‌های pad ​

MIME خروجی را در خط‌های حداکثر ۷۶ نویسه می‌شکند؛ RFC 2045 می‌گوید حد ۷۶ نویسه CRLF پایانی را نمی‌شمارد ولی بقیهٔ نویسه‌ها از جمله = را می‌شمارد. PEM از ۶۴ استفاده می‌کند. آخرین گروه ۶ بیتی ممکن است بیت‌های بلااستفاده (pad bits) داشته باشد؛ RFC 4648 می‌گوید encoderهای منطبق باید آنها را صفر بگذارند و decoderها «ممکن است» در صورت غیرصفر بودن رد کنند. برای همین aGl= و aGk= هر دو در decoder آسان‌گیر به hi می‌رسند ولی فقط aGk= canonical است (Strict() در Go دیگری را رد می‌کند). دو رشته که به یک بایت decode می‌شوند مقایسهٔ امضا را می‌شکنند؛ پس بایت‌ها را مقایسه کنید نه رشتهٔ کدگذاری‌شده را.

کارایی، SIMD و streaming ​

Base64 روی CPUهای امروزی محدود به حافظه است. مقالهٔ Lemire و Muła (arXiv 1910.05109) نشان می‌دهد با AVX-512 می‌شود Base64 را «تقریباً با سرعت memcpy» کدگذاری و decode کرد؛ base64.c در PHP مسیرهای AVX2 و SSSE3 و AVX-512 دارد که در زمان اجرا انتخاب می‌شوند؛ کتابخانهٔ simdutf decode با قواعد forgiving WHATWG را دارد. با go test -bench روی این ماشین (Apple M5، بافر ۱ مگابایت): encode حدود ۳٫۰ گیگابایت بر ثانیه، decode حدود ۳٫۵، EncodeToString ۲٫۵ همراه ۲ allocation و hex ۲٫۱۵. درس عملی: (۱) یک بار با EncodedLen تخصیص بدهید؛ (۲) فایل بزرگ را stream کنید (اندازه‌گیری‌شده: ۱۰۰ مگابایت با خط‌شکن MIME کدگذاری و دوباره decode شد با حداکثر ۹٫۷ مگابایت حافظهٔ resident)؛ (۳) وقتی کانال باینری یا multipart هست payload بزرگ را در JSON به Base64 نبرید، چون آن ۳۳٪ در پهنای باند، CPU، حافظه و لاگ دو طرف پرداخت می‌شود.

text
stream: file ──read 32 KiB──▶ base64.NewEncoder ──▶ line wrapper (76) ──▶ bufio ──▶ file
memory stays constant; Close() flushes the final 1-2 bytes and the "=" padding

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

Error textSourceMeaning
illegal base64 data at input byte NGo CorruptInputErrorwrong alphabet, wrong padding mode, or stray character (the offset is a hint, not always exact)
InvalidCharacterError: Invalid characterJavaScript atob / btoa (measured in Node)non-alphabet character, or Unicode passed to btoa
binascii.Error: Incorrect paddingPythonunpadded input to the padded decoder
base64_decode(): ... returns falsePHP strictcharacter outside the alphabet or wrong padding
URIError: URI malformedJavaScript decodeURIComponent('%zz') (measured)a % not followed by two hex digits, or invalid UTF-8
invalid URL escape "%zz"Go url.QueryUnescape (measured)% not followed by two hex digits
400 Bad Request with % in the pathweb servers and proxiesinvalid percent-escape, or an encoded / the server refuses (Apache has an AllowEncodedSlashes directive)
Invalid signature (Laravel 403)signed middlewareURL changed after signing: re-encoded, parameter reordered, or + mangled

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

همهٔ برنامه‌های Go با go run ./<dir> از docs/snippets/foundations/binary-to-text-encoding/go اجرا می‌شوند؛ PHP (۸.۴ و Laravel 13) بازبینی شده اما اجرا نشده چون PHP روی این ماشین نصب نیست.

مسئلهٔ ۱: همان بایت‌ها در همهٔ کدگذاری‌ها ​

SolutionHowAdvantageCost
One table of all formshex, base64, base32, ascii85, percent in one programshows size and look side by sidenone
go
// Command encodings shows the same bytes through every common
// binary-to-text encoding and prints the size cost of each.
package main

import (
	"encoding/ascii85"
	"encoding/base32"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"net/url"
)

func main() {
	text := "سلام دنیا" // "Hello world" in Persian, 9 characters
	raw := []byte(text)

	rows := []struct {
		name string
		out  string
	}{
		{"hex", hex.EncodeToString(raw)},
		{"base64 std (padded)", base64.StdEncoding.EncodeToString(raw)},
		{"base64 raw (no padding)", base64.RawStdEncoding.EncodeToString(raw)},
		{"base64url (padded)", base64.URLEncoding.EncodeToString(raw)},
		{"base64url raw", base64.RawURLEncoding.EncodeToString(raw)},
		{"base32 std", base32.StdEncoding.EncodeToString(raw)},
		{"base32 hex alphabet", base32.HexEncoding.EncodeToString(raw)},
		{"ascii85", ascii85Encode(raw)},
		{"percent (query)", url.QueryEscape(text)},
		{"percent (path segment)", url.PathEscape(text)},
	}

	fmt.Printf("input: %q  (%d runes, %d bytes in UTF-8)\n\n", text, len([]rune(text)), len(raw))
	fmt.Printf("%-26s %5s %7s  %s\n", "encoding", "len", "ratio", "output")
	for _, r := range rows {
		fmt.Printf("%-26s %5d %6.2fx  %s\n", r.name, len(r.out), float64(len(r.out))/float64(len(raw)), r.out)
	}
}

func ascii85Encode(b []byte) string {
	dst := make([]byte, ascii85.MaxEncodedLen(len(b)))
	n := ascii85.Encode(dst, b)
	return string(dst[:n])
}

خروجی واقعی:

text
input: "سلام دنیا"  (9 runes, 17 bytes in UTF-8)

encoding                     len   ratio  output
hex                           34   2.00x  d8b3d984d8a7d98520d8afd986db8cd8a7
base64 std (padded)           24   1.41x  2LPZhNin2YUg2K/ZhtuM2Kc=
base64 raw (no padding)       23   1.35x  2LPZhNin2YUg2K/ZhtuM2Kc
base64url (padded)            24   1.41x  2LPZhNin2YUg2K_ZhtuM2Kc=
base64url raw                 23   1.35x  2LPZhNin2YUg2K_ZhtuM2Kc
base32 std                    32   1.88x  3CZ5TBGYU7MYKIGYV7MYNW4M3CTQ====
base32 hex alphabet           32   1.88x  R2PTJ16OKVCOA86OLVCODMSCR2JG====
ascii85                       22   1.29x  fX'7afVdDV+P<mNL>.[>VZ
percent (query)               49   2.88x  %D8%B3%D9%84%D8%A7%D9%85+%D8%AF%D9%86%DB%8C%D8%A7
percent (path segment)        51   3.00x  %D8%B3%D9%84%D8%A7%D9%85%20%D8%AF%D9%86%DB%8C%D8%A7

معادل PHP، به‌علاوهٔ base64url و Base32:

php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/**
 * The same bytes through every common binary-to-text encoding in PHP.
 * PHP has native hex, base64, percent-encoding and (via convert.* filters)
 * quoted-printable; Base32 and Base58 are not in the standard library.
 */
final class Encodings
{
    /** RFC 4648 section 5: "-" and "_" instead of "+" and "/", padding removed. */
    public static function base64UrlEncode(string $bytes): string
    {
        return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
    }

    /** Returns false for anything that is not valid base64url (padding optional). */
    public static function base64UrlDecode(string $text): string|false
    {
        // Re-add the padding the encoder removed: length must be a multiple of 4.
        $padded = str_pad(strtr($text, '-_', '+/'), (int) (ceil(strlen($text) / 4) * 4), '=');

        return base64_decode($padded, strict: true);
    }

    /** @return array<string, string> label => encoded text, for one input. */
    public static function allForms(string $bytes): array
    {
        return [
            'hex'               => bin2hex($bytes),
            'base64'            => base64_encode($bytes),
            'base64 (no pad)'   => rtrim(base64_encode($bytes), '='),
            'base64url'         => self::base64UrlEncode($bytes),
            'base32'            => Base32::encode($bytes),
            'urlencode (form)'  => urlencode($bytes),     // space -> +, "~" -> %7E
            'rawurlencode'      => rawurlencode($bytes),  // RFC 3986: space -> %20
            'quoted-printable'  => quoted_printable_encode($bytes),
        ];
    }

    /** Size cost of each form relative to the input, as a ratio. */
    public static function overhead(string $bytes): array
    {
        $n = max(strlen($bytes), 1);

        return array_map(static fn (string $s): float => round(strlen($s) / $n, 2), self::allForms($bytes));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/**
 * RFC 4648 Base32 (A-Z, 2-7), upper-case, optional padding. This is the
 * alphabet authenticator apps use for TOTP secrets (RFC 6238 only
 * specifies the key bytes; the otpauth:// URI uses Base32).
 */
final class Base32
{
    private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

    public static function encode(string $bytes, bool $pad = true): string
    {
        $bits = '';
        foreach (str_split($bytes) as $char) {
            $bits .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
        }

        $out = '';
        foreach (str_split($bits, 5) as $chunk) {
            // The last group is zero-extended to 5 bits (the "pad bits" of RFC 4648).
            $out .= self::ALPHABET[bindec(str_pad($chunk, 5, '0'))];
        }

        return $pad ? str_pad($out, (int) (ceil(strlen($out) / 8) * 8), '=') : $out;
    }

    public static function decode(string $text): string
    {
        // Case-insensitive on input, as authenticator apps print secrets in groups of four.
        $text = strtoupper(str_replace([' ', '-', '='], '', $text));

        $bits = '';
        foreach (str_split($text) as $char) {
            $value = strpos(self::ALPHABET, $char);
            if ($value === false) {
                throw new InvalidArgumentException("Invalid Base32 character: {$char}");
            }
            $bits .= str_pad(decbin($value), 5, '0', STR_PAD_LEFT);
        }

        $out = '';
        foreach (str_split($bits, 8) as $byte) {
            if (strlen($byte) === 8) { // drop the trailing pad bits
                $out .= chr((int) bindec($byte));
            }
        }

        return $out;
    }
}

مسئلهٔ ۲: + که فاصله شد (و double encoding) ​

SolutionHowAdvantageCost
Encode every query valueurl.Values.Encode, http_build_query, URLSearchParamscorrect for any valuemust remember at every call site
base64url instead of base64RawURLEncodingno + or / existsother side must accept base64url
Never decode twicedecode where the value leaves the URL, onceno %2520needs discipline across proxies
go
// Command urlbug reproduces the classic "+ became a space" bug and the
// double-encoding bug, then shows the correct way to build and read queries.
package main

import (
	"encoding/base64"
	"fmt"
	"net/url"
)

func main() {
	token := base64.StdEncoding.EncodeToString([]byte{0xfb, 0xef, 0xbe, 0xff, 0xfe}) // contains + and /
	fmt.Println("token:", token)

	// BUG: concatenating the raw value into the query string.
	broken := "https://api.example.test/verify?token=" + token
	u, _ := url.Parse(broken)
	got := u.Query().Get("token")
	fmt.Printf("broken URL : %s\n", broken)
	fmt.Printf("server sees: %q  (same as sent? %v)\n\n", got, got == token)

	// FIX 1: let net/url encode the value.
	v := url.Values{}
	v.Set("token", token)
	fixed := "https://api.example.test/verify?" + v.Encode()
	u2, _ := url.Parse(fixed)
	got2 := u2.Query().Get("token")
	fmt.Printf("fixed URL  : %s\n", fixed)
	fmt.Printf("server sees: %q  (same as sent? %v)\n\n", got2, got2 == token)

	// FIX 2: do not put '+' and '/' on the wire at all.
	urlSafe := base64.RawURLEncoding.EncodeToString([]byte{0xfb, 0xef, 0xbe, 0xff, 0xfe})
	fmt.Println("base64url  :", urlSafe)

	// Double encoding: encoding an already-encoded value.
	once := url.QueryEscape("a b&c=d")
	twice := url.QueryEscape(once)
	decodedOnce, _ := url.QueryUnescape(twice)
	fmt.Printf("\nonce  : %s\ntwice : %s\ndecode(twice) once -> %s  (still encoded)\n", once, twice, decodedOnce)

	// '+' versus %20: the same string, two different rules.
	fmt.Println("\nQueryEscape(\"a b+c\") =", url.QueryEscape("a b+c"))
	fmt.Println("PathEscape (\"a b+c\") =", url.PathEscape("a b+c"))
	pu, _ := url.Parse("https://example.test/files/a+b%20c?q=a+b%20c")
	fmt.Printf("path decoded: %q   query decoded: %q\n", pu.Path, pu.Query().Get("q"))
}

خروجی واقعی:

text
token: ++++//4=
broken URL : https://api.example.test/verify?token=++++//4=
server sees: "    //4="  (same as sent? false)

fixed URL  : https://api.example.test/verify?token=%2B%2B%2B%2B%2F%2F4%3D
server sees: "++++//4="  (same as sent? true)

base64url  : ----__4

once  : a+b%26c%3Dd
twice : a%2Bb%2526c%253Dd
decode(twice) once -> a+b%26c%3Dd  (still encoded)

QueryEscape("a b+c") = a+b%2Bc
PathEscape ("a b+c") = a%20b+c
path decoded: "/files/a+b c"   query decoded: "a b c"
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/**
 * Reproduces and fixes the "+ became a space" bug. PHP decodes a query
 * string with form rules (plus means space), so a raw standard-base64
 * value loses every "+".
 */
final class UrlBug
{
    public static function demo(): void
    {
        $token = base64_encode("\xfb\xef\xbe\xff\xfe"); // "++++//4="

        // BUG: concatenating the value into the query string.
        $broken = 'https://api.example.test/verify?token=' . $token;
        parse_str((string) parse_url($broken, PHP_URL_QUERY), $query);
        var_dump($query['token'] === $token); // bool(false): "    //4="

        // FIX 1: let http_build_query encode it (RFC 1738 by default: space -> +, "+" -> %2B).
        $fixed = 'https://api.example.test/verify?' . http_build_query(['token' => $token]);
        parse_str((string) parse_url($fixed, PHP_URL_QUERY), $query);
        var_dump($query['token'] === $token); // bool(true)

        // FIX 2: RFC 3986 encoding for query values that are not form posts.
        echo http_build_query(['q' => 'a b+c'], '', '&', PHP_QUERY_RFC3986), PHP_EOL; // q=a%20b%2Bc

        // FIX 3: do not put "+" and "/" on the wire at all.
        echo Encodings::base64UrlEncode("\xfb\xef\xbe\xff\xfe"), PHP_EOL; // ----__4

        // Double encoding: encode once at the boundary, never twice.
        $once = rawurlencode('a b&c=d');   // a%20b%26c%3Dd
        $twice = rawurlencode($once);      // a%2520b%2526c%253Dd
        echo rawurldecode($twice), PHP_EOL; // a%20b%26c%3Dd  (still encoded)

        // Path segment versus query value: "+" is only a space in the query.
        echo urldecode('a+b%20c'), '|', rawurldecode('a+b%20c'), PHP_EOL; // "a b c" | "a+b c"
    }
}

مسئلهٔ ۳: padding حذف‌شده، الفبای اشتباه، بیت‌های شل ​

go
// Command padding shows how Go's base64 decoders treat padding,
// whitespace, the two alphabets and trailing bits.
package main

import (
	"encoding/base64"
	"fmt"
)

func try(name string, enc *base64.Encoding, in string) {
	out, err := enc.DecodeString(in)
	if err != nil {
		fmt.Printf("%-34s %-22q -> error: %v\n", name, in, err)
		return
	}
	fmt.Printf("%-34s %-22q -> %q\n", name, in, out)
}

func main() {
	// "hi!" is 3 bytes: no padding needed. "hi" is 2 bytes: one '='.
	try("Std, padded input", base64.StdEncoding, "aGkh")
	try("Std, 2 bytes, padded", base64.StdEncoding, "aGk=")
	try("Std, 2 bytes, padding stripped", base64.StdEncoding, "aGk")
	try("RawStd, padding present", base64.RawStdEncoding, "aGk=")
	try("RawStd, padding stripped", base64.RawStdEncoding, "aGk")

	// Alphabet mix-ups: '+' and '/' vs '-' and '_'.
	try("Std decodes url-safe input", base64.StdEncoding, "-_-_")
	try("URL decodes std input", base64.URLEncoding, "+/+/")

	// Go silently drops CR and LF but nothing else.
	try("Std, MIME line break inside", base64.StdEncoding, "aGVs\r\nbG8h")
	try("Std, space inside", base64.StdEncoding, "aGVs bG8h")

	// Non-zero trailing bits: "aGl=" decodes like "aGk=" unless Strict.
	try("Std, sloppy trailing bits", base64.StdEncoding, "aGl=")
	try("Std.Strict(), sloppy trailing bits", base64.StdEncoding.Strict(), "aGl=")

	// A percent-encoded '=' from a query string is not base64.
	try("Std, still percent-encoded", base64.StdEncoding, "aGk%3D")
}

خروجی واقعی (offset اولین خطاها گزارش Go است، نه تعهد):

text
Std, padded input                  "aGkh"                 -> "hi!"
Std, 2 bytes, padded               "aGk="                 -> "hi"
Std, 2 bytes, padding stripped     "aGk"                  -> error: illegal base64 data at input byte 0
RawStd, padding present            "aGk="                 -> error: illegal base64 data at input byte 3
RawStd, padding stripped           "aGk"                  -> "hi"
Std decodes url-safe input         "-_-_"                 -> error: illegal base64 data at input byte 0
URL decodes std input              "+/+/"                 -> error: illegal base64 data at input byte 0
Std, MIME line break inside        "aGVs\r\nbG8h"         -> "hello!"
Std, space inside                  "aGVs bG8h"            -> error: illegal base64 data at input byte 4
Std, sloppy trailing bits          "aGl="                 -> "hi"
Std.Strict(), sloppy trailing bits "aGl="                 -> error: illegal base64 data at input byte 3
Std, still percent-encoded         "aGk%3D"               -> error: illegal base64 data at input byte 3

PHP: از base64UrlDecode در Encodings.php استفاده کنید (دوباره pad می‌کند و بعد base64_decode(..., strict: true)).

مسئلهٔ ۴: decode کردن base64 دست مهاجم و محدودیت طول ​

SolutionHowAdvantageCost
Cap before decodereject len(s) > max; http.MaxBytesReader; Laravel max:no big allocationchoose a sensible limit
Decode strictlyGo Strict(); PHP strict: truerejects noise and ambiguitybreaks lenient producers
Cap after decodeDecodedLen checkcatches expansion trickstiny
Verify content, not labelcheck PNG/JPEG magic bytes, re-encode imagesstops disguised payloadsmore code
go
// Command safedecode shows how to accept base64 from an untrusted client:
// cap the encoded length before decoding, decode strictly, cap the decoded
// size, and never trust what the bytes claim to be.
package main

import (
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

const (
	maxEncoded = 4 * 1024 // 4 KiB of base64 is plenty for a token or avatar hash
)

var ErrTooLarge = errors.New("payload too large")

// DecodeUntrusted decodes standard padded base64 with a hard size limit.
func DecodeUntrusted(s string) ([]byte, error) {
	if len(s) > maxEncoded {
		return nil, ErrTooLarge // reject before allocating anything
	}
	enc := base64.StdEncoding.Strict() // reject non-zero trailing bits
	// Refuse whitespace and line breaks: the lenient decoder would skip CR/LF.
	if strings.ContainsAny(s, "\r\n \t") {
		return nil, errors.New("whitespace not allowed")
	}
	out := make([]byte, enc.DecodedLen(len(s)))
	n, err := enc.Decode(out, []byte(s))
	if err != nil {
		return nil, err
	}
	return out[:n], nil
}

// handler reads a JSON-free body that is itself base64, with a body cap.
func handler(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, maxEncoded+1) // cap the read, not just the decode
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "too large", http.StatusRequestEntityTooLarge)
		return
	}
	raw, err := DecodeUntrusted(string(body))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "ok %d bytes", len(raw))
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handler))
	defer srv.Close()

	cases := []struct{ name, body string }{
		{"valid", base64.StdEncoding.EncodeToString([]byte("hello"))},
		{"newline injected", "aGVs\nbG8="},
		{"sloppy trailing bits", "aGl="},
		{"oversize", strings.Repeat("A", 10_000)},
	}
	for _, c := range cases {
		resp, err := http.Post(srv.URL, "text/plain", strings.NewReader(c.body))
		if err != nil {
			panic(err)
		}
		b, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		fmt.Printf("%-22s -> %d %s\n", c.name, resp.StatusCode, strings.TrimSpace(string(b)))
	}
}

خروجی واقعی:

text
valid                  -> 200 ok 5 bytes
newline injected       -> 400 whitespace not allowed
sloppy trailing bits   -> 400 illegal base64 data at input byte 3
oversize               -> 413 too large
php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Accepting base64 from an untrusted client: cap the encoded length first,
 * decode strictly, cap the decoded size, then verify what the bytes are.
 */
final class SafeBase64Controller extends Controller
{
    private const MAX_ENCODED = 4096;

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            // max applies to the string length, before any decoding happens.
            // The regex ends in \z, not $, because "$" would accept a trailing newline.
            'avatar' => ['required', 'string', 'max:' . self::MAX_ENCODED, 'regex:/^[A-Za-z0-9+\/]+={0,2}\z/'],
        ]);

        // Str::fromBase64 is base64_decode($value, $strict); pass true to reject stray characters.
        $bytes = Str::fromBase64($request->string('avatar')->toString(), strict: true);
        abort_if($bytes === false, 422, 'avatar is not valid base64');

        // Do not trust the label: inspect the bytes (PNG signature here).
        abort_unless(str_starts_with($bytes, "\x89PNG\r\n\x1a\n"), 422, 'avatar must be a PNG');

        return response()->json(['bytes' => strlen($bytes)]);
    }
}

مسئلهٔ ۵: فایل بزرگ با حافظهٔ ثابت ​

go
// Command stream base64-encodes and decodes a large file in constant
// memory, optionally wrapping lines at 76 characters as MIME requires.
package main

import (
	"bufio"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// lineWrapper inserts CRLF after every n bytes written (RFC 2045: n = 76).
type lineWrapper struct {
	w   io.Writer
	n   int
	col int
}

func (l *lineWrapper) Write(p []byte) (int, error) {
	written := 0
	for len(p) > 0 {
		room := l.n - l.col
		chunk := p
		if len(chunk) > room {
			chunk = chunk[:room]
		}
		if _, err := l.w.Write(chunk); err != nil {
			return written, err
		}
		written += len(chunk)
		l.col += len(chunk)
		p = p[len(chunk):]
		if l.col == l.n {
			if _, err := l.w.Write([]byte("\r\n")); err != nil {
				return written, err
			}
			l.col = 0
		}
	}
	return written, nil
}

func encodeFile(src, dst string, mime bool) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	bw := bufio.NewWriterSize(out, 64*1024)
	var sink io.Writer = bw
	if mime {
		sink = &lineWrapper{w: bw, n: 76}
	}
	enc := base64.NewEncoder(base64.StdEncoding, sink)
	if _, err := io.Copy(enc, in); err != nil { // 32 KiB at a time
		return err
	}
	if err := enc.Close(); err != nil { // flushes the final partial group and padding
		return err
	}
	return bw.Flush()
}

func decodeFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()
	// The decoder skips CR and LF, so MIME-wrapped input works unchanged.
	_, err = io.Copy(out, base64.NewDecoder(base64.StdEncoding, bufio.NewReaderSize(in, 64*1024)))
	return err
}

func sum(path string) string {
	f, _ := os.Open(path)
	defer f.Close()
	h := sha256.New()
	_, _ = io.Copy(h, f)
	return fmt.Sprintf("%x", h.Sum(nil))[:16]
}

func main() {
	dir, _ := os.MkdirTemp("", "b64")
	defer os.RemoveAll(dir)
	src := filepath.Join(dir, "big.bin")

	// 100 MiB of deterministic bytes, written without holding them in memory.
	f, _ := os.Create(src)
	block := make([]byte, 1<<20)
	for i := range block {
		block[i] = byte(i * 31)
	}
	for i := 0; i < 100; i++ {
		_, _ = f.Write(block)
	}
	f.Close()

	enc, back := filepath.Join(dir, "big.b64"), filepath.Join(dir, "big.out")
	if err := encodeFile(src, enc, true); err != nil {
		panic(err)
	}
	if err := decodeFile(enc, back); err != nil {
		panic(err)
	}
	a, _ := os.Stat(src)
	b, _ := os.Stat(enc)
	fmt.Printf("source %d bytes, base64+MIME %d bytes (%.3fx)\n", a.Size(), b.Size(), float64(b.Size())/float64(a.Size()))
	fmt.Printf("sha256 before %s, after %s\n", sum(src), sum(back))
}

خروجی واقعی (۱۰۰ مگابایت، با خط‌شکن MIME، رفت‌وبرگشت تأییدشده):

text
source 104857600 bytes, base64+MIME 143489350 bytes (1.368x)
sha256 before 7264223ed5715d75, after 7264223ed5715d75
maximum resident set size: 9748480 bytes   (from /usr/bin/time -l on the built binary)
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use RuntimeException;

/**
 * Base64 a large file in constant memory with PHP stream filters.
 * convert.base64-encode accepts line-length and line-break-chars, which
 * gives MIME-style wrapping at 76 characters.
 */
final class StreamBase64
{
    public static function encodeFile(string $source, string $target, bool $mime = true): void
    {
        $in = fopen($source, 'rb');
        $out = fopen($target, 'wb');
        if ($in === false || $out === false) {
            throw new RuntimeException('Cannot open files');
        }

        $params = $mime ? ['line-length' => 76, 'line-break-chars' => "\r\n"] : [];
        $filter = stream_filter_append($out, 'convert.base64-encode', STREAM_FILTER_WRITE, $params);

        stream_copy_to_stream($in, $out); // copies in 8 KiB chunks; memory stays flat

        stream_filter_remove($filter); // flushes the final partial group and the "=" padding
        fclose($in);
        fclose($out);
    }

    public static function decodeFile(string $source, string $target): void
    {
        $in = fopen($source, 'rb');
        $out = fopen($target, 'wb');
        stream_filter_append($in, 'convert.base64-decode', STREAM_FILTER_READ);
        stream_copy_to_stream($in, $out);
        fclose($in);
        fclose($out);
    }
}

مسئلهٔ ۶: ساخت و parse امن data URI ​

go
// Command datauri builds an RFC 2397 data URI from a generated PNG and
// parses one back, with a size cap so a hostile value cannot exhaust memory.
package main

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"image"
	"image/color"
	"image/png"
	"net/url"
	"strings"
)

const maxDecoded = 64 * 1024 // refuse inline payloads above 64 KiB

func buildPNG() []byte {
	img := image.NewRGBA(image.Rect(0, 0, 16, 16))
	for y := 0; y < 16; y++ {
		for x := 0; x < 16; x++ {
			img.Set(x, y, color.RGBA{R: uint8(x * 16), G: uint8(y * 16), B: 128, A: 255})
		}
	}
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		panic(err)
	}
	return buf.Bytes()
}

// Encode returns data:<mediatype>;base64,<payload>.
func Encode(mediaType string, payload []byte) string {
	return "data:" + mediaType + ";base64," + base64.StdEncoding.EncodeToString(payload)
}

// EncodeText returns a non-base64 data URI where the payload is percent-encoded.
func EncodeText(mediaType, text string) string {
	return "data:" + mediaType + "," + url.PathEscape(text)
}

// Decode parses data:[<mediatype>][;base64],<data> and enforces a size cap.
func Decode(uri string) (mediaType string, payload []byte, err error) {
	rest, ok := strings.CutPrefix(uri, "data:")
	if !ok {
		return "", nil, errors.New("not a data URI")
	}
	meta, data, ok := strings.Cut(rest, ",")
	if !ok {
		return "", nil, errors.New("missing comma")
	}
	isB64 := false
	if m, found := strings.CutSuffix(meta, ";base64"); found {
		meta, isB64 = m, true
	}
	if meta == "" {
		meta = "text/plain;charset=US-ASCII" // RFC 2397 default
	}
	if isB64 {
		if base64.StdEncoding.DecodedLen(len(data)) > maxDecoded {
			return "", nil, errors.New("data URI too large")
		}
		payload, err = base64.StdEncoding.DecodeString(data)
	} else {
		if len(data) > maxDecoded {
			return "", nil, errors.New("data URI too large")
		}
		var s string
		s, err = url.PathUnescape(data)
		payload = []byte(s)
	}
	return meta, payload, err
}

func main() {
	pngBytes := buildPNG()
	uri := Encode("image/png", pngBytes)
	fmt.Printf("png bytes: %d, data URI length: %d (%.2fx)\n", len(pngBytes), len(uri), float64(len(uri))/float64(len(pngBytes)))
	fmt.Println(uri[:60] + "...")
	fmt.Printf("<img src=%q>\n", uri[:40]+"...")

	mt, back, err := Decode(uri)
	fmt.Printf("decoded: type=%s bytes=%d same=%v err=%v\n", mt, len(back), bytes.Equal(back, pngBytes), err)

	txt := EncodeText("text/plain;charset=UTF-8", "سلام & hello")
	fmt.Println(txt)
	mt, back, err = Decode(txt)
	fmt.Printf("decoded: type=%s text=%q err=%v\n", mt, back, err)

	_, _, err = Decode("data:application/octet-stream;base64," + strings.Repeat("A", 200_000))
	fmt.Println("oversize:", err)
}

خروجی واقعی:

text
png bytes: 86, data URI length: 138 (1.60x)
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAA...
<img src="data:image/png;base64,iVBORw0KGgoAAAANSU...">
decoded: type=image/png bytes=86 same=true err=<nil>
data:text/plain;charset=UTF-8,%D8%B3%D9%84%D8%A7%D9%85%20&%20hello
decoded: type=text/plain;charset=UTF-8 text="سلام & hello" err=<nil>
oversize: data URI too large
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/** RFC 2397 data URIs with a size cap. */
final class DataUri
{
    private const MAX_DECODED = 64 * 1024;

    public static function fromFile(string $path): string
    {
        $mime = mime_content_type($path) ?: 'application/octet-stream';

        return 'data:' . $mime . ';base64,' . base64_encode((string) file_get_contents($path));
    }

    /** @return array{mediaType: string, bytes: string} */
    public static function parse(string $uri): array
    {
        if (! str_starts_with($uri, 'data:') || ! str_contains($uri, ',')) {
            throw new InvalidArgumentException('Not a data URI');
        }

        [$meta, $data] = explode(',', substr($uri, 5), 2);
        $isBase64 = str_ends_with($meta, ';base64');
        $mediaType = $isBase64 ? substr($meta, 0, -7) : $meta;
        $mediaType = $mediaType === '' ? 'text/plain;charset=US-ASCII' : $mediaType; // RFC 2397 default

        // Check the size before decoding anything.
        if (strlen($data) > self::MAX_DECODED * 4 / 3 + 4) {
            throw new InvalidArgumentException('Data URI too large');
        }

        $bytes = $isBase64 ? base64_decode($data, strict: true) : rawurldecode($data);
        if ($bytes === false || strlen($bytes) > self::MAX_DECODED) {
            throw new InvalidArgumentException('Invalid or oversized data URI');
        }

        return ['mediaType' => $mediaType, 'bytes' => $bytes];
    }
}

مسئلهٔ ۷: Crockford، z-base-32، Base58 و secret های TOTP ​

go
// Command alphabets implements the "other" bases from first principles:
// Crockford Base32 with its check symbol, z-base-32, Base58 (Bitcoin
// alphabet) and Git's Base85, and decodes a TOTP-style Base32 secret.
package main

import (
	"encoding/base32"
	"fmt"
	"math/big"
	"strings"
)

// Crockford Base32: no I, L, O, U; encode uppercase, decode case-insensitive.
const crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

var crockfordEnc = base32.NewEncoding(crockford).WithPadding(base32.NoPadding)

// normalizeCrockford applies the decoding rules: ignore hyphens, fold case,
// map I and L to 1 and O to 0.
func normalizeCrockford(s string) string {
	s = strings.ToUpper(strings.ReplaceAll(s, "-", ""))
	r := strings.NewReplacer("I", "1", "L", "1", "O", "0")
	return r.Replace(s)
}

// zbase32 is Zooko's human-oriented alphabet.
var zbase32Enc = base32.NewEncoding("ybndrfg8ejkmcpqxot1uwisza345h769").WithPadding(base32.NoPadding)

const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

// Base58Encode converts bytes to Base58; each leading zero byte becomes '1'.
func Base58Encode(in []byte) string {
	n := new(big.Int).SetBytes(in)
	base := big.NewInt(58)
	mod := new(big.Int)
	var out []byte
	for n.Sign() > 0 {
		n.DivMod(n, base, mod)
		out = append(out, base58Alphabet[mod.Int64()])
	}
	for _, b := range in {
		if b != 0 {
			break
		}
		out = append(out, base58Alphabet[0])
	}
	for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
		out[i], out[j] = out[j], out[i]
	}
	return string(out)
}

// Base58Decode reverses Base58Encode.
func Base58Decode(s string) ([]byte, error) {
	n := new(big.Int)
	base := big.NewInt(58)
	for _, c := range s {
		i := strings.IndexRune(base58Alphabet, c)
		if i < 0 {
			return nil, fmt.Errorf("invalid base58 character %q", c)
		}
		n.Mul(n, base)
		n.Add(n, big.NewInt(int64(i)))
	}
	out := n.Bytes()
	zeros := 0
	for zeros < len(s) && s[zeros] == base58Alphabet[0] {
		zeros++
	}
	return append(make([]byte, zeros), out...), nil
}

func main() {
	data := []byte{0x00, 0x00, 0x01, 0x02, 0x03, 0xff, 0xee}
	fmt.Println("bytes          :", fmt.Sprintf("% x", data))
	fmt.Println("base58         :", Base58Encode(data))
	back, _ := Base58Decode(Base58Encode(data))
	fmt.Printf("round trip     : % x\n", back)

	// Crockford
	c := crockfordEnc.EncodeToString([]byte("hello"))
	fmt.Println("crockford      :", c)
	typed := "d1jprv3f" // lower case, '1' typed as 'l' still decodes
	typed = strings.Replace(typed, "1", "l", 1)
	dec, _ := crockfordEnc.DecodeString(normalizeCrockford(typed))
	fmt.Printf("crockford typed %q -> %q\n", typed, dec)

	// z-base-32
	fmt.Println("z-base-32      :", zbase32Enc.EncodeToString([]byte("hello")))

	// TOTP secrets are RFC 4648 base32: upper-case, usually unpadded in apps.
	secret := "JBSWY3DPEHPK3PXP"
	key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(strings.ReplaceAll(secret, " ", "")))
	fmt.Printf("TOTP secret %s -> %d bytes % x err=%v\n", secret, len(key), key, err)
}

خروجی واقعی:

text
bytes          : 00 00 01 02 03 ff ee
base58         : 117bX9dP
round trip     : 00 00 01 02 03 ff ee
crockford      : D1JPRV3F
crockford typed "dljprv3f" -> "hello"
z-base-32      : pb1sa5dx
TOTP secret JBSWY3DPEHPK3PXP -> 10 bytes 48 65 6c 6c 6f 21 de ad be ef err=<nil>
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/**
 * Base58 with the Bitcoin alphabet: no 0, O, I, l; no "+" or "/".
 * Leading zero bytes become leading "1" characters.
 * Plain integer arithmetic on a digit array, so no gmp/bcmath is needed.
 */
final class Base58
{
    private const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

    public static function encode(string $bytes): string
    {
        $digits = [0]; // base-58 digits, least significant first
        foreach (str_split($bytes) as $char) {
            $carry = ord($char);
            foreach ($digits as $i => $d) {
                $carry += $d << 8;
                $digits[$i] = $carry % 58;
                $carry = intdiv($carry, 58);
            }
            while ($carry > 0) {
                $digits[] = $carry % 58;
                $carry = intdiv($carry, 58);
            }
        }

        $out = '';
        foreach ($digits as $d) {
            $out = self::ALPHABET[$d] . $out;
        }
        $out = ltrim($out, '1'); // the all-zero value has no digits of its own
        $leadingZeros = strlen($bytes) - strlen(ltrim($bytes, "\0"));

        return str_repeat('1', $leadingZeros) . $out;
    }

    public static function decode(string $text): string
    {
        $bytes = [0]; // base-256 digits, least significant first
        foreach (str_split($text) as $char) {
            $carry = strpos(self::ALPHABET, $char);
            if ($carry === false) {
                throw new InvalidArgumentException("Invalid Base58 character: {$char}");
            }
            foreach ($bytes as $i => $b) {
                $carry += $b * 58;
                $bytes[$i] = $carry & 0xFF;
                $carry >>= 8;
            }
            while ($carry > 0) {
                $bytes[] = $carry & 0xFF;
                $carry >>= 8;
            }
        }

        $out = '';
        foreach ($bytes as $b) {
            $out = chr($b) . $out;
        }
        $out = ltrim($out, "\0");
        $leadingOnes = strlen($text) - strlen(ltrim($text, '1'));

        return str_repeat("\0", $leadingOnes) . $out;
    }
}

مسئلهٔ ۸: دامنه‌ها و URLهای فارسی (IDNA) ​

go
// Command idna converts internationalized domain names between Unicode and
// the ASCII "xn--" form (Punycode, RFC 3492; IDNA 2008 via x/net/idna) and
// shows the two spellings of a Persian URL: IRI versus URI.
package main

import (
	"fmt"
	"net/url"

	"golang.org/x/net/idna"
)

func main() {
	for _, host := range []string{"مثال.ایران", "bücher.example", "例え.jp"} {
		ascii, err := idna.Lookup.ToASCII(host)
		back, _ := idna.Lookup.ToUnicode(ascii)
		fmt.Printf("%-18s -> %-28s -> %s (err=%v)\n", host, ascii, back, err)
	}

	// An IRI (RFC 3987) with a Persian path and query.
	iri := "https://مثال.ایران/مقاله/سلام?q=دنیا"
	u, err := url.Parse(iri)
	if err != nil {
		panic(err)
	}
	host, _ := idna.Lookup.ToASCII(u.Hostname())
	u.Host = host
	fmt.Println("IRI :", iri)
	fmt.Println("URI :", u.String())
	fmt.Println("path:", u.EscapedPath(), " raw query:", u.RawQuery)
}

خروجی واقعی:

text
مثال.ایران         -> xn--mgbh0fb.xn--mgba3a4f16a  -> مثال.ایران (err=<nil>)
bücher.example     -> xn--bcher-kva.example        -> bücher.example (err=<nil>)
例え.jp              -> xn--r8jz45g.jp               -> 例え.jp (err=<nil>)
IRI : https://مثال.ایران/مقاله/سلام?q=دنیا
URI : https://xn--mgbh0fb.xn--mgba3a4f16a/%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85?q=دنیا
path: /%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85  raw query: q=دنیا

مسئلهٔ ۹: HTML، JSON، quoted-printable و headerهای MIME ​

go
// Command boundaries shows the "other encodings" that guard other
// boundaries: HTML entities, JSON string escapes, quoted-printable and
// MIME encoded-words in mail headers. None of them is base64.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html"
	"mime"
	"mime/quotedprintable"
	"strings"
)

func main() {
	in := `<a href="/?q=1&x=2">Tom & "Jerry"</a>`
	fmt.Println("HTML escape :", html.EscapeString(in))
	fmt.Println("HTML unesc  :", html.UnescapeString("&lt;b&gt; &amp;amp; &#1587;&#x644; &eacute;"))

	// JSON escapes are for the JSON string boundary: quote, backslash, control chars.
	v := map[string]string{"s": "line1\nline2 \"q\" <tag> & 
 سلام"}
	b, _ := json.Marshal(v)
	fmt.Println("json default:", string(b))
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	_ = enc.Encode(v)
	fmt.Print("json no-HTML:", " ", buf.String())

	// Quoted-printable: readable text stays readable, other bytes become =XX.
	var qp bytes.Buffer
	w := quotedprintable.NewWriter(&qp)
	_, _ = w.Write([]byte("Café = 5€, " + strings.Repeat("long ", 20)))
	_ = w.Close()
	fmt.Println("\nquoted-printable:")
	fmt.Print(qp.String(), "\n")

	// RFC 2047 encoded-words for non-ASCII mail headers: Q (QP-like) and B (base64).
	fmt.Println("subject Q:", mime.QEncoding.Encode("utf-8", "سلام"))
	fmt.Println("subject B:", mime.BEncoding.Encode("utf-8", "سلام"))
	dec := new(mime.WordDecoder)
	s, _ := dec.DecodeHeader("=?utf-8?b?2LPZhNin2YU=?=")
	fmt.Println("decoded   :", s)
}

خروجی واقعی:

text
HTML escape : &lt;a href=&#34;/?q=1&amp;x=2&#34;&gt;Tom &amp; &#34;Jerry&#34;&lt;/a&gt;
HTML unesc  : <b> &amp; سل é
json default: {"s":"line1\nline2 \"q\" <tag> & 
 سلام"}
json no-HTML: {"s":"line1\nline2 \"q\" <tag> & 
 سلام"}

quoted-printable:
Caf=C3=A9 =3D 5=E2=82=AC, long long long long long long long long long long=
 long long long long long long long long long long=20
subject Q: =?utf-8?q?=D8=B3=D9=84=D8=A7=D9=85?=
subject B: =?utf-8?b?2LPZhNin2YU=?=
decoded   : سلام
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/** Encodings that guard other boundaries: HTML, JSON, MIME headers, domains. */
final class Boundaries
{
    public static function demo(): void
    {
        $in = '<a href="/?q=1&x=2">Tom & "Jerry"</a>';

        // HTML boundary. ENT_QUOTES also escapes the single quote; always pass the charset.
        echo htmlspecialchars($in, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), PHP_EOL;

        // JSON boundary: PHP escapes "/" and non-ASCII by default; both flags are readability choices.
        echo json_encode(['s' => "line1\nline2 \"q\" <tag> / سلام"]), PHP_EOL;
        echo json_encode(['s' => "line1\nline2 \"q\" <tag> / سلام"], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
        echo json_encode(['s' => '<tag> & "q"'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT), PHP_EOL; // safe inside HTML

        // Quoted-printable (MIME body) and RFC 2047 encoded-words (MIME header).
        echo quoted_printable_encode("Café = 5€"), PHP_EOL;                 // Caf=C3=A9 =3D 5=E2=82=AC
        echo mb_encode_mimeheader('سلام', 'UTF-8', 'B'), PHP_EOL;           // =?UTF-8?B?2LPZhNin2YU=?=

        // Domain boundary (ext-intl): Unicode host <-> xn-- host.
        echo idn_to_ascii('مثال.ایران', IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46), PHP_EOL;
        echo idn_to_utf8('xn--mgbh0fb.xn--mgba3a4f16a', IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46), PHP_EOL;
    }
}

مسئلهٔ ۱۰: JWT، Basic auth و Kubernetes Secret ​

go
// Command tokens decodes the three base64 payloads a developer inspects
// most often: a JWT (base64url, no padding), a Kubernetes Secret value
// (standard base64) and an HTTP Basic Authorization header.
package main

import (
	"bufio"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func b64u(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }

// makeJWT builds an HS256 token by hand so the three segments are visible.
func makeJWT(secret []byte, claims map[string]any) string {
	header, _ := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"})
	payload, _ := json.Marshal(claims)
	signingInput := b64u(header) + "." + b64u(payload)
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(signingInput))
	return signingInput + "." + b64u(mac.Sum(nil))
}

// inspectJWT decodes header and payload WITHOUT verifying the signature.
func inspectJWT(tok string) {
	parts := strings.Split(tok, ".")
	if len(parts) != 3 {
		fmt.Println("not a compact JWS")
		return
	}
	for i, name := range []string{"header", "payload"} {
		raw, err := base64.RawURLEncoding.DecodeString(parts[i])
		fmt.Printf("%-8s %s  (err=%v)\n", name, raw, err)
	}
	sig, _ := base64.RawURLEncoding.DecodeString(parts[2])
	fmt.Printf("%-8s %d bytes (HMAC-SHA256 output)\n", "sig", len(sig))
}

// k8sSecret is the part of `kubectl get secret -o json` we care about.
type k8sSecret struct {
	Data map[string][]byte `json:"data"` // encoding/json decodes std base64 into []byte
}

func main() {
	tok := makeJWT([]byte("demo-secret"), map[string]any{"sub": "42", "name": "مرتضی", "iat": 1764000000})
	fmt.Println("JWT:", tok)
	inspectJWT(tok)

	// HTTP Basic: base64("user:password"), RFC 7617. This is NOT encryption.
	req, _ := http.NewRequest("GET", "https://example.test/", nil)
	req.SetBasicAuth("morteza", "p@ss:word")
	hdr := req.Header.Get("Authorization")
	fmt.Println("\nAuthorization:", hdr)
	raw, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(hdr, "Basic "))
	fmt.Printf("decoded      : %s\n", raw)

	// Kubernetes Secret JSON on stdin (optional).
	if fi, _ := os.Stdin.Stat(); fi.Mode()&os.ModeCharDevice == 0 {
		var s k8sSecret
		if err := json.NewDecoder(bufio.NewReader(os.Stdin)).Decode(&s); err == nil {
			fmt.Println("\nKubernetes Secret keys decoded:")
			for k, v := range s.Data {
				fmt.Printf("  %-10s = %q\n", k, v)
			}
		}
	}
}

خروجی واقعی (با kubectl create secret ... --dry-run=client -o json | go run ./tokens):

text
JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3NjQwMDAwMDAsIm5hbWUiOiLZhdix2KrYttuMIiwic3ViIjoiNDIifQ.D7xYjF12Q1bFykenEVYi8222lSfbHXYUMlrYkUgtPNA
header   {"alg":"HS256","typ":"JWT"}  (err=<nil>)
payload  {"iat":1764000000,"name":"مرتضی","sub":"42"}  (err=<nil>)
sig      32 bytes (HMAC-SHA256 output)

Authorization: Basic bW9ydGV6YTpwQHNzOndvcmQ=
decoded      : morteza:p@ss:word

Kubernetes Secret keys decoded:
  password   = "p@ss/w+rd"
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/** Decode the three base64 payloads a developer inspects most often. */
final class Tokens
{
    /** @return array{header: array, payload: array} NOT verified: never trust this for auth. */
    public static function inspectJwt(string $jwt): array
    {
        [$h, $p] = array_slice(explode('.', $jwt), 0, 2);

        return [
            'header'  => json_decode((string) Encodings::base64UrlDecode($h), true, flags: JSON_THROW_ON_ERROR),
            'payload' => json_decode((string) Encodings::base64UrlDecode($p), true, flags: JSON_THROW_ON_ERROR),
        ];
    }

    /** HTTP Basic (RFC 7617): base64("user:password"). Encoding, not encryption. */
    public static function basicAuthHeader(string $user, string $password): string
    {
        return 'Basic ' . base64_encode($user . ':' . $password);
    }

    /** @return array{0: string, 1: string} */
    public static function parseBasic(string $header): array
    {
        $decoded = base64_decode(substr($header, 6), strict: true);
        // The first colon separates user from password; the password may contain colons.
        return $decoded === false ? ['', ''] : explode(':', $decoded, 2) + [1 => ''];
    }

    /**
     * Kubernetes Secret .data values are standard base64 of the raw bytes;
     * a trailing newline from `echo` is a classic source of login failures.
     *
     * @param array<string, string> $data the "data" map of a Secret manifest
     * @return array<string, string>
     */
    public static function decodeSecretData(array $data): array
    {
        return array_map(static fn (string $v): string => (string) base64_decode($v, true), $data);
    }
}

مسئلهٔ ۱۱: signed URL و کدگذاری در Laravel ​

signed URL یک HMAC به‌شکل hex روی همان رشتهٔ دقیق URL دارد؛ هر کدگذاری دوباره بعد از امضا آن را باطل می‌کند. با helper بسازید؛ هرگز الصاق نکنید.

php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

/**
 * Laravel signed URLs: the signature is the lower-case hex of
 * hash_hmac('sha256', <full URL>, APP_KEY) in the "signature" query
 * parameter (see Illuminate\Routing\UrlGenerator::signedRoute). The URL
 * is encoded by the route helper; never hand-build the query for a signed URL.
 */
final class SignedUrls extends Controller
{
    public function link(): string
    {
        // Parameters are percent-encoded by the URL generator; the signature covers the encoded form.
        return URL::temporarySignedRoute(
            'unsubscribe',
            now()->plus(minutes: 30),
            ['user' => 1, 'email' => 'a+b@example.test'] // "+" is encoded as %2B, so it survives
        );
    }

    public function unsubscribe(Request $request): string
    {
        // The route has ->middleware('signed'); this is the manual equivalent.
        abort_unless($request->hasValidSignature(), 403);

        return 'ok';
    }
}

مسئلهٔ ۱۲: بودجهٔ حجم و سرعت (benchmark) ​

go
package bench

import (
	"encoding/base64"
	"encoding/hex"
	"math/rand"
	"testing"
)

var payload = func() []byte {
	b := make([]byte, 1<<20)
	rand.New(rand.NewSource(1)).Read(b)
	return b
}()

func BenchmarkBase64Encode(b *testing.B) {
	dst := make([]byte, base64.StdEncoding.EncodedLen(len(payload)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		base64.StdEncoding.Encode(dst, payload)
	}
}

func BenchmarkBase64Decode(b *testing.B) {
	enc := make([]byte, base64.StdEncoding.EncodedLen(len(payload)))
	base64.StdEncoding.Encode(enc, payload)
	dst := make([]byte, base64.StdEncoding.DecodedLen(len(enc)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		if _, err := base64.StdEncoding.Decode(dst, enc); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBase64EncodeToString(b *testing.B) {
	b.SetBytes(int64(len(payload)))
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = base64.StdEncoding.EncodeToString(payload)
	}
}

func BenchmarkHexEncode(b *testing.B) {
	dst := make([]byte, hex.EncodedLen(len(payload)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		hex.Encode(dst, payload)
	}
}
text
BenchmarkBase64Encode-10            	     200	    350122 ns/op	2994.88 MB/s
BenchmarkBase64Decode-10            	     200	    299048 ns/op	3506.38 MB/s
BenchmarkBase64EncodeToString-10    	     200	    412536 ns/op	2541.78 MB/s	 2801701 B/op	       2 allocs/op
BenchmarkHexEncode-10               	     200	    486976 ns/op	2153.24 MB/s

مسئلهٔ ۱۳: یک تصویر چقدر هزینه دارد؟ ​

go
// Command sizes prints how many bytes a file (or a string) becomes under
// each encoding. Usage: sizes -file logo.png   or   sizes -text "سلام"
package main

import (
	"encoding/base64"
	"encoding/hex"
	"flag"
	"fmt"
	"net/url"
	"os"
)

func main() {
	file := flag.String("file", "", "path of a file to measure")
	text := flag.String("text", "", "a string to measure (UTF-8)")
	flag.Parse()

	var raw []byte
	switch {
	case *file != "":
		b, err := os.ReadFile(*file)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		raw = b
	case *text != "":
		raw = []byte(*text)
	default:
		flag.Usage()
		os.Exit(2)
	}

	fmt.Printf("%-16s %10s %8s\n", "encoding", "bytes", "ratio")
	row := func(name string, n int) {
		fmt.Printf("%-16s %10d %7.3fx\n", name, n, float64(n)/float64(len(raw)))
	}
	row("raw", len(raw))
	row("hex", hex.EncodedLen(len(raw)))
	row("base64", base64.StdEncoding.EncodedLen(len(raw)))
	row("base64 raw", base64.RawStdEncoding.EncodedLen(len(raw)))
	row("base64url raw", base64.RawURLEncoding.EncodedLen(len(raw)))
	row("percent (query)", len(url.QueryEscape(string(raw))))
	row("data URI (b64)", len("data:application/octet-stream;base64,")+base64.StdEncoding.EncodedLen(len(raw)))
}

انتخاب ​

SituationRecommendedExtra techniqueReason
Binary in a JSON/XML body (API)standard Base64prefer multipart/binary for files over about 100 KBuniversally supported, +33%
Token, ID, hash in a URL, cookie, filenamebase64url, no paddinglength cap; compare in constant timeno + / = to escape
Value a person will read aloud or typeCrockford Base32 or Base58group in fours, add a check symbolremoves look-alike characters
TOTP/2FA secretRFC 4648 Base32uppercase, strip spaces and =what authenticator apps expect
Debugging, hashes, byte dumpshexgroup by 2 or 4clearest, 2x
Smallest text form of 4-byte blocks, in a file formatAscii85 or Z85not in HTML/JSON1.25x
User text in a URL queryurl.Values, http_build_queryUTF-8 first+ and & handled
User text in a URL path segmentPathEscape, rawurlencodeper segment%20, %2F
Domain names with Persian lettersIDNA to xn--UTS #46 profile; show Unicode in UIDNS carries ASCII
Small icon in HTML or CSSdata: URICSP img-src data:one fewer request
Large or reused imagefile or object storage URLCDN and cache headerscaching beats inlining
Secret storagereal encryption (KMS, AES-GCM)not encodingencoding is reversible by everyone
Binary between services you ownbytes (Protobuf, gRPC, multipart)base64 only at JSON edgessaves 33% CPU and bandwidth

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

Monolith (یک پروسه، یک پایگاه داده) ​

یک برنامهٔ Laravel HTML می‌سازد، cookie می‌خواند و لینک می‌سازد و کدگذاری‌ها بیشتر نامرئی‌اند: echo دوآکولادی Blade برای HTML escape می‌کند، route() پارامترها را percent-encode می‌کند و مقدارهای رمزشدهٔ خود فریم‌ورک Base64 هستند (کد Encrypter روی یک payload JSON شامل iv، value، mac و tag تابع base64_encode را صدا می‌زند). باگ‌ها در لبه‌ها پیدا می‌شوند: آواتاری که به‌صورت data: URI فرستاده شده، لینک بازیابی رمز با token Base64 که + دارد، CSV فارسی با charset اشتباه. مثال روزمره: ایمیل بازیابی رمز. ۳۲ بایت تصادفی بسازید، rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=') را در URL بگذارید، hash('sha256', $bytes) را به‌شکل hex در پایگاه داده نگه دارید و با hash_equals مقایسه کنید. حساب نشان می‌دهد چرا Base64 ساده تله است: ۳۲ بایت یعنی ۴۳ نویسهٔ Base64 و هر نویسه با احتمال ۱/۶۴ برابر + است؛ پس احتمال دست‌کم یک + برابر 1 - (63/64)^43 یعنی حدود ۴۹٪ است: اگر + به فاصله تبدیل شود تقریباً از هر دو لینک یکی می‌شکند. مثال تولیدی (قابل‌بررسی): signed URL لاراول پارامتر signature= را با hex حروف کوچک از hash_hmac('sha256', <url>, <key>) اضافه می‌کند (UrlGenerator::signedRoute)؛ عمداً hex تا هیچ نویسهٔ مهم برای URL ظاهر نشود.

Modular monolith / چند پایگاه داده ​

ماژول‌ها در مرزها روی قالب توافق می‌کنند: ماژول Identity JWT (base64url) صادر می‌کند، Billing فاکتور PDF را به‌صورت bytea یا در object storage نگه می‌دارد، Notifications پیام MIME می‌سازد (پیوست Base64، بدنهٔ quoted-printable). هر encoder را یک‌جا نگه دارید (یک کلاس Encodings یا یک package Go) و مقدارهای تایپ‌دار (SignedToken، ContentHash) بدهید تا کسی «یک رشتهٔ base64» دست‌به‌دست نکند. مثال روزمره: invoice_pdf_sha256 به‌صورت ۳۲ بایت خام در ستون bytea، در پنل ادمین hex و در URL دانلود base64url: سه نما از یک مقدار با یک منبع حقیقت. مثال تولیدی (قابل‌بررسی): خود PostgreSQL ذخیره را از شکل متنی جدا می‌کند: مستندات نشان می‌دهد decode('MTIzAAE=', 'base64') مقدار bytea را به شکل hex یعنی \x3132330001 برمی‌گرداند و encode(bytea, 'hex' | 'base64' | 'escape') تبدیل‌های صریح‌اند (PostgreSQL binary string functions): بایت را ذخیره کنید و در لبه تبدیل کنید.

Microservices ​

بین سرویس‌ها کدگذاری‌های متنی تکثیر می‌شوند: JSON باینری را به Base64 می‌برد، headerها JWT می‌برند، صف‌ها envelope. قواعدی که عاقلانه نگهش می‌دارد: (۱) الفبا و padding را در قرارداد API بنویسید (OpenAPI 3.1 از contentEncoding: base64 در JSON Schema استفاده می‌کند؛ 3.0 از format: byte؛ برای base64url نام استانداردی نیست، در توضیحات بنویسید)؛ (۲) برای payload بیش از حدود ۱۰۰ کیلوبایت پروتکل باینری ترجیح بدهید: bytes در Protobuf، stream در gRPC، multipart (نگاه کنید به Serialization Formats)؛ (۳) داده‌های همبستگی را در header به‌صورت متن ساده و امضا را base64url بگذارید؛ (۴) URL را یک بار encode‌شده رد کنید و در هر hop یک بار decode کنید، نه در gateway و دوباره در سرویس.

text
browser ── POST /v1/avatars  {"image":"<base64>"}  ──▶ gateway (route-specific body cap)
gateway ── Authorization: Bearer <b64url.b64url.b64url> ──▶ avatar-svc
avatar-svc ── decode strictly, cap decoded size, sniff magic bytes ──▶ object storage (raw bytes)
avatar-svc ── event {"key":"avatars/9f2c.../1.png","sha256":"9f2c..."} ──▶ queue   (hex hash, no payload)

مثال روزمره: API فیلد image_base64 ۲۰۰ کیلوبایتی برمی‌گرداند و اپ موبایل decode می‌کند. جایگزین کردنش با pre-signed URL کدگذاری، ۳۳٪ و جهش حافظه را حذف می‌کند. مثال تولیدی (قابل‌بررسی): نگاشت JSON در Protocol Buffers فیلد bytes را رشتهٔ Base64 تعریف می‌کند («JSON value will be the data encoded as a string using standard base64») و parserها هر دو الفبا را می‌پذیرند؛ پس سرویس gRPC پشت یک gateway JSON هر فیلد باینری را با ۳۳٪ سربار می‌برد.

Distributed data (replicaها، cacheها و CDNها) ​

کدگذاری بخشی از هویت می‌شود: کلید cache، URL در CDN و کلید shard رشته‌اند؛ پس دو املای یک مقدار دو کلید است. RFC 3986 می‌گوید URIهایی که فقط در حروف بزرگ و کوچک ارقام hex در percent-encoding فرق دارند معادل‌اند، اما cacheی که روی رشتهٔ خام کلید می‌زند %d8%b3 و %D8%B3 را جدا نگه می‌دارد مگر CDN یا کد شما نرمال کند؛ + در برابر %20 و Base64 با و بدون padding نسخه‌های تکراری بیشتری می‌سازند. مثال روزمره: کلید Redis ساخته‌شده از یک filter به‌شکل JSON: JSON را نرمال کنید، hash بگیرید، hex حروف کوچک یا base64url بدون padding بسازید تا همان filter همیشه به همان کلید برسد. مثال تولیدی (قابل‌بررسی): فایل pointer در Git LFS (بخش «The Pointer» در مشخصه) متنی از version، oid sha256:<۶۴ رقم hex> و size است، «یکتا: دقیقاً یک کدگذاری معتبر برای pointer وجود دارد» و کمتر از ۱۰۲۴ بایت: هویتی content-addressed که عمداً canonical است تا هر replica همان بایت‌ها را حساب کند. replicaها بایت را تکثیر می‌کنند نه املا را: ستون bytea نصف متن Base64 خود جا می‌گیرد و پرسش «کدام املا ذخیره شد» را حذف می‌کند.

Scaling path (مسیر مقیاس) ​

LoadWhat changes
1x (hundreds of requests per second)Standard libraries; encode in the handler; base64 in JSON is fine
10xStop base64-ing files in JSON: use upload URLs and streaming; use AppendEncode-style APIs and pooled buffers; cap sizes at the edge
100xBinary protocols between services; CDN for images; normalise URLs at the edge (lower-case percent hex, one +/%20 policy) so caches hit; SIMD-accelerated Base64 where it shows in profiles
Multi-regionKeep encodings in the contract, version them, and test with a golden vector file (known inputs and outputs) in every language you ship

عیب‌یابی (Troubleshooting) ​

SymptomLikely causeCheckFix
Token verifies locally, fails after a redirect or e-mail link+ became a space, or = was droppedcompare the received query string byte by bytepercent-encode, or switch to base64url
illegal base64 data at input byte N (Go)wrong variant (padded vs raw, std vs url)look for -, _, missing =choose the matching Encoding; normalise
Decoded text has a trailing newline (...\n)echo added a newline before base64echo -n or printfuse printf '%s'; check Kubernetes Secret values with base64 -d | xxd
Login to a service fails with a "correct" Kubernetes Secretnewline inside the encoded valuekubectl get secret x -o jsonpath='{.data.k}' | base64 -d | xxd | tailrecreate with --from-literal or echo -n
InvalidCharacterError from btoastring contains characters above 0xFFcontains Persian or emojiTextEncoder to UTF-8 bytes, then Base64
Persian text shows سلامUTF-8 bytes decoded as Latin-1 after Base64check charsetdecode bytes as UTF-8
%2520 in a URLdouble encodingdecode once and look againencode once
400 or 404 only when path has %2Fproxy or server rejects encoded slashesnginx/Apache logschange the identifier (base64url) or the server setting
Image does not show in e-mailclient blocks data: imagestest in Gmail/Outlookuse a cid: attachment or a hosted image
CSP violation for an inline imageimg-src lacks data:browser consoleadd data: to img-src only
Laravel signed URL gives 403URL re-encoded, parameter order changed, proxy rewrote the hostcompare the incoming URL with the generated onepass the original query untouched; set trusted proxies
Two services compute different hashes for the "same" stringhex case, padding or line wrap differsnormalise to lower-case hexone canonical form, constant-time compare
Memory spike when encoding an uploadwhole file built as a stringprofileNewEncoder/stream filters
Pasting a key breaks in a chat app= or + reformattedview as plain textuse base64url or hex for pasted secrets

آزمایشگاه (Lab) ​

روی Mac یا Linux کپی‌-پیست کنید؛ برنامه‌ها Go 1.24 به بالا می‌خواهند. همه چیز را از docs/snippets/foundations/binary-to-text-encoding/go اجرا کنید.

آزمایش ۱ — مقایسهٔ حجم برای یک رشتهٔ فارسی و یک فایل (تصویر).

bash
go run ./encodings
# expected: the table in Problem 1: hex 34, base64 24, base64url raw 23, percent 49-51 for 17 bytes
head -c 3000 /dev/urandom > /tmp/blob.bin
go run ./sizes -file /tmp/blob.bin
# expected: raw 3000, hex 6000 (2.000x), base64 4000 (1.333x), base64 raw 4000, base64url raw 4000, percent about 8000+, data URI 4037
go run ./sizes -text "سلام دنیا"
# expected: raw 17, hex 34, base64 24, base64url raw 23, percent (query) 49

آزمایش ۲ — بازتولید باگ + به فاصله و رفعش.

bash
go run ./urlbug
# expected: "server sees: \"    //4=\" (same as sent? false)" then the fixed URL with %2B and "same as sent? true"
curl -sG -o /dev/null -w '%{url_effective}\n' --data-urlencode 'q=a+b c/d' --data-urlencode 'name=سلام' http://127.0.0.1:1/x
# expected: http://127.0.0.1:1/x?q=a%2bb+c%2fd&name=%d8%b3%d9%84%d8%a7%d9%85   (curl uses lower-case hex)
python3 -c "import urllib.parse as u; print(u.quote('a b+c/d'), u.quote_plus('a b+c/d'), u.unquote_plus('a+b%2Bc'))"
# expected: a%20b%2Bc/d a+b%2Bc%2Fd a b+c

آزمایش ۳ — بازرسی یک JWT.

bash
T=$(go run ./tokens | sed -n 1p | cut -d' ' -f2)
echo $T | cut -d. -f1 | base64 -d; echo
# expected: {"alg":"HS256","typ":"JWT"}        (works because this segment length needs no padding on this machine)
p=$(echo $T | cut -d. -f2); while [ $(( ${#p} % 4 )) -ne 0 ]; do p="$p="; done
echo $p | tr '_-' '/+' | base64 -d; echo
# expected: {"iat":1764000000,"name":"مرتضی","sub":"42"}

حلقهٔ pad کردن راه‌حل خطای base64: invalid input برای بخش‌های بدون padding است و tr برای برگرداندن base64url به استاندارد.

آزمایش ۴ — بازرسی یک Kubernetes Secret (بدون cluster).

bash
kubectl create secret generic db --from-literal=username=admin --from-literal=password='p@ss/w+rd' --dry-run=client -o yaml
# expected:
# apiVersion: v1
# data:
#   password: cEBzcy93K3Jk
#   username: YWRtaW4=
# kind: Secret
kubectl create secret generic db --from-literal=password='p@ss/w+rd' --dry-run=client -o jsonpath='{.data.password}' | base64 -d; echo
# expected: p@ss/w+rd
echo hello | base64; printf hello | base64
# expected: aGVsbG8K  then  aGVsbG8=      (the first has a hidden newline: the classic Secret bug)

آزمایش ۵ — hex، چیدمان بیت Base64 و Base85 در Git.

bash
printf 'Man' | xxd -p; printf 'Man' | base64; printf 'Ma' | base64; printf 'M' | base64
# expected: 4d616e   TWFu   TWE=   TQ==
cd /tmp && rm -rf b2t && mkdir b2t && cd b2t && git init -q . && printf '\x00\x01\x02binary\xff' > f.bin && git add f.bin && git -c user.email=a@b -c user.name=a commit -qm one && printf '\x00\x01\x02BINARY\xff\xfe' > f.bin && git diff --binary | sed -n 3,6p
# expected: GIT binary patch / literal 11 / <one Base85 line> (git's own alphabet)

آزمایش ۶ — streaming و decoder امن.

bash
go build -o /tmp/stream ./stream && /usr/bin/time -l /tmp/stream 2>&1 | egrep "source|sha256|maximum resident"
# expected: source 104857600 bytes, base64+MIME 143489350 bytes (1.368x); sha256 before == after; maximum resident set size about 9.7 MB (9748480 here)
go run ./safedecode
# expected: valid 200, newline injected 400, sloppy trailing bits 400, oversize 413

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

BeliefReality
"Base64 encrypts or hides data"It is reversible spelling; RFC 4648: it "does not provide any computational confidentiality"
"Base64 shrinks data"It grows it by a third (hex doubles it); compress first, then encode
"There is one Base64"Standard vs url-safe, padded vs raw, wrapped vs not: five spellings; Go has four Encoding constants for them
"= is part of the data"It is length filler; JWT and many tokens remove it
"+ means space in URLs"Only in form encoding; in a path it is a plus, and RFC 3986 gives it no special meaning in a query
"encodeURI is safe for query values"It leaves & = + # alone; use encodeURIComponent or URLSearchParams for values
"urlencode and rawurlencode are the same"PHP: + versus %20 for space; urlencode also encodes ~
"Encode the whole URL once and it is fine"Encode each component separately, once
"A URL can contain Persian letters"A URI cannot; an IRI can and is mapped to percent-encoded UTF-8; hosts use Punycode
"btoa handles any string"Only characters up to 0xFF; Unicode needs UTF-8 bytes first
"Bigger inline images are faster"data: URIs grow 33%, cannot be cached separately and are blocked by strict CSP
"A JWT is encrypted"A JWS is signed; header and payload are base64url, readable by anyone holding the token
"Kubernetes Secrets are secure because they are base64"Base64 is encoding; Secrets are plaintext in etcd unless encryption at rest is on
"If the decoder accepts it, it is valid"Lenient decoders drop junk, accept the other alphabet and ignore non-zero pad bits
"Hex case does not matter for security"RFC 4648 warns case alteration can be used to make string comparisons fail; normalise first

چکیده (Cheat sheet) ​

TopicWhat to remember
Base64 size3 bytes to 4 chars, 4*ceil(n/3), +33%; MIME wrap adds CRLF every 76 (about 1.37x)
Base64 alphabetsA-Za-z0-9+/ and =; url-safe A-Za-z0-9-_
Where padding is droppedJWT (JWS), many URL tokens: RFC 4648 allows when the length is implicit
JWTthree base64url segments joined by .; eyJ starts a JSON object; signed, not encrypted
Hex2 chars per byte, 2x, case-insensitive; compare in constant time
Base32A-Z2-7, 1.6x, case-insensitive; TOTP secrets; Crockford drops ILOU
Base58Bitcoin alphabet without 0OIl+/; big-integer maths; short values only
Base855 chars per 4 bytes, 1.25x; Ascii85 in PDF; Git has its own alphabet
Unreserved charactersA-Z a-z 0-9 - . _ ~; encode everything else per component
+ vs %20+ is a space only in form encoding; always encode query values
Double encodingencode once, decode once; %25 is the sign of a second pass
IRI and IDNAbrowsers map Persian URLs to UTF-8 %XX paths and xn-- hosts
Data URIdata:<type>;base64,<data>; only small assets; CSP img-src data:
Decoding untrusted inputcap length first, decode strictly, verify content type, cap decoded size
Not encryptionBase64, hex, percent, Basic, Kubernetes data: are all readable without a key
Gobase64.StdEncoding, RawURLEncoding, url.Values, hex, NewEncoder for streams
PHP and Laravelbase64_decode($s, true), rawurlencode, http_build_query, Str::toBase64, signed URLs

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

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

۱ — چرا خروجی Base64 حدود ۳۳٪ بزرگ‌تر می‌شود و طول دقیق برای ۱۰ بایت ورودی چند است؟ حیاتی ​

پاسخ

پاسخ: هر ۳ بایت (۲۴ بیت) به ۴ نویسهٔ ۶ بیتی تبدیل می‌شود. برای ۱۰ بایت: 4 * ceil(10 / 3) = ۱۶ نویسه با padding (ceil(40/3) = ۱۴ بدون padding).

۲ — token امضاشده در JSON کار می‌کند اما در لینک ایمیل نه. دو بایت مظنون اول کدام‌اند؟ مهم ​

پاسخ

پاسخ: + (که decode فرم آن را فاصله می‌کند) و = (padding که حذف یا percent-encode شده). base64url بدون padding بگیرید یا مقدار را percent-encode کنید.

۳ — فرق urlencode و rawurlencode در PHP و فرق QueryEscape و PathEscape در Go چیست؟ مهم ​

پاسخ

پاسخ: urlencode و QueryEscape قاعدهٔ فرم دارند (فاصله می‌شود +)؛ rawurlencode و PathEscape %20 می‌دهند. urlencode در PHP حرف ~ را هم encode می‌کند.

۴ — چرا btoa('سلام') خطا می‌دهد و چطور درست می‌شود؟ حیاتی ​

پاسخ

پاسخ: btoa کد هر نویسه را یک بایت می‌گیرد و کدپوینت‌های بالاتر از 0xFF را رد می‌کند. رشته را با TextEncoder به بایت‌های UTF-8 ببرید و بایت‌ها را Base64 کنید.

۵ — آیا payload یک JWT محرمانه است؟ چرا؟ حیاتی ​

پاسخ

پاسخ: نه. JWT معمولی (JWS) امضا شده و base64url است؛ هر کس آن را دارد payload را می‌خواند. فقط امضا یکپارچگی را حفظ می‌کند. برای محرمانگی JWE لازم است.

۶ — مقدار Secret به شکل cEBzcy93K3Jk چه نسبتی با راز واقعی دارد و چه کسی می‌خواندش؟ حیاتی ​

پاسخ

پاسخ: Base64 استاندارد بایت‌های خام (p@ss/w+rd) است. هر کس شیء Secret را بخواند، یا etcd وقتی encryption at rest خاموش است، با base64 -d آن را decode می‌کند.

۷ — double encoding چیست و چطور به باگ امنیتی تبدیل می‌شود؟ مهم ​

پاسخ

پاسخ: encode یا decode دوباره (%2520). فیلتر یک بار decode می‌کند و متن بی‌خطر می‌بیند؛ برنامه دوباره decode می‌کند و ../ یا script می‌گیرد. دقیقاً یک بار در مرز decode کنید.

۸ — چرا aGl= را بعضی decoderها می‌پذیرند و Strict() در Go رد می‌کند؟ تکمیلی ​

پاسخ

پاسخ: آخرین نویسه‌اش pad bit غیرصفر دارد؛ شکل canonical aGk= است. decoderهای آسان‌گیر بیت‌ها را نادیده می‌گیرند و سخت‌گیر رد می‌کند. ابهام مقایسهٔ رشته‌های کدگذاری‌شده را می‌شکند.

۹ — data URI کِی ایدهٔ خوبی است و کِی بد؟ تکمیلی ​

پاسخ

پاسخ: برای دارایی‌های بسیار کوچک و یک‌بارمصرف خوب است (آیکون، placeholder، تصویر inline ایمیل در جاهایی که پشتیبانی می‌شود). برای تصویر بزرگ یا تکراری بد است: ۳۳٪ بیشتر، cache جدا ندارد، CSP باید data: را مجاز کند و بعضی کلاینت‌های ایمیل مسدودش می‌کنند.

۱۰ — host با نام مثال.ایران روی سیم چه کدگذاری می‌شود و path با /مقاله چه؟ مهم ​

پاسخ

پاسخ: host با IDNA/Punycode (xn--mgbh0fb.xn--mgba3a4f16a)؛ path با بایت‌های UTF-8 که percent-encode می‌شوند (%D9%85%D9%82%D8%A7%D9%84%D9%87).

۱۱ — چطور یک آواتار base64 را از کلاینت نامطمئن امن می‌پذیرید؟ حیاتی ​

پاسخ

پاسخ: طول کدگذاری‌شده را پیش از decode محدود کنید، سخت‌گیرانه decode کنید، فاصلهٔ ناخواسته را رد کنید، اندازهٔ decode‌شده را محدود کنید و سپس magic bytes را بررسی و تصویر را دوباره پردازش کنید. به نوع اعلام‌شده اعتماد نکنید.

۱۲ — چرا echo hello | base64 با printf hello | base64 فرق دارد؟ حیاتی ​

پاسخ

پاسخ: echo یک بایت newline اضافه می‌کند؛ پس ورودی hello\n است (aGVsbG8K). علت معمول newline پنهان در Secretهای Kubernetes است.

واژه‌نامه (Glossary) ​

TermOne line
Binary-to-text encodingA reversible mapping of arbitrary bytes onto a restricted printable alphabet
AlphabetThe set of characters an encoding may output
QuantumRFC 4648 term for the input group that maps to one output unit (3 bytes for Base64)
Base16 / hex4 bits per character, 0-9A-F
Base325 bits per character, A-Z2-7, case-insensitive
base32hexBase32 with 0-9A-V so order is preserved
Crockford Base32Base32 without I L O U, tolerant decoding, optional check symbol
z-base-32Human-oriented Base32 with a reordered lower-case alphabet
Base58Big-integer base with no 0 O I l + /; Bitcoin alphabet
Base58CheckBase58 plus a 4-byte double-SHA-256 checksum
Base646 bits per character, A-Za-z0-9+/
Base64urlBase64 with - and _; RFC 4648 section 5
Padding (=)Filler making the output a multiple of 4 (Base64) or 8 (Base32) characters
Raw / unpaddedBase64 without =, as used by JWT
MIME line wrappingLines of at most 76 characters separated by CRLF
Pad bitsUnused low bits in the last character; must be zero in canonical form
Strict decodingRejecting input with non-alphabet characters, wrong padding or non-zero pad bits
Forgiving-base64The WHATWG decode used by atob: strips whitespace, tolerates missing padding
Ascii85 / Base855 characters per 4 bytes; Adobe, Git, RFC 1924 and Z85 variants
uuencodeUnix-to-Unix encoding, 1980s ancestor of Base64
Quoted-printableMIME encoding that keeps printable ASCII and writes other bytes as =XX
Encoded-wordRFC 2047 syntax =?charset?B or Q?text?= for non-ASCII mail headers
Percent-encoding%XX for a byte; RFC 3986 pct-encoded
Unreserved charactersA-Z a-z 0-9 - . _ ~: never need encoding
Reserved charactersgen-delims and sub-delims: delimiters with meaning inside a URL
application/x-www-form-urlencodedForm encoding where space is + and + is decoded as space
Double encodingEncoding an already-encoded value, producing %25 sequences
URI / URLAn ASCII identifier; URL is a URI that locates
IRIURI that may contain Unicode characters (RFC 3987), mapped to a URI
IDNAInternationalized Domain Names in Applications
PunycodeRFC 3492 ASCII form of Unicode labels, prefixed xn--
Data URIdata: URL with inline data (RFC 2397)
CSPContent-Security-Policy; img-src must allow data: for inline images
JWS / JWTSigned token: three base64url segments joined by .
HTTP BasicAuthorization: Basic + Base64 of user:password
HTML entity&amp;, &#x633;: HTML's escape syntax
JSON escape\", \\, \n, \uXXXX in a JSON string
ObfuscationMaking data look unreadable without a key; not security
SIMD base64Vectorised encoders/decoders (AVX2, AVX-512, NEON) that approach memcpy speed
Git LFS pointerSmall text file with version, oid sha256: and size that stands in for a large file
TOTP secretBase32-encoded key in otpauth:// URIs

منابع (References) ​

همهٔ منابع در ۲۰۲۶-۱۱-۲۵ دریافت و خوانده شده‌اند؛ نسخهٔ محلی هر کدام ذخیره شده است. همهٔ لینک‌ها کد ۲۰۰ برگرداندند.

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