Files
devbox/js/tools-codec-extra.js
gitea 80ecd02bfa 补 14 个工具:格式 / 编码 / 加密 / 图片 / 文本 / 时间
- 新分组「格式」:JSON ↔ YAML、XML ↔ JSON、SQL 美化、JSON ↔ 查询串
- 编码:Gzip 压缩 + CRC32、Cookie ↔ JSON、字符编码套件(Unicode/UTF-8/HEX/全角/罗马/摩斯)
- 加密:RSA 密钥对生成、私钥签名、公钥验签(WebCrypto)
- 图片:压缩、九宫格切图、EXIF 读取
- 文本:提取器(手机号/邮箱/链接/身份证/IP/卡号)、人民币与日期大写
- 时间:番茄钟 / 秒表 / 倒计时
- README 工具数 30 → 44
2026-11-20 14:22:23 +08:00

183 lines
9.8 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* DevBox · 编码补齐:Gzip / CRC32、Cookie ↔ JSON、字符编码套件 */
(function () {
'use strict'
const { el, panelTitle, copy, toast, onInput, downloadText } = DB
const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
const ta = (ph, rows) => el('textarea', { class: 'ta', placeholder: ph, rows: rows || 10, spellcheck: 'false' })
/* ---------------- Gzip + CRC32 ---------------- */
const enc = (t) => new TextEncoder().encode(t)
const dec = (b) => new TextDecoder().decode(b)
const b64 = (bytes) => btoa(String.fromCharCode(...bytes))
const unb64 = (s) => Uint8Array.from(atob(s.replace(/\s/g, '')), (c) => c.charCodeAt(0))
const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
const CRC_TABLE = (() => {
const t = new Uint32Array(256)
for (let i = 0; i < 256; i++) {
let c = i
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
t[i] = c >>> 0
}
return t
})()
function crc32(bytes) {
let c = 0xffffffff
for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8)
return ((c ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0')
}
async function gzip(bytes) {
const cs = new CompressionStream('gzip')
const w = cs.writable.getWriter(); w.write(bytes); w.close()
return new Uint8Array(await new Response(cs.readable).arrayBuffer())
}
async function gunzip(bytes) {
const ds = new DecompressionStream('gzip')
const w = ds.writable.getWriter(); w.write(bytes); w.close()
return new Uint8Array(await new Response(ds.readable).arrayBuffer())
}
DB.tool({
id: 'gzip-crc',
name: 'Gzip 压缩 / CRC32',
group: 'encode',
icon: 'archive',
desc: '文本压成 Gzip(Base64 / HEX 两种输出),顺带算 CRC32;也能解回来',
keywords: ['gzip', 'zlib', 'crc32', '压缩', '解压', '校验'],
mount(root) {
const src = ta('要压缩的文本,或者粘 Base64 / HEX 来解压…')
const out = el('pre', { class: 'out' })
const stat = el('div', { class: 'hint' })
const pack = async (fmt) => {
try {
const raw = enc(src.value)
const gz = await gzip(raw)
out.textContent = (fmt === 'hex' ? hex(gz) : b64(gz)) + '\n\nCRC32: ' + crc32(raw) + '\n原始: ' + raw.length + ' B → 压缩: ' + gz.length + ' B (' + (gz.length / Math.max(1, raw.length) * 100).toFixed(1) + '%)'
stat.textContent = '压缩完成'; stat.className = 'hint good'
} catch (e) { stat.textContent = '失败:' + e.message; stat.className = 'hint bad' }
}
const unpack = async () => {
try {
const t = src.value.trim()
const bytes = /^[0-9a-fA-F\s]+$/.test(t) && t.replace(/\s/g, '').length % 2 === 0 ? Uint8Array.from(t.replace(/\s/g, '').match(/../g), (h) => parseInt(h, 16)) : unb64(t)
const raw = await gunzip(bytes)
out.textContent = dec(raw)
stat.textContent = '解压完成,' + raw.length + ' B'; stat.className = 'hint good'
} catch (e) { stat.textContent = '解压失败:' + e.message; stat.className = 'hint bad' }
}
root.append(
pane('压缩 / 解压', el('div', { class: 'row' }, btn('Gzip → Base64', () => pack('b64')), btn('Gzip → HEX', () => pack('hex')), btn('解压', unpack), btn('只看 CRC32', () => { out.textContent = crc32(enc(src.value)) }, 'ghost'))),
src, stat, out
)
},
})
/* ---------------- Cookie ↔ JSON ---------------- */
DB.tool({
id: 'cookie-json',
name: 'Cookie ↔ JSON',
group: 'encode',
icon: 'cookie',
desc: 'Cookie 串与 JSON 互转,带过期时间、路径、SameSite 也能解析',
keywords: ['cookie', 'json', 'header', '会话', '转换'],
mount(root) {
const src = ta('session=abc123; theme=dark; lang=zh-CN', 8)
const out = el('pre', { class: 'out' })
const toJson = () => {
const list = []
let cur = null
for (const part of src.value.split(';')) {
const seg = part.trim()
if (!seg) continue
const i = seg.indexOf('=')
if (i < 0) continue
const k = seg.slice(0, i).trim(), v = seg.slice(i + 1).trim()
if (/^(path|domain|expires|max-age|samesite|secure|httponly)$/i.test(k)) {
if (cur) cur[k.toLowerCase()] = v || true
continue
}
cur = { name: k, value: decodeURIComponent(v) }
list.push(cur)
}
out.textContent = JSON.stringify(list, null, 2)
}
const toCookie = () => {
try {
const v = JSON.parse(src.value)
const arr = Array.isArray(v) ? v : Object.entries(v).map(([name, value]) => ({ name, value }))
out.textContent = arr.map((c) => `${c.name}=${encodeURIComponent(c.value ?? '')}${c.path ? '; Path=' + c.path : ''}${c.domain ? '; Domain=' + c.domain : ''}${c.expires ? '; Expires=' + c.expires : ''}${c.secure ? '; Secure' : ''}${c.httpOnly ? '; HttpOnly' : ''}${c.sameSite ? '; SameSite=' + c.sameSite : ''}`).join('; ')
} catch (e) { out.textContent = 'JSON 解析失败:' + e.message }
}
root.append(pane('转换', el('div', { class: 'row' }, btn('Cookie → JSON', toJson), btn('JSON → Cookie', toCookie), btn('复制当前页面 Cookie', () => { src.value = document.cookie || '(当前域名没有 Cookie)'; toJson() }, 'ghost'))), src, out)
toJson()
},
})
/* ---------------- 字符编码套件 ---------------- */
const ROMAN = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]
const toRoman = (n) => { let r = ''; for (const [v, s] of ROMAN) while (n >= v) { r += s; n -= v } return r }
const fromRoman = (s) => { let i = 0, n = 0; const map = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }; const u = s.toUpperCase().replace(/[^IVXLCDM]/g, ''); while (i < u.length) { const a = map[u[i]], b = map[u[i + 1]]; if (b && a < b) { n += b - a; i += 2 } else { n += a; i++ } } return n }
const MORSE = { a: '.-', b: '-...', c: '-.-.', d: '-..', e: '.', f: '..-.', g: '--.', h: '....', i: '..', j: '.---', k: '-.-', l: '.-..', m: '--', n: '-.', o: '---', p: '.--.', q: '--.-', r: '.-.', s: '...', t: '-', u: '..-', v: '...-', w: '.--', x: '-..-', y: '-.--', z: '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '.': '.-.-.-', ',': '--..--', '?': '..--..', '!': '-.-.--', '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '@': '.--.-.' }
const MORSE_REV = Object.fromEntries(Object.entries(MORSE).map(([k, v]) => [v, k]))
DB.tool({
id: 'char-codec',
name: '字符编码套件',
group: 'encode',
icon: 'type',
desc: 'Unicode 转义、UTF-8 字节、HEX、全角半角、罗马数字、摩斯密码,六种一次装齐',
keywords: ['unicode', 'utf8', 'hex', 'fullwidth', 'roman', 'morse', '摩斯', '罗马', '全角'],
mount(root) {
const mode = el('select', { class: 'input' }, ...[
['unicode', 'Unicode 转义'], ['utf8', 'UTF-8 字节'], ['hex', 'HEX ↔ 文本'], ['width', '全角 ↔ 半角'], ['roman', '阿拉伯 ↔ 罗马数字'], ['morse', '摩斯密码'],
].map(([v, t]) => el('option', { value: v, text: t })))
const src = ta('输入文本…', 8)
const out = el('pre', { class: 'out' })
const go = (reverse) => {
const v = src.value
try {
let r = ''
switch (mode.value) {
case 'unicode':
r = reverse ? v.replace(/\\u\{?([0-9a-fA-F]{2,6})\}?/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
: Array.from(v).map((c) => (c.codePointAt(0) > 0xffff ? '\\u{' + c.codePointAt(0).toString(16).toUpperCase() + '}' : '\\u' + c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0'))).join('')
break
case 'utf8':
r = reverse ? dec(Uint8Array.from(v.trim().split(/[\s,]+/).map((x) => parseInt(x, 16))))
: Array.from(enc(v), (b) => b.toString(16).toUpperCase().padStart(2, '0')).join(' ')
break
case 'hex':
r = reverse ? Array.from(v.trim().match(/.{1,2}/g) || [], (h) => parseInt(h, 16)).map((b) => String.fromCharCode(b)).join('')
: Array.from(enc(v), (b) => b.toString(16).padStart(2, '0')).join('')
break
case 'width':
r = Array.from(v, (c) => {
const code = c.charCodeAt(0)
if (reverse && code >= 0xff01 && code <= 0xff5e) return String.fromCharCode(code - 0xfee0)
if (reverse && code === 0x3000) return ' '
if (!reverse && code === 0x20) return ' '
if (!reverse && code >= 0x21 && code <= 0x7e) return String.fromCharCode(code + 0xfee0)
return c
}).join('')
break
case 'roman':
r = reverse ? String(fromRoman(v)) : toRoman(Number(v.trim()) || 0)
break
case 'morse':
r = reverse ? v.trim().split(/\s*\/\s*|\s{2,}/).map((w) => w.trim().split(/\s+/).map((m) => MORSE_REV[m] || '').join('')).join(' ')
: v.toLowerCase().split('').map((c) => c === ' ' ? '/' : (MORSE[c] || c)).join(' ')
break
}
out.textContent = r
} catch (e) { out.textContent = '转换失败:' + e.message }
}
root.append(
pane('模式', el('div', { class: 'row' }, mode, btn('→ 编码', () => go(false)), btn('← 解码', () => go(true)))),
src, out
)
onInput(src, () => go(false), 300)
},
})
})()