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 for | Go to |
|---|---|
| One table to memorise: encoding, alphabet, size cost, where it is used | Everything in one minute |
| Why bytes cannot just be pasted into JSON, URLs or headers | Why it exists |
| uuencode, MIME, RFC 4648, RFC 3986, Punycode, JWS | Where it comes from |
| Hex and Base16 | Hex |
6-bit groups, alphabet, = padding, 33% overhead, 76-column lines | Base64, Padding |
- and _, padding in URLs, JWT segments | Base64url |
| Why two libraries disagree on the same string | Decoding leniency |
| TOTP secrets, Crockford, z-base-32, base32hex | Base32 |
Bitcoin addresses, no 0OIl | Base58 |
| Ascii85, git binary patches, PDF | Base85 |
Reserved vs unreserved, UTF-8 bytes, %XX | Percent-encoding |
+ vs %20, double encoding, path vs query vs fragment | Plus vs space, Double encoding, Components |
| Persian characters in URLs and domains, IDNA | IRI and Punycode |
| HTML entities, JSON string escapes | HTML and JSON |
data: URLs, size, CSP | Data URIs |
| MIME bodies and headers | Quoted-printable, uuencode |
| "It is encoded, so it is safe" | Not encryption |
JWT, Kubernetes Secrets, Basic auth, src, Git LFS, Protobuf | Where each one shows up |
| Go, PHP, JavaScript, Laravel, CLI tools side by side | Per-language behaviour |
| Bit math, lengths, speed, error messages | Mechanics |
| Code for every classic bug | Solving the classic problems |
| Which encoding for which job | Choosing |
| Monolith to distributed systems | In architecture |
| Symptom to cause | Troubleshooting |
| Hands-on | Lab |
| Wrong beliefs, cheat sheet, definitions | Misconceptions, Cheat sheet, Self-check, Glossary |
همهچیز در یک دقیقه
کدگذاریها. هر ردیف در فهرست مفاهیم باز میشود. نسبتها یعنی حجم خروجی تقسیم بر حجم ورودی؛ جاهایی که اندازهگیری شده روی همین ماشین و روی رشتهٔ ۱۷ بایتی فارسی بوده است.
| Encoding | Alphabet | Output size | Typical home |
|---|---|---|---|
| Hex / Base16 | 0-9A-F (or lower case) | 2.00x | Hashes, colours, byte dumps, UUIDs, Laravel signature |
| Base64 | A-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.33x | Compact tokens |
| Base64url | A-Z a-z 0-9 - _ | about 1.33x | JWT, URL parameters, cookies, filenames |
| Base32 | A-Z 2-7, pad = | 8 chars per 5 bytes, 1.6x | TOTP secrets, case-insensitive systems |
| Crockford / z-base-32 | no ILOU, or a shuffled alphabet | 1.6x | Human-typed IDs, ULID |
| Base58 | no 0 O I l + / | about 1.37x | Bitcoin addresses, short IDs |
| Base85 / Ascii85 | 85 printable characters | 5 chars per 4 bytes, 1.25x | PDF, PostScript, git binary patches |
| Percent-encoding | %XX per byte | 1x to 3x (3x for each non-unreserved byte) | URLs, forms |
| Quoted-printable | mostly literal, =XX otherwise | 1x to 3x | MIME text bodies and headers |
| HTML entities / JSON escapes | &, \n, \uXXXX | depends on content | HTML text, JSON strings |
| Punycode | xn-- + ASCII | about 1x | Internationalized domain names |
سه چیزی که باید به خاطر بسپارید.
| Situation | Do this |
|---|---|
| Putting bytes in a URL, cookie, filename or JWT | base64url 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-mail | standard 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 brackets | Hex: 2x, but only 0-9a-f, the safest alphabet there is |
Base64: 1.33x, but +, /, = are special in URLs | Base32: 1.6x, but case-insensitive and typeable |
| Shorter output | Survives more channels, fewer escaping rules |
| Needs a second layer when a delimiter is in the alphabet | Works almost everywhere unchanged |
تمثیلی که در این صفحه تکرار میکنیم: پیکی که فقط نامهٔ چاپی میپذیرد. میخواهید یک آجر بفرستید. پیک آجر نمیبرد، فقط کاغذ. پس نامهای مینویسید که آجر را تکهتکه با یک الفبای ثابت توصیف میکند و گیرنده از روی نامه آجر را بازسازی میکند. هیچ چیز در نامه آجر را پنهان نمیکند: هر کس نامه را بخواند میتواند آجر را بسازد. هر پیک نامهٔ متفاوتی میخواهد (پیک URL نامهای با / را رد میکند؛ پیک ایمیل خطهای زیر ۷۶ نویسه میخواهد)، پس باید بدانید از کدام پیک استفاده میکنید.
سه بدفهمی رایج، از همان ابتدا
- «Base64 داده را امن یا محرمانه میکند.» فقط آن را قابلانتقال میکند. هر کس با یک دستور آن را برمیگرداند. هرگز برای رمز عبور، token محرمانه یا «مبهمسازی» کلید API استفاده نکنید.
- «Base64 یک چیز است.» دستکم پنج املا هست: استاندارد با padding، استاندارد بدون padding، base64url با و بدون padding، و نسخهٔ MIME با خطشکن. مقدار یکی در decoder دیگری خطا میدهد یا بیصدا خراب میشود.
- «URL encoding یک چیز است.»
%20در path و RFC 3986 درست است؛+برای فاصله فقط درapplication/x-www-form-urlencoded(فرمهای HTML و query که مثل فرم خوانده میشود) درست است. قاطی کردنشان رایجترین باگ کدگذاری در وب است.
از کجا آمده
| Year | Event | Source |
|---|---|---|
| 1980 | uuencode/uudecode written by Mary Ann Horton at UC Berkeley so binary files could pass through e-mail and Usenet | Wikipedia (secondary source; not verified against a primary text) |
| 1996 | MIME (RFC 2045, November 1996) defines the Content-Transfer-Encoding header with the Base64 and quoted-printable encodings, and the 76-character line limit | RFC 2045 |
| 1998 | data: URL scheme (RFC 2397, August 1998), "only useful for short values" | RFC 2397 |
| 2003 | Punycode (RFC 3492, March 2003) for Internationalized Domain Names in Applications | RFC 3492 |
| 2003 to 2006 | RFC 3548 (July 2003) then RFC 4648 (October 2006) standardise Base16, Base32, Base64 and add the URL and filename safe alphabet | RFC 3548, RFC 4648 |
| 2005 | RFC 3986 (January 2005) defines URI syntax, reserved and unreserved characters and percent-encoding; RFC 3987 (January 2005) adds IRIs | RFC 3986, RFC 3987 |
| 2015 | JSON Web Signature (RFC 7515, May 2015) fixes JWT segments as base64url without padding; RFC 7617 (September 2015) defines Basic auth as Base64 of user:password | RFC 7515, RFC 7617 |
| 2025 to 2026 | JavaScript gains native Uint8Array.prototype.toBase64 and toHex; Node 26 on this machine reports both as functions | observed with node -e (Node v26.10.0) |
دو واژه برای ادامه لازم است. RFC 4648 بازگروهبندی ۶ بیتی را quantum مینامد و RFC 3986 شکل %XX را pct-encoded: pct-encoded = "%" HEXDIG HEXDIG. استاندارد WHATWG URL آن چیزی است که مرورگرها واقعاً پیاده میکنند؛ جایی که با RFC 3986 فرق دارد (مثلاً + برای فاصله در فرم) صریح گفته میشود.
نمودار بالا چیدمان بیتی را نشان میدهد: سه بایت 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 یک بایت است؛ خروجی دقیقاً دو برابر ورودی است.
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.
| Product | Hex helpers | Case |
|---|---|---|
| Go | encoding/hex (EncodeToString, DecodeString, Dump), fmt %x | Encodes lower case; decodes both |
| PHP | bin2hex, hex2bin, dechex | bin2hex lower case; hex2bin accepts both |
| JavaScript | Uint8Array.prototype.toHex (a function in Node 26 here), Buffer.toString('hex') | lower case |
| PostgreSQL | encode(bytea, 'hex'), \x input format | lower case |
| CLI | xxd, xxd -p, hexdump -C, openssl dgst | lower 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.
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 میرود.
| Product | Standard encoder | Output has line breaks? |
|---|---|---|
Go encoding/base64 | StdEncoding | No (the decoder skips CR and LF) |
| PHP | base64_encode | No |
| JavaScript browser | btoa (binary string only), Uint8Array.toBase64() | No |
| Node.js | Buffer.from(x).toString('base64') | No |
| Python | base64.b64encode | No (encodebytes adds \n every 76) |
GNU coreutils base64 | wraps at 76 by default; -w 0 disables | Yes |
macOS base64 | no wrapping by default (measured here) | No |
openssl base64 | wraps at 64; -A for one line | Yes |
| Java | Base64.getEncoder() plain, getMimeEncoder() 76 with CRLF | Only 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 به پیمانهٔ ۴ همیشه ۰ یا ۲ یا ۳ است؛ باقیمانده ۱ هرگز معتبر نیست.
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 که برنامهٔ چت = آخرش را برداشته.
| Decoder | Padded input | Unpadded input |
|---|---|---|
Go StdEncoding | accepted | rejected (illegal base64 data) |
Go RawStdEncoding | rejected | accepted |
PHP base64_decode (also strict) | accepted | accepted (the php-src source says it accepts zero padding) |
WHATWG atob | accepted | accepted unless length mod 4 is 1 |
Python b64decode | accepted | binascii.Error: Incorrect padding |
Node Buffer.from(s, 'base64') | accepted | accepted |
Java Base64.getDecoder() | accepted | not 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 با حذف همهٔ = پایانی و بدون خطشکن و فاصله.
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 ساخته میشوند.
| Product | base64url API |
|---|---|
| Go | base64.URLEncoding, base64.RawURLEncoding (no padding) |
| PHP | no built-in: rtrim(strtr(base64_encode($s), '+/', '-_'), '=') |
| JavaScript / Node | Buffer.toString('base64url'); Uint8Array.toBase64({alphabet: 'base64url'}) |
| Python | base64.urlsafe_b64encode (pads) |
| Java | Base64.getUrlEncoder().withoutPadding() |
| PostgreSQL | encode(x, 'base64url') appears in the PostgreSQL 19 documentation I read |
راهحل: برای هر چیزی که به URL، cookie یا نام فایل میرسد base64url بگیرید؛ Base64 استاندارد را برای بدنه نگه دارید. کد: urlbug.
سختگیری decoder (Leniency): یک رشته، چند جواب مهم
به زبان ساده: decoderها در چیزهایی که میبخشند فرق دارند: فاصله، خطشکن، = گمشده، نویسهٔ اضافی، الفبای اشتباه و بیتهای تهماندهٔ غیرصفر.
بدفهمی رایج: «اگر decode شد، معتبر است.» بعضی decoderها نویسههای ناشناس را بیصدا دور میریزند، پس ورودی خراب یا مخرب ممکن است به چیز کوتاهتر یا متفاوتی decode شود و بررسی امضا یا مقایسهٔ رشته را بشکند.
تعریف: RFC 4648 بخش ۳.۳ میگوید پیادهسازیها باید ورودی دارای نویسهٔ خارج از الفبا را رد کنند، مگر مشخصهٔ ارجاعدهنده صریحاً چیز دیگری بگوید؛ MIME چیز دیگری میگوید («در پذیرش آزاد باش»). forgiving-base64 decode استاندارد WHATWG که atob استفاده میکند سیاست سوم است: فاصلههای ASCII را بردار، یک یا دو = پایانی را اگر طول مضرب ۴ است بردار، اگر طول به پیمانهٔ ۴ برابر ۱ است شکست بده، و با هر نویسهٔ خارج از الفبا شکست بده.
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 فرق میکند.
| Behaviour | Go | PHP | WHATWG atob / browsers | Python | Node Buffer | Java |
|---|---|---|---|---|---|---|
| Skips CR and LF | Yes | Yes (php-src: strict mode skips whitespace, non-strict skips every unknown character) | Yes (all ASCII whitespace) | Default yes; validate=True no | Yes | Basic decoder rejects; MIME decoder ignores |
| Skips other junk | No (error) | Non-strict: silently discards; strict: false | No (error) | Default: discards; validate=True: error | Yes (measured: aG$k= decodes to hi) | Basic: error (Javadoc: rejects characters outside the alphabet) |
| Accepts missing padding | Only Raw* | Yes | Yes (unless length mod 4 is 1) | No | Yes | Yes |
| Accepts the other alphabet | No | No | No | b64decode no, urlsafe_b64decode accepts both | Yes (both) | No |
| Rejects non-zero trailing bits | Only .Strict() | No | No | No | No | No |
راهحل: یک گونه را که مشخص کردهاید decode کنید، فاصلهٔ ناخواسته را رد کنید، و امضا را روی رشتهٔ دریافتی بررسی کنید نه روی مقدار دوباره-کدگذاریشده. کد: safedecode.
Base32 مهم
به زبان ساده: مثل Base64 ولی فقط ۳۲ نویسه (A-Z و 2-7)؛ پس هر نویسه ۵ بیت میبرد و ۸ نویسه ۵ بایت. بلندتر است اما حرف کوچک، + و / ندارد و ارقام شبیه حروف نیستند.
بدفهمی رایج: «Base32 فقط Base64ِ بدتر است.» ارزشش در این است که از تبدیل حروف به هم (نام DNS، فایلسیستمهای macOS و Windows) جان سالم به در میبرد و میشود آن را بلند خواند. RFC 4648 دلیلش را میگوید: شکلی که باید به حروف حساس نباشد ولی لازم نیست برای انسان خوانا باشد.
تعریف: الفبای بخش ۶ RFC 4648 یعنی ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 و pad = تا مضرب ۸. بخش ۷ گونهٔ base32hex با 0-9A-V را تعریف میکند که ترتیب بایتها را نگه میدارد. گونههای مخصوص انسان:
| Variant | Alphabet | Rules | Origin |
|---|---|---|---|
| RFC 4648 Base32 | A-Z 2-7 | upper-case, = pad | IETF; TOTP key URIs |
| base32hex | 0-9 A-V | sort-order preserving | RFC 4648 section 7 |
| Crockford | 0-9 A-Z without I L O U | decode accepts lower case, I/L as 1, O as 0, hyphens ignored, optional check symbol modulo 37 | Douglas Crockford |
| z-base-32 | ybndrfg8ejkmcpqxot1uwisza345h769 | lower case, shuffled so common characters are easy | Zooko Wilcox-O'Hearn |
Crockford مینویسد ۴ حرف از ۲۶ حرف کنار گذاشته شدهاند: I L O U؛ چون I و L با 1 اشتباه میشوند، O با 0، و U «ناسزای تصادفی» میسازد. ULID از Crockford Base32 استفاده میکند؛ ID generation.
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؛ کدهای بازیابی که کاربر تایپ میکند.
| Product | Base32 API |
|---|---|
| Go | encoding/base32 (StdEncoding, HexEncoding, NewEncoding(alphabet).WithPadding) |
| PHP | none built in; see the Base32 class in Solving or a library |
| JavaScript | none native; libraries |
| Python | base64.b32encode, b32hexencode |
| PostgreSQL | encode(x, 'base32hex') in the version 19 docs |
راهحل: برای کدهای تایپشده توسط انسان، چهارتا چهارتا گروه کنید و بیتوجه به حروف decode کنید؛ برای TOTP فاصله و = را بردارید. کد: alphabets.
Base58 تکمیلی
به زبان ساده: الفبایی شبیه Base64 که نویسههای مشابه را ندارد تا از روی کاغذ یا صفحه بدون خطا کپی شود، و + و / ندارد تا دابلکلیک کل آن را انتخاب کند.
بدفهمی رایج: «Base58 هم مثل Base64 بیتبُر است.» ۵۸ توان ۲ نیست؛ مثل تبدیل یک عدد بسیار بزرگ به مبنای دیگر کار میکند، به تقسیم اعداد بزرگ نیاز دارد و نسبت به طول درجهدوم است. برای مقدارهای کوتاه (کلید، hash، شناسه) است، نه مگابایت.
تعریف: الفبای Bitcoin یعنی 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz؛ طبق توضیح کد Bitcoin: نویسههای 0OIl استفاده نمیشوند چون در بعضی فونتها یکساناند. هر بایت صفر ابتدایی به یک 1 ابتدایی تبدیل میشود. Base58Check پیش از کدگذاری یک checksum چهاربایتی (SHA-256 دوبار) اضافه میکند.
bytes 00 00 01 02 03 ff ee
b58 117bX9dP (two leading zero bytes -> two leading '1')سناریوهای واقعی: آدرس و کلید WIF در Bitcoin؛ شناسههای کوتاه کپیشونده توسط انسان.
| Product | Base58 |
|---|---|
| Go | github.com/btcsuite/btcutil/base58 or the 40-line math/big version in alphabets |
| PHP | libraries (stephen-hill/base58php) or the class in Solving |
| Variants | Bitcoin, 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 گونههای دیگرند.
$ 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).
| Product | Base85 |
|---|---|
| Go | encoding/ascii85 (Adobe variant) |
| PHP | none built in (libraries) |
| Python | base64.a85encode, base64.b85encode (its alphabet, read from base64._b85alphabet, is 0-9A-Za-z then !#$%&()*+-;<=>?@^_{ |
| Git | internal 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 میشود.
"سلام دنیا" 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؛ پارامترهای ردیابی.
| Function | Encodes | Space becomes | Leaves alone |
|---|---|---|---|
Go url.QueryEscape | everything outside A-Za-z0-9 - _ . ~ | + | unreserved only |
Go url.PathEscape | for one path segment: escapes / ; , ? # and non-ASCII (measured) | %20 | $ & + : = @ stay literal |
PHP urlencode | non-alphanumeric except -_. | + | so ~ becomes %7E |
PHP rawurlencode | RFC 3986 | %20 | -_.~ |
PHP http_build_query | default PHP_QUERY_RFC1738 | + | pass PHP_QUERY_RFC3986 for %20 |
JavaScript encodeURIComponent | all but A-Za-z0-9 - _ . ! ~ * ' ( ) | %20 | for one component |
JavaScript encodeURI | whole URL; keeps ; , / ? : @ & = + $ # | %20 | for a full URL only |
Python urllib.parse.quote / quote_plus | path-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».
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 path | a plus sign | a space |
URL query read as form data (PHP $_GET, Go Query(), Express req.query, Laravel $request->query()) | a space | a space |
application/x-www-form-urlencoded body | a space | a space |
multipart/form-data body | a plus sign (no percent decoding) | not decoded as such |
JavaScript encodeURIComponent output | never produced; + becomes %2B | space |
راهحل: هر مقدار 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 میکند و ../ را راه میرود.
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.
| Layer | Who decodes | Rule |
|---|---|---|
| Reverse proxy / WAF | may normalise %2e, %2f | decode once at the edge, not again downstream |
| Framework router | decodes the path | route parameters are already decoded |
| Application | decodes query | do 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 هرگز به سرور فرستاده نمیشود.
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)سناریوهای واقعی: کلید شیء S3 با اسلش و فاصله؛ منابع REST با ایمیل بهجای شناسه (/users/a%40b.test)؛ رابط جستوجو با query فارسی؛ SPAهایی که state را در fragment نگه میدارند؛ token های جریان implicit در OAuth.
| Component | Which characters must you encode | Go | PHP |
|---|---|---|---|
| Path segment | / ? # %, space, non-ASCII | url.PathEscape | rawurlencode |
| Query value | & = + # %, space, non-ASCII | url.QueryEscape, url.Values | http_build_query, rawurlencode |
| Fragment | space, non-ASCII, % (# only matters before it) | u.Fragment, u.EscapedFragment() | rawurlencode |
| Userinfo | : @ / ? # | url.UserPassword | rawurlencode per part |
| Host | IDNA to xn-- | idna.Lookup.ToASCII | idn_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 است).
مثال.ایران -> 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 باشد.
| Product | IDNA / IRI support |
|---|---|
| Go | golang.org/x/net/idna (Lookup, Registration, Display profiles); net/url does not convert hosts |
| PHP | idn_to_ascii / idn_to_utf8 (ext-intl) with INTL_IDNA_VARIANT_UTS46 |
| Laravel | Str::slug($title, language: null) skips ASCII transliteration and keeps letters (\pL) such as Persian (framework source), Str::ascii; URL helpers percent-encode paths |
| Browsers | show Unicode hosts when the script mix looks safe, Punycode otherwise |
| curl | converts 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 بهعنوان «کدگذاری» مهم
به زبان ساده: < در HTML و \n یا " در JSON همان ایدهٔ %20 است: راهی برای نوشتن نویسهای که در آن جا خام مجاز نیست.
بدفهمی رایج: «یک بار escape کردم، پس همهجا امن است.» escape وابسته به زمینهٔ خروجی است: متن HTML، attribute، رشتهٔ JavaScript، رشتهٔ JSON، URL، CSS. هر خروجی یک escaper.
تعریف: متن HTML به & و < نیاز دارد (و " در attribute)؛ نویسه را میشود س یا س هم نوشت. رشتهٔ JSON (RFC 8259): همهٔ نویسههای Unicode میتوانند داخل نقلقول بیایند مگر آنهایی که باید escape شوند: نقلقول، reverse solidus و نویسههای کنترلی (U+0000 تا U+001F)؛ هر نویسه را میشود \uXXXX نوشت.
HTML <a href="/?q=1&x=2">Tom & "Jerry"</a>
-> <a href="/?q=1&x=2">Tom & "Jerry"</a> (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؛ نام فارسی که به شکل ا... نمایش داده میشود؛ JSON با
که parserهای قدیمی JavaScript را میشکست؛ escape مضاعف که &amp; در صفحه نشان میدهد.
| Product | HTML escape | JSON escape controls |
|---|---|---|
| Go | html.EscapeString, html/template (contextual) | encoding/json escapes <, >, &, U+2028/2029; Encoder.SetEscapeHTML(false) |
| PHP / Laravel | htmlspecialchars, Blade's double-brace echo (escapes automatically) | JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_HEX_TAG |
| JavaScript | textContent, templating libraries | JSON.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) میدانند.
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.
| Aspect | Behaviour | Product note |
|---|---|---|
| Size | base64 form is +33%; prefix data:image/png;base64, adds 22 bytes | measured: 86-byte PNG became 138 characters |
| Caching | none separate from the document | use files plus HTTP caching instead for big or reused images |
| CSP | img-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 scripts | data: in script-src enables XSS |
| E-mail clients | support for data: images varies and some clients block them (not verified per client here) | use cid: attachments or hosted images |
| Origin | MDN: data URLs are treated as unique opaque origins | do 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).
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?... دیده میشود.
| Product | API |
|---|---|
| Go | mime/quotedprintable, mime.QEncoding / mime.BEncoding, mime.WordDecoder |
| PHP | quoted_printable_encode / _decode, mb_encode_mimeheader, iconv_mime_encode |
| Laravel | Symfony 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.
$ 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 است؛ مبهم است اما محرمانه نیست».
$ 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 را دارد میخواند).
| Claim | Reality |
|---|---|
| "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.
| Where | Encoding | Detail |
|---|---|---|
| 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 bytes | stringData: takes plain text and the API server encodes it; Secrets are limited to 1 MiB |
| HTTP Basic | standard Base64 of user:password (RFC 7617) | first colon splits, so user names cannot contain a colon |
Docker config.json auth | Base64 of user:password | obscured, not secret |
| E-mail attachments | Base64 with 76-char lines (RFC 2045) | Content-Transfer-Encoding: base64 |
HTML img src | data URI (RFC 2397) | CSP img-src data: |
| PEM files (certificates, keys) | Base64 body, 64-char lines between -----BEGIN ...----- markers | see TLS in Practice |
| Git LFS pointer file | text file: version, oid sha256:<64 hex>, size | the oid is hex of the content hash; pointers must be under 1024 bytes |
| Git binary patch | Git's Base85 | git diff --binary |
| Protobuf JSON mapping | bytes field becomes a Base64 string | "JSON value will be the data encoded as a string using standard base64"; parsers accept both alphabets |
| Cookie values | RFC 6265 allows + / =, forbids space, comma, semicolon, quote, backslash; at least 4096 bytes per cookie | Laravel's session and encrypted cookies are Base64 of JSON |
Laravel Encrypter payload | Base64 of a JSON object with base64 iv, value, mac, tag | read in the framework source |
| TOTP secret | Base32 | otpauth://totp/...?secret=JBSWY3DPEHPK3PXP |
| Laravel signed URL | signature= lower-case hex of HMAC-SHA256 over the URL | not base64 |
| SSH, WireGuard keys | Base64 | 32-byte key = 44 characters with padding |
راهحل: وقتی مطمئن نیستید با گونهٔ متناسب decode کنید و بررسی کنید؛ Lab.
نمودار بالا نقشهٔ مرزها را نشان میدهد: در یک درخواست، 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):
| Need | API | Notes |
|---|---|---|
| Standard padded | base64.StdEncoding | decoder ignores \r and \n only |
| Unpadded standard | base64.RawStdEncoding | |
| URL-safe padded / unpadded | base64.URLEncoding / base64.RawURLEncoding | JWT uses RawURLEncoding |
| Custom alphabet / padding | base64.NewEncoding(alphabet).WithPadding(rune); base64.NoPadding | alphabet must be 64 distinct bytes without \r \n |
| Reject non-zero trailing bits | enc.Strict() | |
| Streaming | base64.NewEncoder(enc, w) (must Close), base64.NewDecoder(enc, r) | |
| Sizes | EncodedLen, DecodedLen, AppendEncode | allocate buffers exactly |
| JSON | []byte fields become standard padded base64 strings | encoding/json |
| Hex | hex.EncodeToString, hex.DecodeString, hex.Dump | |
| Percent | url.QueryEscape, url.PathEscape, url.Values.Encode, url.ParseQuery |
PHP (۸.۴) و Laravel 13:
| Need | API | Notes |
|---|---|---|
| Base64 | base64_encode, base64_decode($s, strict: true) | non-strict silently discards invalid characters |
| Base64url | rtrim(strtr(base64_encode($s), '+/', '-_'), '=') | no built-in |
| Hex | bin2hex, hex2bin | |
| Percent (form) | urlencode, urldecode, http_build_query | space is + |
| Percent (RFC 3986) | rawurlencode, rawurldecode, http_build_query($d, '', '&', PHP_QUERY_RFC3986) | space is %20 |
| Laravel string helpers | Str::toBase64($s), Str::fromBase64($s, $strict = false) | thin wrappers over base64_encode and base64_decode (framework source) |
| Laravel query building | Arr::query($array) | calls http_build_query with PHP_QUERY_RFC3986 |
| Laravel signed URLs | URL::signedRoute, URL::temporarySignedRoute, $request->hasValidSignature(), signed middleware | signature is hex hash_hmac('sha256', ...) |
| Laravel encryption | Crypt::encryptString | output is Base64 of JSON |
| Quoted-printable | quoted_printable_encode | |
| IDN | idn_to_ascii, idn_to_utf8 | ext-intl |
JavaScript (مرورگر و Node):
| Need | API | Pitfall |
|---|---|---|
| Base64 of a binary string | btoa, atob | btoa('سلام') 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 bytes | Uint8Array.prototype.toBase64(), Uint8Array.fromBase64(); Node Buffer.from(x).toString('base64') | Node 26 here reports Uint8Array.prototype.toBase64 as a function |
| Percent | encodeURIComponent (component), encodeURI (whole URL), URLSearchParams (form rules, + for space) | escape/unescape are deprecated; do not use |
| UTF-8 bytes | new TextEncoder().encode(str) |
ابزارهای خط فرمان:
| Tool | Command | Behaviour on this machine |
|---|---|---|
base64 (macOS) | printf hello | base64 | no wrapping; -b 76 wraps; echo hello adds \n and changes the output (aGVsbG8K) |
base64 (GNU coreutils) | base64 -w 0 | wraps at 76 by default: "The default is to wrap after 76 characters. Use the value 0 to disable line wrapping" |
openssl base64 | openssl base64 -A | wraps at 64 (measured); -A single line |
xxd | xxd -p, xxd -r -p | hex dump and reverse |
curl | --data-urlencode 'q=a+b' | percent-encodes (lower-case hex: %2b) |
kubectl | kubectl get secret x -o jsonpath='{.data.password}' | base64 -d | decode a value |
git | git diff --binary | Base85 patches |
| PostgreSQL | encode(x, 'hex' / 'base64' / 'escape'), decode(...) | base64url and base32hex are in the 19 docs |
-- 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)
ریاضی بیت و طولها
| Encoding | Bits per char | Group (input to output) | Encoded length for n bytes |
|---|---|---|---|
| Base16 | 4 | 1 byte to 2 chars | 2n |
| Base32 | 5 | 5 bytes to 8 chars | 8 * ceil(n / 5) padded |
| Base64 | 6 | 3 bytes to 4 chars | 4 * ceil(n / 3) padded; ceil(4n / 3) unpadded |
| Base64 MIME | 6 | plus CRLF every 76 chars | 4 * ceil(n/3) + 2 * ceil(4*ceil(n/3) / 76) |
| Base85 | about 6.4 | 4 bytes to 5 chars | 5 * ceil(n / 4) |
| Base58 | about 5.86 | big-integer division | about 1.37n |
| Percent | variable | 1 byte to 3 chars when escaped | n 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، حافظه و لاگ دو طرف پرداخت میشود.
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 text | Source | Meaning |
|---|---|---|
illegal base64 data at input byte N | Go CorruptInputError | wrong alphabet, wrong padding mode, or stray character (the offset is a hint, not always exact) |
InvalidCharacterError: Invalid character | JavaScript atob / btoa (measured in Node) | non-alphabet character, or Unicode passed to btoa |
binascii.Error: Incorrect padding | Python | unpadded input to the padded decoder |
base64_decode(): ... returns false | PHP strict | character outside the alphabet or wrong padding |
URIError: URI malformed | JavaScript 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 path | web servers and proxies | invalid percent-escape, or an encoded / the server refuses (Apache has an AllowEncodedSlashes directive) |
Invalid signature (Laravel 403) | signed middleware | URL 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 روی این ماشین نصب نیست.
مسئلهٔ ۱: همان بایتها در همهٔ کدگذاریها
| Solution | How | Advantage | Cost |
|---|---|---|---|
| One table of all forms | hex, base64, base32, ascii85, percent in one program | shows size and look side by side | none |
// 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])
}خروجی واقعی:
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
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
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)
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Encode every query value | url.Values.Encode, http_build_query, URLSearchParams | correct for any value | must remember at every call site |
| base64url instead of base64 | RawURLEncoding | no + or / exists | other side must accept base64url |
| Never decode twice | decode where the value leaves the URL, once | no %2520 | needs discipline across proxies |
// 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"))
}خروجی واقعی:
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
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 حذفشده، الفبای اشتباه، بیتهای شل
// 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 است، نه تعهد):
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 3PHP: از base64UrlDecode در Encodings.php استفاده کنید (دوباره pad میکند و بعد base64_decode(..., strict: true)).
مسئلهٔ ۴: decode کردن base64 دست مهاجم و محدودیت طول
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Cap before decode | reject len(s) > max; http.MaxBytesReader; Laravel max: | no big allocation | choose a sensible limit |
| Decode strictly | Go Strict(); PHP strict: true | rejects noise and ambiguity | breaks lenient producers |
| Cap after decode | DecodedLen check | catches expansion tricks | tiny |
| Verify content, not label | check PNG/JPEG magic bytes, re-encode images | stops disguised payloads | more code |
// 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)))
}
}خروجی واقعی:
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
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)]);
}
}مسئلهٔ ۵: فایل بزرگ با حافظهٔ ثابت
// 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، رفتوبرگشت تأییدشده):
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
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
// 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)
}خروجی واقعی:
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
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
// 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)
}خروجی واقعی:
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
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)
// 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)
}خروجی واقعی:
مثال.ایران -> 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
// 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("<b> &amp; سل é"))
// 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)
}خروجی واقعی:
HTML escape : <a href="/?q=1&x=2">Tom & "Jerry"</a>
HTML unesc : <b> & سل é
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
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
// 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):
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
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
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)
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)
}
}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مسئلهٔ ۱۳: یک تصویر چقدر هزینه دارد؟
// 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)))
}انتخاب
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Binary in a JSON/XML body (API) | standard Base64 | prefer multipart/binary for files over about 100 KB | universally supported, +33% |
| Token, ID, hash in a URL, cookie, filename | base64url, no padding | length cap; compare in constant time | no + / = to escape |
| Value a person will read aloud or type | Crockford Base32 or Base58 | group in fours, add a check symbol | removes look-alike characters |
| TOTP/2FA secret | RFC 4648 Base32 | uppercase, strip spaces and = | what authenticator apps expect |
| Debugging, hashes, byte dumps | hex | group by 2 or 4 | clearest, 2x |
| Smallest text form of 4-byte blocks, in a file format | Ascii85 or Z85 | not in HTML/JSON | 1.25x |
| User text in a URL query | url.Values, http_build_query | UTF-8 first | + and & handled |
| User text in a URL path segment | PathEscape, rawurlencode | per segment | %20, %2F |
| Domain names with Persian letters | IDNA to xn-- | UTS #46 profile; show Unicode in UI | DNS carries ASCII |
| Small icon in HTML or CSS | data: URI | CSP img-src data: | one fewer request |
| Large or reused image | file or object storage URL | CDN and cache headers | caching beats inlining |
| Secret storage | real encryption (KMS, AES-GCM) | not encoding | encoding is reversible by everyone |
| Binary between services you own | bytes (Protobuf, gRPC, multipart) | base64 only at JSON edges | saves 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 و دوباره در سرویس.
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 (مسیر مقیاس)
| Load | What changes |
|---|---|
| 1x (hundreds of requests per second) | Standard libraries; encode in the handler; base64 in JSON is fine |
| 10x | Stop base64-ing files in JSON: use upload URLs and streaming; use AppendEncode-style APIs and pooled buffers; cap sizes at the edge |
| 100x | Binary 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-region | Keep encodings in the contract, version them, and test with a golden vector file (known inputs and outputs) in every language you ship |
عیبیابی (Troubleshooting)
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
| Token verifies locally, fails after a redirect or e-mail link | + became a space, or = was dropped | compare the received query string byte by byte | percent-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 base64 | echo -n or printf | use printf '%s'; check Kubernetes Secret values with base64 -d | xxd |
| Login to a service fails with a "correct" Kubernetes Secret | newline inside the encoded value | kubectl get secret x -o jsonpath='{.data.k}' | base64 -d | xxd | tail | recreate with --from-literal or echo -n |
InvalidCharacterError from btoa | string contains characters above 0xFF | contains Persian or emoji | TextEncoder to UTF-8 bytes, then Base64 |
Persian text shows سلام | UTF-8 bytes decoded as Latin-1 after Base64 | check charset | decode bytes as UTF-8 |
%2520 in a URL | double encoding | decode once and look again | encode once |
400 or 404 only when path has %2F | proxy or server rejects encoded slashes | nginx/Apache logs | change the identifier (base64url) or the server setting |
| Image does not show in e-mail | client blocks data: images | test in Gmail/Outlook | use a cid: attachment or a hosted image |
| CSP violation for an inline image | img-src lacks data: | browser console | add data: to img-src only |
| Laravel signed URL gives 403 | URL re-encoded, parameter order changed, proxy rewrote the host | compare the incoming URL with the generated one | pass the original query untouched; set trusted proxies |
| Two services compute different hashes for the "same" string | hex case, padding or line wrap differs | normalise to lower-case hex | one canonical form, constant-time compare |
| Memory spike when encoding an upload | whole file built as a string | profile | NewEncoder/stream filters |
| Pasting a key breaks in a chat app | = or + reformatted | view as plain text | use base64url or hex for pasted secrets |
آزمایشگاه (Lab)
روی Mac یا Linux کپی-پیست کنید؛ برنامهها Go 1.24 به بالا میخواهند. همه چیز را از docs/snippets/foundations/binary-to-text-encoding/go اجرا کنید.
آزمایش ۱ — مقایسهٔ حجم برای یک رشتهٔ فارسی و یک فایل (تصویر).
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آزمایش ۲ — بازتولید باگ + به فاصله و رفعش.
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.
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).
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.
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 امن.
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بدفهمیهای رایج
| Belief | Reality |
|---|---|
| "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)
| Topic | What to remember |
|---|---|
| Base64 size | 3 bytes to 4 chars, 4*ceil(n/3), +33%; MIME wrap adds CRLF every 76 (about 1.37x) |
| Base64 alphabets | A-Za-z0-9+/ and =; url-safe A-Za-z0-9-_ |
| Where padding is dropped | JWT (JWS), many URL tokens: RFC 4648 allows when the length is implicit |
| JWT | three base64url segments joined by .; eyJ starts a JSON object; signed, not encrypted |
| Hex | 2 chars per byte, 2x, case-insensitive; compare in constant time |
| Base32 | A-Z2-7, 1.6x, case-insensitive; TOTP secrets; Crockford drops ILOU |
| Base58 | Bitcoin alphabet without 0OIl+/; big-integer maths; short values only |
| Base85 | 5 chars per 4 bytes, 1.25x; Ascii85 in PDF; Git has its own alphabet |
| Unreserved characters | A-Z a-z 0-9 - . _ ~; encode everything else per component |
+ vs %20 | + is a space only in form encoding; always encode query values |
| Double encoding | encode once, decode once; %25 is the sign of a second pass |
| IRI and IDNA | browsers map Persian URLs to UTF-8 %XX paths and xn-- hosts |
| Data URI | data:<type>;base64,<data>; only small assets; CSP img-src data: |
| Decoding untrusted input | cap length first, decode strictly, verify content type, cap decoded size |
| Not encryption | Base64, hex, percent, Basic, Kubernetes data: are all readable without a key |
| Go | base64.StdEncoding, RawURLEncoding, url.Values, hex, NewEncoder for streams |
| PHP and Laravel | base64_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)
| Term | One line |
|---|---|
| Binary-to-text encoding | A reversible mapping of arbitrary bytes onto a restricted printable alphabet |
| Alphabet | The set of characters an encoding may output |
| Quantum | RFC 4648 term for the input group that maps to one output unit (3 bytes for Base64) |
| Base16 / hex | 4 bits per character, 0-9A-F |
| Base32 | 5 bits per character, A-Z2-7, case-insensitive |
| base32hex | Base32 with 0-9A-V so order is preserved |
| Crockford Base32 | Base32 without I L O U, tolerant decoding, optional check symbol |
| z-base-32 | Human-oriented Base32 with a reordered lower-case alphabet |
| Base58 | Big-integer base with no 0 O I l + /; Bitcoin alphabet |
| Base58Check | Base58 plus a 4-byte double-SHA-256 checksum |
| Base64 | 6 bits per character, A-Za-z0-9+/ |
| Base64url | Base64 with - and _; RFC 4648 section 5 |
Padding (=) | Filler making the output a multiple of 4 (Base64) or 8 (Base32) characters |
| Raw / unpadded | Base64 without =, as used by JWT |
| MIME line wrapping | Lines of at most 76 characters separated by CRLF |
| Pad bits | Unused low bits in the last character; must be zero in canonical form |
| Strict decoding | Rejecting input with non-alphabet characters, wrong padding or non-zero pad bits |
| Forgiving-base64 | The WHATWG decode used by atob: strips whitespace, tolerates missing padding |
| Ascii85 / Base85 | 5 characters per 4 bytes; Adobe, Git, RFC 1924 and Z85 variants |
| uuencode | Unix-to-Unix encoding, 1980s ancestor of Base64 |
| Quoted-printable | MIME encoding that keeps printable ASCII and writes other bytes as =XX |
| Encoded-word | RFC 2047 syntax =?charset?B or Q?text?= for non-ASCII mail headers |
| Percent-encoding | %XX for a byte; RFC 3986 pct-encoded |
| Unreserved characters | A-Z a-z 0-9 - . _ ~: never need encoding |
| Reserved characters | gen-delims and sub-delims: delimiters with meaning inside a URL |
application/x-www-form-urlencoded | Form encoding where space is + and + is decoded as space |
| Double encoding | Encoding an already-encoded value, producing %25 sequences |
| URI / URL | An ASCII identifier; URL is a URI that locates |
| IRI | URI that may contain Unicode characters (RFC 3987), mapped to a URI |
| IDNA | Internationalized Domain Names in Applications |
| Punycode | RFC 3492 ASCII form of Unicode labels, prefixed xn-- |
| Data URI | data: URL with inline data (RFC 2397) |
| CSP | Content-Security-Policy; img-src must allow data: for inline images |
| JWS / JWT | Signed token: three base64url segments joined by . |
| HTTP Basic | Authorization: Basic + Base64 of user:password |
| HTML entity | &, س: HTML's escape syntax |
| JSON escape | \", \\, \n, \uXXXX in a JSON string |
| Obfuscation | Making data look unreadable without a key; not security |
| SIMD base64 | Vectorised encoders/decoders (AVX2, AVX-512, NEON) that approach memcpy speed |
| Git LFS pointer | Small text file with version, oid sha256: and size that stands in for a large file |
| TOTP secret | Base32-encoded key in otpauth:// URIs |
منابع (References)
همهٔ منابع در ۲۰۲۶-۱۱-۲۵ دریافت و خوانده شدهاند؛ نسخهٔ محلی هر کدام ذخیره شده است. همهٔ لینکها کد ۲۰۰ برگرداندند.
- RFC 4648, The Base16, Base32, and Base64 Data Encodings (October 2006): https://www.rfc-editor.org/rfc/rfc4648.txt
- RFC 3548 (July 2003): https://www.rfc-editor.org/rfc/rfc3548.txt
- RFC 3986, URI Generic Syntax (January 2005): https://www.rfc-editor.org/rfc/rfc3986.txt
- RFC 3987, Internationalized Resource Identifiers (January 2005): https://www.rfc-editor.org/rfc/rfc3987.txt
- RFC 3492, Punycode (March 2003): https://www.rfc-editor.org/rfc/rfc3492.txt
- RFC 2397, The "data" URL scheme (August 1998): https://www.rfc-editor.org/rfc/rfc2397.txt
- RFC 2045, MIME Part One (November 1996): https://www.rfc-editor.org/rfc/rfc2045.txt
- RFC 2047, MIME Part Three, message header extensions (November 1996): https://www.rfc-editor.org/rfc/rfc2047.txt
- RFC 7515, JSON Web Signature (May 2015): https://www.rfc-editor.org/rfc/rfc7515.txt
- RFC 7519, JSON Web Token: https://www.rfc-editor.org/rfc/rfc7519.txt
- RFC 7617, The 'Basic' HTTP Authentication Scheme (September 2015): https://www.rfc-editor.org/rfc/rfc7617.txt
- RFC 8259, JSON (December 2017): https://www.rfc-editor.org/rfc/rfc8259.txt
- RFC 6265, HTTP State Management (cookies): https://www.rfc-editor.org/rfc/rfc6265.txt
- RFC 6238, TOTP: https://www.rfc-editor.org/rfc/rfc6238.txt
- WHATWG URL Standard (application/x-www-form-urlencoded, percent-encode sets): https://url.spec.whatwg.org/
- WHATWG Infra Standard, forgiving-base64 decode: https://infra.spec.whatwg.org/
- Crockford Base 32: https://www.crockford.com/base32.html
- z-base-32 design note (Zooko): https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
- Bitcoin wiki, Base58Check encoding: https://en.bitcoin.it/wiki/Base58Check_encoding
- Git source
base85.c: https://raw.githubusercontent.com/git/git/master/base85.c - git-diff documentation (
--binary): https://git-scm.com/docs/git-diff - Git LFS specification: https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md
- Wikipedia, Ascii85 and Uuencode (secondary): https://en.wikipedia.org/wiki/Ascii85, https://en.wikipedia.org/wiki/Uuencode
- Google Authenticator Key URI format: https://github.com/google/google-authenticator/wiki/Key-Uri-Format
- Kubernetes documentation, Secrets: https://kubernetes.io/docs/concepts/configuration/secret/
- Protocol Buffers, JSON mapping: https://protobuf.dev/programming-guides/json/
- MDN,
btoa(): https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa ;data:URLs: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data ;encodeURIComponent: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent - W3C Content Security Policy Level 3: https://www.w3.org/TR/CSP3/
- Go
encoding/base64source and docs: https://raw.githubusercontent.com/golang/go/master/src/encoding/base64/base64.go (alsogo doc encoding/base64,net/url,encoding/hex,encoding/base32) - PHP manual: https://www.php.net/manual/en/function.base64-encode.php, https://www.php.net/manual/en/function.base64-decode.php, https://www.php.net/manual/en/function.urlencode.php, https://www.php.net/manual/en/function.rawurlencode.php, https://www.php.net/manual/en/function.http-build-query.php ; php-src
ext/standard/base64.c: https://raw.githubusercontent.com/php/php-src/master/ext/standard/base64.c - Laravel 13 docs, URLs (signed URLs) and Strings (
Str::toBase64,Str::fromBase64): https://laravel.com/docs/13.x/urls , https://laravel.com/docs/13.x/strings ; framework sourceUrlGenerator.php,Str.php,Arr.php,Encrypter.php(13.x branch on GitHub) - PostgreSQL documentation, binary string functions (
encode,decode): https://www.postgresql.org/docs/current/functions-binarystring.html - Java
java.util.Base64: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Base64.html - GNU coreutils,
base64invocation: https://www.gnu.org/software/coreutils/manual/html_node/base64-invocation.html - Lemire and Muła, "Faster Base64 Encoding and Decoding using AVX2 Instructions" / AVX-512 follow-up, arXiv 1910.05109: https://arxiv.org/abs/1910.05109 ; simdutf: https://github.com/simdutf/simdutf
- OWASP, Double Encoding: https://owasp.org/www-community/Double_Encoding