Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion scripts/sync.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { marked } from 'marked';
import { collections, projects, site } from '../projects.config.mjs';
import { linkRfcsInMarkdown, markedRfc } from '../src/lib/rfc.mjs';

// Every RFC mention links to the Datatracker, in all HTML built here.
marked.use(markedRfc);

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const cacheDir = path.join(root, '.cache', 'repos');
Expand Down Expand Up @@ -182,7 +186,7 @@ function rewriteLinks(md, ctx) {
if (isImage) return `https://raw.githubusercontent.com/${repo}/${branch}/${resolved}`;
return `https://github.com/${repo}/blob/${branch}/${resolved}${hash ? `#${hash}` : ''}`;
};
return md
return linkRfcsInMarkdown(md)
.replace(/(!?)\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(\s+"[^"]*")?\s*\)/g, (m, bang, text, url, title = '') =>
`${bang}[${text}](${fix(url, !!bang)}${title})`,
)
Expand Down
11 changes: 11 additions & 0 deletions src/components/RfcText.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
// Renders a plain string with every RFC mention linked to the Datatracker.
import { rfcParts } from '../lib/rfc.mjs';

interface Props {
text: string;
}
const parts = rfcParts(Astro.props.text);
---

{parts.map((p) => (typeof p === 'string' ? p : <a href={p.href} class="text-fg underline decoration-fg/30 underline-offset-2 hover:decoration-fg">{p.text}</a>))}
203 changes: 203 additions & 0 deletions src/components/toolbox/Aes.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
---
// AES in the classic modes. GCM lives on the "Encrypt and decrypt" tool.
const modes = [
['cbc', 'CBC'],
['ctr', 'CTR'],
['ecb', 'ECB'],
['cfb', 'CFB (128-bit)'],
['cfb8', 'CFB8'],
['ofb', 'OFB'],
['ccm', 'CCM (authenticated)'],
['xts', 'XTS (disk encryption)'],
['pcbc', 'PCBC'],
['ige', 'IGE'],
];
const paddings = [
['pkcs7', 'PKCS#7'],
['ansi', 'ANSI X9.23'],
['byte', 'ISO/IEC 7816-4'],
['zero', 'Zero bytes'],
['none', 'None'],
];
---

<div id="tb-aes" class="grid gap-5">
<div class="flex flex-wrap items-end gap-4">
<div>
<label for="aes-mode" class="tb-label">Mode</label>
<select id="aes-mode" class="tb-select w-auto">{modes.map(([v, l]) => <option value={v}>{l}</option>)}</select>
</div>
<div id="aes-padding-field">
<label for="aes-padding" class="tb-label">Padding</label>
<select id="aes-padding" class="tb-select w-auto">{paddings.map(([v, l]) => <option value={v}>{l}</option>)}</select>
</div>
<div id="aes-tag-field" hidden>
<label for="aes-tag" class="tb-label">Tag bytes</label>
<select id="aes-tag" class="tb-select w-auto">{[16, 14, 12, 10, 8, 6, 4].map((n) => <option>{n}</option>)}</select>
</div>
</div>
<p class="-mt-2 text-sm text-muted" id="aes-about"></p>

<div>
<div class="flex items-end justify-between gap-3">
<label for="aes-key" class="tb-label">Key (hex)</label>
<button type="button" class="tb-btn tb-btn-ghost tb-btn-sm mb-1.5" id="aes-key-random">New random key</button>
</div>
<input id="aes-key" class="tb-input tb-mono" autocomplete="off" spellcheck="false" />
<p class="tb-hint" id="aes-key-hint"></p>
</div>
<div id="aes-iv-field">
<div class="flex items-end justify-between gap-3">
<label for="aes-iv" class="tb-label" id="aes-iv-label">IV (hex)</label>
<button type="button" class="tb-btn tb-btn-ghost tb-btn-sm mb-1.5" id="aes-iv-random">New random IV</button>
</div>
<input id="aes-iv" class="tb-input tb-mono" placeholder="Empty: a random one each time you encrypt" autocomplete="off" spellcheck="false" />
<p class="tb-hint" id="aes-iv-hint"></p>
</div>
<div id="aes-aad-field" hidden>
<label for="aes-aad" class="tb-label">Associated data (optional)</label>
<input id="aes-aad" class="tb-input" placeholder="Authenticated, not encrypted" autocomplete="off" spellcheck="false" />
</div>

