From 6a3cae65efe98178ce4d9b1f481c0da92bb49097 Mon Sep 17 00:00:00 2001 From: ru44 <18311071+ru44@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:24:18 +0300 Subject: [PATCH] feat: new lesson "AES step by step" with the real S-box, MixColumns matrix and round keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Students type their own message and key (16 bytes each) and walk through real AES-128: round 0's XOR with the key, then SubBytes (the 16×16 S-box table with the byte's row and column lit up), ShiftRows (each row's slide drawn), MixColumns (the fixed matrix times the column, with the products worked out) and AddRoundKey (the XOR shown bit by bit). Clicking any byte shows how it was made. The ciphertext after round 10 updates as they type. The AES engine is checked against the FIPS-197 examples (appendix B round 1 and both ciphertexts). The lesson comes right after "Block ciphers and AES". --- content/lessons/cryptography/_order.yaml | 1 + .../cryptography/aes-step-by-step/ar.md | 73 +++++++ .../cryptography/aes-step-by-step/en.md | 73 +++++++ .../cryptography/aes-step-by-step/lesson.yaml | 65 ++++++ .../block-ciphers-and-aes/lesson.yaml | 1 + content/ui/ar/aes-explorer.yaml | 37 ++++ content/ui/en/aes-explorer.yaml | 37 ++++ scripts/test-engine.ts | 17 ++ src/engine/aes.ts | 89 ++++++++ src/viz/cryptography/AesExplorer.vue | 205 ++++++++++++++++++ 10 files changed, 598 insertions(+) create mode 100644 content/lessons/cryptography/aes-step-by-step/ar.md create mode 100644 content/lessons/cryptography/aes-step-by-step/en.md create mode 100644 content/lessons/cryptography/aes-step-by-step/lesson.yaml create mode 100644 content/ui/ar/aes-explorer.yaml create mode 100644 content/ui/en/aes-explorer.yaml create mode 100644 src/engine/aes.ts create mode 100644 src/viz/cryptography/AesExplorer.vue diff --git a/content/lessons/cryptography/_order.yaml b/content/lessons/cryptography/_order.yaml index 0b944ccf..54e518cd 100644 --- a/content/lessons/cryptography/_order.yaml +++ b/content/lessons/cryptography/_order.yaml @@ -13,6 +13,7 @@ - password-salting - confusion-and-diffusion - block-ciphers-and-aes +- aes-step-by-step - digital-signatures - elliptic-curve-cryptography - secret-sharing diff --git a/content/lessons/cryptography/aes-step-by-step/ar.md b/content/lessons/cryptography/aes-step-by-step/ar.md new file mode 100644 index 00000000..a2f5a84c --- /dev/null +++ b/content/lessons/cryptography/aes-step-by-step/ar.md @@ -0,0 +1,73 @@ +--- +title: 'تشفير AES خطوة بخطوة: الشيفرة الحقيقية بايتًا بايتًا' +summary: اكتب رسالة ومفتاحًا وتابع AES الحقيقي في جولاته العشر، مع جدول الاستبدال وإزاحة الصفوف وخلط الأعمدة والمفتاح. +parameters: + round: الجولة (0 = قبل بدء الجولات) + step: الخطوة داخل الجولة (1 إلى 4) + cell: البايت الذي تتابعه (0 إلى 15) +variables: + - الشبكة (16 بايتًا) بعد الجولة r + - الشبكة قبل الجولة r + - مفتاح الجولة r، ونصنعه من مفتاحك + - 'استبدال البايتات: كل بايت يمر في جدول الاستبدال' + - 'إزاحة الصفوف: الصف r ينزاح r خانات إلى اليسار' + - 'خلط الأعمدة: كل عمود يُضرب في المصفوفة الثابتة' +--- + +## Try it + +1. اجعل «الجولة» 0. أول بايت في الرسالة هو 68، أي الحرف h، وأول بايت في المفتاح هو 6d، أي الحرف m. يحسب صندوق الحساب $\mathtt{68 \oplus 6d = 05}$ بتًا بتًا. +2. اجعل «الجولة» 1 و«الخطوة» 1. البايت 05 موجود في الصف 0 والعمود 5 من جدول الاستبدال، والخانة هناك فيها 6b، فيصير البايت 6b. +3. اجعل «الخطوة» 3. صار البايت الأول $\mathtt{2\cdot 6b \oplus 3\cdot 1a \oplus 76 \oplus 63 = d6 \oplus 2e \oplus 76 \oplus 63 = ed}$، فقد دخلت فيه بايتات العمود الأول الأربعة كلها. + +## Real-life examples + +1. **أول حركة في كل كتلة.** «الجولة» = 0 تعرض الشيء الوحيد الذي يحدث قبل الجولات: نجمع الرسالة مع المفتاح بعملية XOR. ذاكرة هاتفك، وشبكة الواي فاي في بيتك (WPA2)، والقفل في متصفحك (HTTPS)، كلها تبدأ كل كتلة من 16 بايتًا بهذه الطريقة. +2. **كيف يصل بايت واحد إلى العمود كله.** «الجولة» = 1 مع «الخطوة» = 3 تعرض خلط الأعمدة: العمود 6b 1a 76 63 يصير عمودًا جديدًا، وكل بايت فيه يعتمد على البايتات الأربعة. وبعد جولتين يصل تغيير بايت واحد إلى البايتات الـ16 كلها. +3. **آخر حركة قبل الإرسال.** «الجولة» = 10 مع «الخطوة» = 4 تضيف مفتاح الجولة الأخير. الناتج الذي يبدأ بـ 3e 80 8b 71 هو النص المشفر الذي يسافر عبر الشبكة. + +## Test yourself + +1. ابحث عن الجولة التي لا تستخدم خلط الأعمدة، وافتح خطوة خلط الأعمدة فيها. +2. في الجولة 1، افتح الخطوة التي تستخدم المفتاح. +3. في خطوة إزاحة الصفوف، اختر بايتًا من الصف الذي ينزاح 3 خانات. + +## Intuition + +يعمل AES الحقيقي على 16 بايتًا في كل مرة، مرتبة في شبكة 4×4. اكتب أي رسالة وأي مفتاح في الخانتين فوق الرسم. كل حرف إنجليزي بايت واحد، ونكتبه برقمين ست عشريين، فالحرف h هو 68 والحرف m هو 6d. قبل بدء الجولات يجمع AES الرسالة مع المفتاح بعملية XOR. ثم يجري 10 جولات، في كل جولة 4 خطوات. استبدال البايتات يغيّر كل بايت ببايت آخر من جدول ثابت فيه 256 خانة. وإزاحة الصفوف تحرك الصف 1 خانة واحدة إلى اليسار، والصف 2 خانتين، والصف 3 ثلاث خانات. وخلط الأعمدة يضرب كل عمود في مصفوفة ثابتة 4×4، فيؤثر كل بايت في العمود على الأربعة كلها. وإضافة مفتاح الجولة تجمع كل شيء بعملية XOR مع مفتاح جديد مصنوع من مفتاحك. + +استخدم «الجولة» و«الخطوة» لتمشي في الجولات، واضغط على أي بايت لترى بالضبط كيف حسبناه: أي خانة في الجدول، وأي إزاحة، وأي ضرب، وأي XOR. ثم غيّر حرفًا واحدًا في الرسالة، مثلًا 2026 إلى 2027. في الجولات الأولى تتغير بايتات قليلة فقط، لكن النص المشفر تحت الرسم يتغير كله: يتغير 62 بتًا من أصل 128. هذا هو الانتشار نفسه الذي رأيته في الدرس السابق على 16 بتًا، لكنه هنا في الشيفرة الحقيقية. + +## Formal + +يشفّر AES-128 كتلة $M$ من 128 بتًا بمفتاح $K$ من 128 بتًا. تبدأ الشبكة بـ $s_0 = M \oplus K_0$، وكل جولة تحسب $s_r = \mathrm{MC}(\mathrm{SR}(\mathrm{SB}(s_{r-1}))) \oplus K_r$ من $r = 1$ إلى $10$، إلا أن الجولة 10 لا تستخدم $\mathrm{MC}$. والنص المشفر هو $s_{10}$. نصنع مفاتيح الجولات الإحدى عشرة، $K_0, \dots, K_{10}$، من $K$ بطريقة اسمها جدولة المفتاح، وهي تستخدم جدول الاستبدال نفسه. + +كل بايت عنصر في حقل فيه 256 عنصرًا، نكتبه $\mathrm{GF}(2^8)$. جمع بايتين هو XOR. والضرب في 2 يزيح البتات خانة إلى اليسار، وإذا خرج 1 نجمع الناتج مع 1b، لأن الحقل مبني على كثيرة الحدود $x^8 + x^4 + x^3 + x + 1$. وجدول الاستبدال يأخذ مقلوب كل بايت في هذا الحقل، ثم يخلط بتاته بطريقة ثابتة ويجمع معه 63، ولهذا فاستبدال البايتات هو الخطوة الوحيدة غير الخطية. ويمكن عكس كل خطوة، ولذلك يجري فك التشفير الخطوات المعاكسة بالترتيب المعكوس. + +## Advanced + +اختار المعهد الوطني الأمريكي للمعايير والتقنية هذه الشيفرة من بين 15 مرشحًا، واعتمدها معيارًا عام 2001. اسمها الأصلي Rijndael، على اسم مصمميها البلجيكيين يوان دايمن وفنسنت رايمن. المفاتيح ذات 192 و256 بتًا تستخدم 12 و14 جولة. صُمم AES بحيث يمر أي فرق ينتقل عبر 4 جولات في 25 خانة على الأقل من جدول الاستبدال، ولهذا فأفضل هجوم معروف على AES الكامل أسرع بقليل فقط من تجربة كل المفاتيح. وفي أغلب المعالجات تعليمات خاصة بـ AES، فيشفّر الحاسوب المحمول عدة غيغابايتات في الثانية. وAES يشفّر كتلة واحدة، أما البيانات الطويلة فتُشفَّر بطريقة تشغيل مثل GCM، وهي تكشف أيضًا أي عبث بالبيانات. + +## Derivation + +1. البداية: نجمع بايتات الرسالة الـ16 مع بايتات المفتاح الـ16 بعملية XOR. +2. في كل جولة: استبدال البايتات، ثم إزاحة الصفوف، ثم خلط الأعمدة، ثم XOR مع مفتاح تلك الجولة. +3. بعد 10 جولات، والأخيرة منها بلا خلط الأعمدة، تصير الشبكة هي النص المشفر. + +## Real world + +### الواي فاي + +يشفّر WPA2 وWPA3 كل حزمة بيانات بين هاتفك والراوتر بـ AES. + +### المواقع الآمنة + +أغلب المواقع الآمنة تحمي بياناتها بـ AES-GCM، وهذا ما يعنيه القفل في متصفحك. + +### ذاكرة الهاتف + +يشفّر الآيفون وهواتف أندرويد كل ما في ذاكرتها بـ AES، بمفتاح مرتبط برمز القفل. + +### تطبيقات المراسلة + +يشفّر واتساب وسيغنال محتوى كل رسالة بـ AES، والمفاتيح يتفق عليها الطرفان ببروتوكول Signal. diff --git a/content/lessons/cryptography/aes-step-by-step/en.md b/content/lessons/cryptography/aes-step-by-step/en.md new file mode 100644 index 00000000..0a456968 --- /dev/null +++ b/content/lessons/cryptography/aes-step-by-step/en.md @@ -0,0 +1,73 @@ +--- +title: 'AES step by step: the real cipher, byte by byte' +summary: Type a message and a key and follow real AES through all 10 rounds — the lookup table, the row shifts, the column mixing and the key. +parameters: + round: round (0 = before the rounds) + step: step in the round (1–4) + cell: byte to follow (0–15) +variables: + - the 16-byte state after round r + - the state before round r + - the round key for round r, grown from your key + - 'SubBytes: every byte through the S-box table' + - 'ShiftRows: row r slides r places left' + - 'MixColumns: each column times the fixed matrix' +--- + +## Try it + +1. Set «round» to 0. The message's first byte is 68, the letter h, and the key's first byte is 6d, the letter m. The calculation box works out $\mathtt{68 \oplus 6d = 05}$ bit by bit. +2. Set «round» to 1 and «step» to 1. Byte 05 sits in row 0, column 5 of the S-box table, and the entry there is 6b, so the byte becomes 6b. +3. Set «step» to 3. Byte 0 is now $\mathtt{2\cdot 6b \oplus 3\cdot 1a \oplus 76 \oplus 63 = d6 \oplus 2e \oplus 76 \oplus 63 = ed}$: all four bytes of the first column went into it. + +## Real-life examples + +1. **The first move of every block.** «round» = 0 shows the only thing that happens before the rounds: the message is XORed with the key. Your phone's storage, your home Wi-Fi (WPA2) and the padlock in your browser (HTTPS) all start every 16-byte block this way. +2. **How one byte reaches the whole column.** «round» = 1 with «step» = 3 shows MixColumns turning the column 6b 1a 76 63 into a new column where every byte depends on all four. After two rounds, a change in one byte has spread to all 16. +3. **The last move before sending.** «round» = 10 with «step» = 4 adds the last round key. The result, starting 3e 80 8b 71, is the ciphertext that would travel over the network. + +## Test yourself + +1. Find the round that skips MixColumns, and open MixColumns in that round. +2. In round 1, open the step that uses the key. +3. In ShiftRows, select a byte from the row that slides 3 places. + +## Intuition + +Real AES works on 16 bytes at a time, laid out as a 4×4 grid. Type any message and key in the boxes above the picture. Each English letter is one byte, written as two hex digits, so h is 68 and m is 6d. Before the rounds start, AES XORs the message with the key. Then it runs 10 rounds of 4 steps. SubBytes swaps every byte for another one from a fixed table of 256 entries, the S-box. ShiftRows slides row 1 one place left, row 2 two places and row 3 three. MixColumns multiplies each column by a fixed 4×4 matrix, so every byte of a column changes all four. AddRoundKey XORs everything with a new round key made from your key. + +Use «round» and «step» to walk through the rounds, and click any byte to see exactly how it was made: which table entry, which shift, which multiplication, which XOR. Then change one letter of the message, for example 2026 to 2027. The first rounds change only a few bytes, but the ciphertext under the picture changes completely: 62 of its 128 bits flip. It is the same spreading you saw with 16 bits in the previous lesson, now in the real cipher. + +## Formal + +AES-128 encrypts a block $M$ of 128 bits with a key $K$ of 128 bits. The state starts as $s_0 = M \oplus K_0$, and each round computes $s_r = \mathrm{MC}(\mathrm{SR}(\mathrm{SB}(s_{r-1}))) \oplus K_r$ for $r = 1$ to $10$, except that round 10 leaves out $\mathrm{MC}$. The ciphertext is $s_{10}$. The 11 round keys $K_0, \dots, K_{10}$ are grown from $K$ by the key schedule, which uses the same S-box. + +Each byte is an element of a field with 256 elements, written $\mathrm{GF}(2^8)$. Adding two bytes is XOR. Multiplying by 2 shifts the bits one place left and, if a 1 falls off, XORs with 1b, because the field is built on the polynomial $x^8 + x^4 + x^3 + x + 1$. The S-box takes each byte's inverse in this field, then mixes its bits in a fixed way and adds 63, which makes SubBytes the only step that is not linear. Every step can be undone, so decryption runs the inverse steps in reverse order. + +## Advanced + +The U.S. National Institute of Standards and Technology chose this cipher from 15 candidates and made it a standard in 2001. Its original name is Rijndael, after its Belgian designers Joan Daemen and Vincent Rijmen. Keys of 192 and 256 bits use 12 and 14 rounds. AES is built so that any difference passing through 4 rounds goes through at least 25 S-box lookups, which is why the best known attack on full AES is only slightly faster than trying every key. Most processors have special AES instructions, so a laptop encrypts several gigabytes per second. AES encrypts one block; longer data is encrypted with a mode such as GCM, which also detects any tampering. + +## Derivation + +1. Start: XOR the 16 message bytes with the 16 key bytes. +2. Each round: SubBytes, then ShiftRows, then MixColumns, then XOR with that round's key. +3. After 10 rounds, the last one without MixColumns, the state is the ciphertext. + +## Real world + +### Wi-Fi + +WPA2 and WPA3 encrypt every packet between your phone and the router with AES. + +### HTTPS + +Most secure websites protect their traffic with AES-GCM; that is what the padlock in your browser stands for. + +### Phone storage + +iPhones and Android phones encrypt everything stored on them with AES, using a key tied to your passcode. + +### Messaging apps + +WhatsApp and Signal encrypt the content of each message with AES, with keys agreed by the Signal protocol. diff --git a/content/lessons/cryptography/aes-step-by-step/lesson.yaml b/content/lessons/cryptography/aes-step-by-step/lesson.yaml new file mode 100644 index 00000000..ee8eda64 --- /dev/null +++ b/content/lessons/cryptography/aes-step-by-step/lesson.yaml @@ -0,0 +1,65 @@ +id: aes-step-by-step +subject: cryptography +difficulty: high-school +added: '2026-11-27' +equation: s_r = \mathrm{MC}(\mathrm{SR}(\mathrm{SB}(s_{r-1}))) \oplus K_r +concepts: + - aes + - block-cipher + - s-box + - mix-columns + - xor +prerequisites: + - block-ciphers-and-aes + - xor-and-one-time-pad +related: + - confusion-and-diffusion + - hash-functions +visualization: + type: aes-explorer + options: + message: hello world 2026 + key: my secret key 16 +parameters: + round: + min: 0 + max: 10 + step: 1 + value: 1 + step: + min: 1 + max: 4 + step: 1 + value: 1 + cell: + min: 0 + max: 15 + step: 1 + value: 0 +variables: + - s_r + - s_{r-1} + - K_r + - \mathrm{SB} + - \mathrm{SR} + - \mathrm{MC} +derivation: + - s_0 = M \oplus K_0 + - s_r = \mathrm{MC}(\mathrm{SR}(\mathrm{SB}(s_{r-1}))) \oplus K_r, \quad r = 1, \dots, 9 + - C = s_{10} = \mathrm{SR}(\mathrm{SB}(s_9)) \oplus K_{10} +charts: [] +primary: step +presets: + - round: 0 + step: 4 + cell: 0 + - round: 1 + step: 3 + cell: 0 + - round: 10 + step: 4 + cell: 0 +challenges: + - check: 'round == 10 and step == 3' + - check: 'round == 1 and step == 4' + - check: 'round >= 1 and step == 2 and (cell == 3 or cell == 7 or cell == 11 or cell == 15)' diff --git a/content/lessons/cryptography/block-ciphers-and-aes/lesson.yaml b/content/lessons/cryptography/block-ciphers-and-aes/lesson.yaml index fe03a777..cfa366f8 100644 --- a/content/lessons/cryptography/block-ciphers-and-aes/lesson.yaml +++ b/content/lessons/cryptography/block-ciphers-and-aes/lesson.yaml @@ -11,6 +11,7 @@ prerequisites: - xor-and-one-time-pad - binary-numbers related: + - aes-step-by-step - hash-functions - digital-signatures visualization: diff --git a/content/ui/ar/aes-explorer.yaml b/content/ui/ar/aes-explorer.yaml new file mode 100644 index 00000000..a9aa373f --- /dev/null +++ b/content/ui/ar/aes-explorer.yaml @@ -0,0 +1,37 @@ +aes.message: الرسالة (16 بايتًا) +aes.key: المفتاح (16 بايتًا) +aes.bytesNote: 'كل حرف إنجليزي أو رقم أو مسافة بايت واحد، والحرف العربي بايتان. نأخذ أول 16 بايتًا فقط، وإذا كان النص أقصر نكمله بمسافات. نكتب كل بايت برقمين من النظام الست عشري (من 0 إلى 9 ثم من a إلى f)، فالبايت 68 هو الحرف h.' +aes.title0: 'الجولة 0: قبل بدء الجولات نجمع الرسالة مع المفتاح بعملية XOR.' +aes.title: 'الجولة {r} من 10 · الخطوة {s} من 4: {name}' +aes.step1: استبدال البايتات (SubBytes) +aes.step2: إزاحة الصفوف (ShiftRows) +aes.step3: خلط الأعمدة (MixColumns) +aes.step4: إضافة مفتاح الجولة (AddRoundKey) +aes.short1: استبدال البايتات +aes.short2: إزاحة الصفوف +aes.short3: خلط الأعمدة +aes.short4: إضافة مفتاح الجولة +aes.what1: نستبدل كل بايت ببايت آخر من جدول ثابت فيه 256 خانة، اسمه جدول الاستبدال (S-box). +aes.what2: الصف 0 لا يتحرك، والصف 1 ينزاح خانة واحدة إلى اليسار، والصف 2 خانتين، والصف 3 ثلاث خانات. البايت الذي يخرج من اليسار يعود من اليمين. +aes.what3: نضرب كل عمود في مصفوفة ثابتة 4×4، فيؤثر كل بايت في العمود على البايتات الأربعة كلها. +aes.what3last: الجولة الأخيرة لا تستخدم هذه الخطوة، فلا يتغير شيء هنا. +aes.what4: نجمع كل بايت بعملية XOR مع البايت الذي في المكان نفسه من مفتاح هذه الجولة. +aes.click: اضغط على أي بايت لترى كيف حسبناه. +aes.before: قبل الخطوة +aes.after: بعد الخطوة +aes.order: البايتات تملأ الشبكة من أعلى إلى أسفل، عمودًا بعد عمود +aes.sbox: 'الجدول: الصف هو الرقم الأول من البايت، والعمود هو الرقم الثاني' +aes.rowShift: 'الصف {r}' +aes.matrix: المصفوفة الثابتة +aes.column: 'العمود {c}' +aes.roundKey: 'مفتاح الجولة {r}' +aes.subCalc: 'البايت {a}: اذهب إلى الصف {row} والعمود {col} في الجدول. الخانة هناك فيها {b}.' +aes.shift0: الصف 0 لا يتحرك، فيبقى هذا البايت في مكانه. +aes.shiftCalc: 'الصف {r} ينزاح إلى اليسار بمقدار {r}: كان هذا البايت في العمود {from} وصار في العمود {to}.' +aes.mixRule: '×1 يبقي البايت كما هو. و×2 يزيح بتاته خانة واحدة إلى اليسار، وإذا خرج 1 من اليسار نجمع الناتج مع 1b بعملية XOR. و×3 هو ×2 ثم XOR مع البايت نفسه. والرمز ⊕ يعني XOR.' +aes.keyWord: المفتاح +aes.xorRule: 'عملية XOR تقارن البتات واحدًا واحدًا: بتان متساويان يعطيان 0، وبتان مختلفان يعطيان 1.' +aes.cipher: 'النص المشفر بعد الجولة 10:' +aes.roundLabel: الجولة +aes.stepLabel: الخطوة +aes.byteLabel: البايت المختار diff --git a/content/ui/en/aes-explorer.yaml b/content/ui/en/aes-explorer.yaml new file mode 100644 index 00000000..6649d304 --- /dev/null +++ b/content/ui/en/aes-explorer.yaml @@ -0,0 +1,37 @@ +aes.message: Message (16 bytes) +aes.key: Key (16 bytes) +aes.bytesNote: 'Each English letter, digit or space is 1 byte; an Arabic letter is 2. Only the first 16 bytes are used, and a shorter text is filled with spaces. Bytes are shown in hex, two digits from 0–9 and a–f: 68 is the letter h.' +aes.title0: 'Round 0: before the rounds start, the message is XORed with the key.' +aes.title: 'Round {r} of 10 · step {s} of 4: {name}' +aes.step1: SubBytes +aes.step2: ShiftRows +aes.step3: MixColumns +aes.step4: AddRoundKey +aes.short1: SubBytes +aes.short2: ShiftRows +aes.short3: MixColumns +aes.short4: AddRoundKey +aes.what1: Every byte is swapped for another from a fixed table of 256 entries, the S-box. +aes.what2: Row 0 stays put, row 1 slides 1 place left, row 2 slides 2 and row 3 slides 3. A byte that falls off the left end comes back on the right. +aes.what3: Each column is multiplied by a fixed 4×4 matrix, so every byte of the column changes all four. +aes.what3last: The last round skips this step, so nothing changes here. +aes.what4: Every byte is XORed with the byte in the same place of this round's key. +aes.click: Click any byte to see how it was made. +aes.before: before +aes.after: after +aes.order: bytes fill the grid down each column, column by column +aes.sbox: 'the S-box: row = first hex digit, column = second' +aes.rowShift: 'row {r}' +aes.matrix: fixed matrix +aes.column: 'column {c}' +aes.roundKey: 'round key {r}' +aes.subCalc: 'Byte {a}: go to row {row}, column {col} of the table. The entry there is {b}.' +aes.shift0: Row 0 does not move, so this byte stays in its place. +aes.shiftCalc: 'Row {r} slides {r} places left: this byte was in column {from} and is now in column {to}.' +aes.mixRule: '×1 keeps the byte. ×2 shifts its bits one place left, and if a 1 falls off the left end, XORs with 1b. ×3 is ×2 XORed with the byte itself. ⊕ means XOR.' +aes.keyWord: key +aes.xorRule: 'XOR compares bit by bit: two equal bits give 0, two different bits give 1.' +aes.cipher: 'Ciphertext after round 10:' +aes.roundLabel: round +aes.stepLabel: step +aes.byteLabel: selected byte diff --git a/scripts/test-engine.ts b/scripts/test-engine.ts index 08ef0b67..565cb04c 100644 --- a/scripts/test-engine.ts +++ b/scripts/test-engine.ts @@ -152,3 +152,20 @@ ok4('a perfect score stays a modest estimate', iqs[60].iq <= 135 && iqs[60].iq > ok4('very low scores give no number', iqs[20].tooLow && !iqs[30].tooLow, [iqs[20], iqs[30]]) if (f4) { console.log(`\n${f4} FAILED (rough IQ)`); process.exit(1) } console.log('rough IQ checks passed') + +// ---- AES-128 (FIPS-197 examples) -------------------------------------------------------------- +import { aesTrace, fromHex, toHex, SBOX } from '../src/engine/aes' +let f5 = 0 +const ok5 = (name: string, cond: boolean, got: unknown) => { + if (!cond) f5++ + console.log(`${cond ? '✓' : '✗'} ${name}${cond ? '' : ' → got ' + JSON.stringify(got)}`) +} +const fipsB = aesTrace(fromHex('3243f6a8885a308d313198a2e0370734'), fromHex('2b7e151628aed2a6abf7158809cf4f3c')) +ok5('S-box: 00 → 63, 53 → ed, ff → 16', SBOX[0] === 0x63 && SBOX[0x53] === 0xed && SBOX[0xff] === 0x16, [SBOX[0], SBOX[0x53], SBOX[0xff]]) +ok5('FIPS-197 appendix B: round 1 SubBytes starts d4', fipsB[1].sub[0] === 0xd4, fipsB[1].sub[0]) +ok5('FIPS-197 appendix B: round 1 MixColumns starts 04 66 81 e5', toHex(fipsB[1].mix.slice(0, 4)) === '046681e5', toHex(fipsB[1].mix)) +ok5('FIPS-197 appendix B: ciphertext 3925841d…', toHex(fipsB[10].end) === '3925841d02dc09fbdc118597196a0b32', toHex(fipsB[10].end)) +const fipsC = aesTrace(fromHex('00112233445566778899aabbccddeeff'), fromHex('000102030405060708090a0b0c0d0e0f')) +ok5('FIPS-197 appendix C.1: ciphertext 69c4e0d8…', toHex(fipsC[10].end) === '69c4e0d86a7b0430d8cdb78070b4c55a', toHex(fipsC[10].end)) +if (f5) { console.log(`\n${f5} FAILED (AES)`); process.exit(1) } +console.log('all AES tests passed') diff --git a/src/engine/aes.ts b/src/engine/aes.ts new file mode 100644 index 00000000..1c2bbeba --- /dev/null +++ b/src/engine/aes.ts @@ -0,0 +1,89 @@ +// AES-128 (FIPS-197), written to show every step rather than to be fast. A state is 16 bytes in AES order: +// byte i sits in row i % 4, column i >> 2, so the bytes fill the 4×4 grid column by column. + +/** The S-box: 256 fixed entries; byte b is replaced by SBOX[b] (row = first hex digit, column = second). */ +export const SBOX: number[] = (() => { + const s = new Array(256) + const rotl = (x: number, k: number) => ((x << k) | (x >>> (8 - k))) & 0xff + let p = 1 + let q = 1 + // p runs through every non-zero byte (multiplying by 3); q is its inverse in GF(2⁸) (dividing by 3) + do { + p = (p ^ (p << 1) ^ (p & 0x80 ? 0x1b : 0)) & 0xff + q ^= q << 1 + q ^= q << 2 + q ^= q << 4 + q &= 0xff + if (q & 0x80) q ^= 0x09 + s[p] = q ^ rotl(q, 1) ^ rotl(q, 2) ^ rotl(q, 3) ^ rotl(q, 4) ^ 0x63 + } while (p !== 1) + s[0] = 0x63 + return s +})() + +/** The fixed MixColumns matrix. */ +export const MIX = [ + [2, 3, 1, 1], + [1, 2, 3, 1], + [1, 1, 2, 3], + [3, 1, 1, 2], +] + +/** ×2 in AES arithmetic: shift left one bit; if a 1 fell off the left end, XOR with 1B. */ +export const xtime = (b: number) => ((b << 1) ^ (b & 0x80 ? 0x1b : 0)) & 0xff +/** ×1, ×2 or ×3 (the only factors MixColumns uses): ×3 is ×2 XOR the byte itself. */ +export const mul = (b: number, k: number) => (k === 1 ? b : k === 2 ? xtime(b) : xtime(b) ^ b) + +export const subBytes = (s: number[]) => s.map((b) => SBOX[b]) +/** Row r slides r places left: the byte at (r, c) comes from (r, c + r). */ +export const shiftRows = (s: number[]) => s.map((_, i) => s[(i % 4) + 4 * (((i >> 2) + (i % 4)) % 4)]) +export const mixColumns = (s: number[]) => + s.map((_, i) => { + const r = i % 4 + const c = i >> 2 + return MIX[r].reduce((acc, k, j) => acc ^ mul(s[4 * c + j], k), 0) + }) +export const xor = (a: number[], b: number[]) => a.map((x, i) => x ^ b[i]) + +/** The 11 round keys (16 bytes each) grown from a 16-byte key. */ +export function roundKeys(key: number[]): number[][] { + const w: number[][] = [] + for (let i = 0; i < 4; i++) w.push(key.slice(4 * i, 4 * i + 4)) + let rcon = 1 + for (let i = 4; i < 44; i++) { + let t = w[i - 1] + if (i % 4 === 0) { + t = [SBOX[t[1]] ^ rcon, SBOX[t[2]], SBOX[t[3]], SBOX[t[0]]] + rcon = xtime(rcon) + } + w.push(w[i - 4].map((x, j) => x ^ t[j])) + } + return Array.from({ length: 11 }, (_, r) => w.slice(4 * r, 4 * r + 4).flat()) +} + +/** One round's states: start → sub → shift → mix → end (= mix XOR key). Round 0 is only the XOR with the key. */ +export interface AesRound { + start: number[] + sub: number[] + shift: number[] + mix: number[] + key: number[] + end: number[] +} + +export function aesTrace(message: number[], key: number[]): AesRound[] { + const keys = roundKeys(key) + const rounds: AesRound[] = [{ start: message, sub: message, shift: message, mix: message, key: keys[0], end: xor(message, keys[0]) }] + for (let r = 1; r <= 10; r++) { + const start = rounds[r - 1].end + const sub = subBytes(start) + const shift = shiftRows(sub) + // the last round skips MixColumns + const mix = r < 10 ? mixColumns(shift) : shift + rounds.push({ start, sub, shift, mix, key: keys[r], end: xor(mix, keys[r]) }) + } + return rounds +} + +export const fromHex = (h: string) => Array.from({ length: h.length / 2 }, (_, i) => parseInt(h.slice(2 * i, 2 * i + 2), 16)) +export const toHex = (b: number[]) => b.map((x) => x.toString(16).padStart(2, '0')).join('') diff --git a/src/viz/cryptography/AesExplorer.vue b/src/viz/cryptography/AesExplorer.vue new file mode 100644 index 00000000..4068e808 --- /dev/null +++ b/src/viz/cryptography/AesExplorer.vue @@ -0,0 +1,205 @@ + + +