<div class="tb-seg w-fit" role="radiogroup" aria-label="Direction">
<label><input type="radio" name="aes-dir" value="encrypt" checked /><span>Encrypt</span></label>
<label><input type="radio" name="aes-dir" value="decrypt" /><span>Decrypt</span></label>
</div>

<form class="grid gap-4" id="aes-form">
<div>
<div class="flex items-end justify-between gap-3">
<label for="aes-input" class="tb-label" id="aes-input-label">Plaintext</label>
<select id="aes-input-format" class="tb-select mb-1.5 w-auto" aria-label="Input format">
<option value="text">Text</option>
<option value="hex">Hex</option>
<option value="base64">Base64</option>
</select>
</div>
<textarea id="aes-input" class="tb-textarea" rows="4" spellcheck="false">Attack at dawn.</textarea>
</div>
<div class="flex flex-wrap items-center gap-3">
<button type="submit" class="tb-btn" id="aes-go">Encrypt</button>
<div class="flex items-center gap-2">
<label for="aes-output-format" class="text-xs text-subtle">Output as</label>
<select id="aes-output-format" class="tb-select w-auto">
<option value="hex">Hex</option>
<option value="base64">Base64</option>
</select>
</div>
</div>
<p class="tb-error" id="aes-error" hidden></p>
<div id="aes-result" hidden>
<div class="tb-panel overflow-hidden" id="aes-rows"></div>
<button type="button" class="tb-btn tb-btn-ghost tb-btn-sm mt-3" id="aes-swap">Try decrypting it</button>
</div>
</form>
</div>

<script>
import { $, $$, call, radio, renderRows, showError } from '../../lib/toolbox-client';

const root = document.getElementById('tb-aes')!;
const el = <T extends HTMLElement = HTMLInputElement>(id: string) => $<T>(root, `#${id}`);
const mode = () => el<HTMLSelectElement>('aes-mode').value;
const dir = () => radio(root, 'aes-dir');

const ABOUT: Record<string, string> = {
cbc: 'The most common mode in older systems. Needs a random IV for every message and padding to whole blocks.',
ctr: 'Turns AES into a stream cipher: no padding, and encrypt and decrypt are the same. Never reuse a counter with the same key.',
ecb: 'Encrypts each block on its own, so equal blocks give equal ciphertext and patterns show through. Only for compatibility.',
cfb: 'A stream mode that feeds back the previous ciphertext block. No padding needed.',
cfb8: 'CFB one byte at a time, as some older protocols use. No padding needed.',
ofb: 'A stream mode whose keystream does not depend on the data. No padding needed.',
ccm: 'Counter mode plus a CBC-MAC tag, as used in Wi-Fi (WPA2) and Bluetooth. Detects tampering.',
xts: 'For disk and storage encryption: the tweak is usually the sector number. Takes two AES keys joined together, and at least 16 bytes of data.',
pcbc: 'A CBC variant where an error spreads to every later block. Used by Kerberos v4.',
ige: 'Infinite Garble Extension, used by Telegram’s MTProto. Takes a 32-byte IV.',
};
const usesPadding = (m: string) => ['ecb', 'cbc', 'pcbc', 'ige'].includes(m);
const ivBytes = (m: string) => (m === 'ecb' ? 0 : m === 'ccm' ? 13 : m === 'ige' ? 32 : 16);
const keyBytes = (m: string) => (m === 'xts' ? 64 : 32);

const random = async (n: number) => {
const r = await call('random', { length: n, format: 'hex' });
return r.ok ? (r.value as string) : '';
};
const newKey = async () => (el('aes-key').value = await random(keyBytes(mode())));
el('aes-key-random').addEventListener('click', newKey);
el('aes-iv-random').addEventListener('click', async () => (el('aes-iv').value = await random(ivBytes(mode()))));

const refresh = () => {
const m = mode();
const what = m === 'ccm' ? 'Nonce' : m === 'xts' ? 'Tweak' : 'IV';
el('aes-about').textContent = ABOUT[m];
el('aes-padding-field').hidden = !usesPadding(m);
el('aes-tag-field').hidden = m !== 'ccm';
el('aes-aad-field').hidden = m !== 'ccm';
el('aes-iv-field').hidden = m === 'ecb';
el('aes-iv-label').textContent = `${what} (hex)`;
el('aes-iv-random').textContent = `New random ${what.toLowerCase()}`;
el('aes-iv-hint').textContent =
m === 'ccm' ? '7 to 13 bytes; 13 is common. Never reuse a nonce with the same key.' : m === 'ige' ? '32 bytes.' : m === 'xts' ? '16 bytes, often the sector number.' : '16 bytes.';
el('aes-key-hint').textContent = m === 'xts' ? '32, 48 or 64 bytes: two AES keys joined (64 bytes for AES-256-XTS).' : '16, 24 or 32 bytes for AES-128, AES-192 or AES-256.';
const key = el('aes-key').value.replace(/\s/g, '');
const xtsKey = [64, 96, 128].includes(key.length);
if (key && (m === 'xts') !== xtsKey) void newKey();
const iv = el('aes-iv').value.replace(/\s/g, '');
if (iv && iv.length !== ivBytes(m) * 2 && !(m === 'ccm' && iv.length >= 14 && iv.length <= 26)) el('aes-iv').value = '';
el('aes-result').hidden = true;
};
el('aes-mode').addEventListener('change', refresh);

const direction = (d: string) => {
for (const r of $$<HTMLInputElement>(root, 'input[name="aes-dir"]')) r.checked = r.value === d;
el('aes-go').textContent = d === 'encrypt' ? 'Encrypt' : 'Decrypt';
el('aes-input-label').textContent = d === 'encrypt' ? 'Plaintext' : 'Ciphertext';
el('aes-swap').hidden = d === 'decrypt';
const fmt = el<HTMLSelectElement>('aes-input-format');
if (d === 'decrypt' && fmt.value === 'text') fmt.value = 'hex';
el('aes-result').hidden = true;
showError(el('aes-error'), null);
};
for (const r of $$<HTMLInputElement>(root, 'input[name="aes-dir"]')) r.addEventListener('change', () => direction(r.value));

let last: { value: string; iv?: string; format: string } | null = null;
el('aes-form').addEventListener('submit', async (e) => {
e.preventDefault();
const outFormat = el<HTMLSelectElement>('aes-output-format').value;
const r = await call('aes', {
mode: mode(),
direction: dir(),
key: el('aes-key').value,
iv: el('aes-iv').value,
padding: el<HTMLSelectElement>('aes-padding').value,
tagSize: Number(el<HTMLSelectElement>('aes-tag').value),
aad: el('aes-aad').value,
input: el<HTMLTextAreaElement>('aes-input').value,
inputFormat: el<HTMLSelectElement>('aes-input-format').value,
outputFormat: outFormat,
});
showError(el('aes-error'), r.ok ? null : r.error);
el('aes-result').hidden = !r.ok;
if (!r.ok) return;
const rows: { name: string; value: string | null; note?: string }[] = [];
if (dir() === 'encrypt') {
rows.push({ name: mode() === 'ccm' ? 'Ciphertext ‖ tag' : 'Ciphertext', value: r.value });
if (r.iv) rows.push({ name: mode() === 'ccm' ? 'Nonce' : mode() === 'xts' ? 'Tweak' : 'IV', value: r.iv });
last = { value: r.value, iv: r.iv, format: outFormat };
} else {
rows.push({ name: 'Plaintext', value: r.text, note: 'Not valid UTF-8 text; see the bytes below.' });
rows.push({ name: `Plaintext (${outFormat})`, value: r.value });
}
renderRows(el('aes-rows'), rows);
});
el('aes-swap').addEventListener('click', () => {
if (!last) return;
if (last.iv) el('aes-iv').value = last.iv;
el<HTMLTextAreaElement>('aes-input').value = last.value;
direction('decrypt');
el<HTMLSelectElement>('aes-input-format').value = last.format;
});

refresh();
void newKey();
</script>
3 changes: 3 additions & 0 deletions src/components/toolbox/Codec.astro
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ const LABELS: Record<string, string> = {
base62: 'Base62',
base36: 'Base36',
base45: 'Base45',
percent: 'Percent-encoded (RFC 3986)',
'percent-component': 'Like encodeURIComponent',
'percent-form': 'Form data (space as +)',
};
---

Expand Down
17 changes: 15 additions & 2 deletions src/components/toolbox/Hash.astro
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ const { ids, common } = Astro.props;

<p class="tb-error mt-4" id="hash-error" hidden></p>
<div class="tb-panel mt-3 overflow-hidden" id="hash-results"></div>
<button type="button" class="tb-btn tb-btn-ghost tb-btn-sm mt-3" id="hash-more" hidden>Show all algorithms</button>
<div class="mt-3 flex flex-wrap items-center justify-between gap-3">
<button type="button" class="tb-btn tb-btn-ghost tb-btn-sm" id="hash-more" hidden>Show all algorithms</button>
<div class="flex items-center gap-2" id="hash-shake" hidden>
<label for="hash-shake-bits" class="text-xs text-subtle">SHAKE output (bits)</label>
<input id="hash-shake-bits" class="tb-input w-28" type="number" min="8" max="8192" step="8" placeholder="256 / 512" />
</div>
</div>
</div>

<script>
Expand All @@ -67,12 +73,18 @@ const { ids, common } = Astro.props;
let file: { name: string; base64: string; size: number } | null = null;
const fresh = latest();

const shake = $(root, '#hash-shake');
const shakeBits = $<HTMLInputElement>(root, '#hash-shake-bits');
const hasShake = ids.some((id) => id.startsWith('shake'));
more.hidden = showAll;
shake.hidden = !(showAll && hasShake);
more.addEventListener('click', () => {
showAll = true;
more.hidden = true;
shake.hidden = !hasShake;
update(true);
});
shakeBits.addEventListener('input', () => update());

const mode = () => radio(root, 'hash-mode');

Expand All @@ -89,7 +101,8 @@ const { ids, common } = Astro.props;
showError(error, null);
return;
}
const r = await call('hash', { ...args, algorithms, outputFormat: radio(root, 'hash-out') });
const shakeArg = showAll && hasShake && shakeBits.value ? { shakeBits: Number(shakeBits.value) } : {};
const r = await call('hash', { ...args, ...shakeArg, algorithms, outputFormat: radio(root, 'hash-out') });
if (!isLatest()) return;
showError(error, r.ok ? null : r.error);
results.hidden = !r.ok;
Expand Down
36 changes: 32 additions & 4 deletions src/components/toolbox/Hmac.astro
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
// HMAC with any cryptographic hash, or BLAKE2 in its own keyed mode.
const algorithms = [
['sha256', 'SHA-256'],
['sha512', 'SHA-512'],
Expand All @@ -13,6 +14,16 @@ const algorithms = [
['sha1', 'SHA-1'],
['md5', 'MD5'],
];
const blake2 = [
['blake2b:512', 'BLAKE2b-512'],
['blake2b:384', 'BLAKE2b-384'],
['blake2b:256', 'BLAKE2b-256'],
['blake2b:160', 'BLAKE2b-160'],
['blake2s:256', 'BLAKE2s-256'],
['blake2s:224', 'BLAKE2s-224'],
['blake2s:160', 'BLAKE2s-160'],
['blake2s:128', 'BLAKE2s-128'],
];
const formats = [
['text', 'Text'],
['hex', 'Hex'],
Expand All @@ -21,10 +32,15 @@ const formats = [
---

<div id="tb-hmac" class="grid gap-5">
<div class="tb-seg w-fit" role="radiogroup" aria-label="Kind">
<label><input type="radio" name="hmac-kind" value="hmac" checked /><span>HMAC</span></label>
<label><input type="radio" name="hmac-kind" value="blake2" /><span>Keyed BLAKE2</span></label>
</div>
<div class="grid gap-4 sm:grid-cols-[1fr_auto]">
<div>
<label for="hmac-key" class="tb-label">Secret key</label>
<input id="hmac-key" class="tb-input tb-mono" value="key" spellcheck="false" autocomplete="off" />
<p class="tb-hint" id="hmac-key-hint" hidden>1 to 64 bytes for BLAKE2b, 1 to 32 for BLAKE2s.</p>
</div>
<div>
<label for="hmac-key-format" class="tb-label">Key as</label>
Expand All @@ -39,10 +55,14 @@ const formats = [
<textarea id="hmac-message" class="tb-textarea" rows="4" spellcheck="false">The quick brown fox jumps over the lazy dog</textarea>
</div>
<div class="flex flex-wrap items-end gap-4">
<div>
<div data-kind="hmac">
<label for="hmac-algorithm" class="tb-label">Hash</label>
<select id="hmac-algorithm" class="tb-select w-auto">{algorithms.map(([v, l]) => <option value={v}>{l}</option>)}</select>
</div>
<div data-kind="blake2" hidden>
<label for="hmac-blake2" class="tb-label">BLAKE2</label>
<select id="hmac-blake2" class="tb-select w-auto">{blake2.map(([v, l]) => <option value={v}>{l}</option>)}</select>
</div>
<div class="tb-seg" role="radiogroup" aria-label="Output format">
<label><input type="radio" name="hmac-out" value="hex" checked /><span>hex</span></label>
<label><input type="radio" name="hmac-out" value="base64" /><span>Base64</span></label>
Expand All @@ -58,22 +78,30 @@ const formats = [

const root = document.getElementById('tb-hmac')!;
const v = (id: string) => $<HTMLInputElement>(root, `#${id}`).value;
const kind = () => radio(root, 'hmac-kind');
const fresh = latest();
const update = live(async () => {
const isLatest = fresh();
const r = await call('hmac', {
const common = {
key: v('hmac-key'),
keyFormat: v('hmac-key-format'),
message: v('hmac-message'),
messageFormat: v('hmac-message-format'),
algorithm: v('hmac-algorithm'),
outputFormat: radio(root, 'hmac-out'),
});
};
const [variant, bits] = v('hmac-blake2').split(':');
const r = kind() === 'hmac' ? await call('hmac', { ...common, algorithm: v('hmac-algorithm') }) : await call('blake2mac', { ...common, variant, bits: Number(bits) });
if (!isLatest()) return;
showError($(root, '#hmac-error'), r.ok ? null : r.error);
$(root, '#hmac-result').hidden = !r.ok;
if (r.ok) renderRows($(root, '#hmac-result'), [{ name: r.name, value: r.value }]);
});
for (const el of $$<HTMLInputElement>(root, 'input[name="hmac-kind"]')) {
el.addEventListener('change', () => {
for (const p of $$(root, '[data-kind]')) p.hidden = p.dataset.kind !== kind();
$(root, '#hmac-key-hint').hidden = kind() !== 'blake2';
});
}
for (const el of $$(root, 'input, textarea, select')) {
el.addEventListener(el.tagName === 'SELECT' || (el as HTMLInputElement).type === 'radio' ? 'change' : 'input', () => update());
}
Expand Down
Loading