381 lines
20 KiB
JavaScript
381 lines
20 KiB
JavaScript
/* DevBox · 加密工具:哈希 / AES / JWT / 随机生成 */
|
||
(function () {
|
||
'use strict'
|
||
const { el, panelTitle, output, copy, toast, onInput } = DB
|
||
const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
|
||
const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
|
||
const field = (label, control) => el('label', { class: 'field' }, el('span', { text: label }), control)
|
||
|
||
const enc = new TextEncoder()
|
||
const b64 = (buf) => btoa(String.fromCharCode.apply(null, new Uint8Array(buf)))
|
||
const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
|
||
const hexOf = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
||
const subtle = window.crypto && window.crypto.subtle
|
||
|
||
/* ================= 哈希 ================= */
|
||
DB.tool({
|
||
id: 'hash',
|
||
name: '哈希 / HMAC',
|
||
group: 'crypto',
|
||
icon: 'hash',
|
||
desc: 'SHA-1 / 256 / 384 / 512,支持文件、HMAC 与结果比对',
|
||
keywords: ['hash', 'sha256', 'sha1', 'md5', 'hmac', 'checksum', '哈希', '摘要', '校验'],
|
||
mount(root) {
|
||
const input = el('textarea', { rows: 5, placeholder: '要计算哈希的文本…', spellcheck: 'false' })
|
||
const fileInput = el('input', { type: 'file', multiple: true, hidden: true })
|
||
const keyInput = el('input', { type: 'text', placeholder: 'HMAC 密钥(留空则算普通哈希)' })
|
||
const upper = el('input', { type: 'checkbox', id: 'hashUpper' })
|
||
const algos = {}
|
||
const algoHost = el('div', { class: 'row' })
|
||
for (const a of ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512']) {
|
||
const box = el('input', { type: 'checkbox', checked: a === 'SHA-256' })
|
||
algos[a] = box
|
||
algoHost.append(el('label', { class: 'check' }, box, el('span', { text: a })))
|
||
}
|
||
const out = el('div', { class: 'files' })
|
||
const status = el('div', { class: 'hint' })
|
||
const expected = el('input', { type: 'text', placeholder: '粘贴别人给的哈希,自动比对', style: { fontFamily: 'var(--mono)' } })
|
||
const verdict = el('div', { class: 'hint' })
|
||
let lastHashes = []
|
||
|
||
const compare = () => {
|
||
const want = expected.value.trim().toLowerCase()
|
||
verdict.textContent = ''
|
||
verdict.className = 'hint'
|
||
if (!want) return
|
||
if (!lastHashes.length) { verdict.textContent = '先算出结果,才能比对。'; return }
|
||
const hit = lastHashes.find((h) => h.toLowerCase() === want)
|
||
if (hit) { verdict.className = 'hint good'; verdict.textContent = '✓ 和结果一致,文件没被动过。' }
|
||
else { verdict.className = 'hint bad'; verdict.textContent = '✗ 对不上:预期与当前内容的摘要不同。' }
|
||
}
|
||
const compute = async (data) => {
|
||
out.textContent = ''
|
||
status.textContent = ''
|
||
lastHashes = []
|
||
if (!input.value.trim() && !keyInput.value) {
|
||
status.textContent = '输入文字,或点「选文件算 SHA-256」。结果会自动比对下面粘贴的哈希。'
|
||
compare()
|
||
return
|
||
}
|
||
const names = Object.keys(algos).filter((a) => algos[a].checked)
|
||
if (!names.length) { status.textContent = '至少勾一个算法'; return }
|
||
if (!subtle) { status.textContent = '当前浏览器不支持 Web Crypto(需要 https 或 localhost)'; return }
|
||
for (const name of names) {
|
||
let buf
|
||
if (keyInput.value) {
|
||
const key = await subtle.importKey('raw', enc.encode(keyInput.value), { name: 'HMAC', hash: name }, false, ['sign'])
|
||
buf = await subtle.sign('HMAC', key, data)
|
||
} else {
|
||
buf = await subtle.digest(name, data)
|
||
}
|
||
let hex = hexOf(buf)
|
||
if (upper.checked) hex = hex.toUpperCase()
|
||
lastHashes.push(hex)
|
||
const row = el('div', { class: 'file-row', style: { gridTemplateColumns: '1fr auto' } },
|
||
el('div', { class: 'file-meta' }, el('b', { text: (keyInput.value ? 'HMAC-' : '') + name }), el('span', { text: hex })))
|
||
row.append(el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(hex) }))
|
||
out.append(row)
|
||
}
|
||
compare()
|
||
}
|
||
|
||
const runText = () => compute(enc.encode(input.value))
|
||
const runFiles = async (files) => {
|
||
out.textContent = ''
|
||
for (const f of [...files].slice(0, 5)) {
|
||
status.textContent = '正在算 ' + f.name + '(' + DB.bytes(f.size) + ')…'
|
||
const buf = await f.arrayBuffer()
|
||
const digest = await subtle.digest('SHA-256', buf)
|
||
const hex = (upper.checked ? hexOf(digest) : hexOf(digest)).toUpperCase() === '' ? '' : hexOf(digest)
|
||
const row = el('div', { class: 'file-row', style: { gridTemplateColumns: '1fr auto' } },
|
||
el('div', { class: 'file-meta' }, el('b', { text: f.name }), el('span', { text: 'SHA-256 · ' + hex })))
|
||
row.append(el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(hex) }))
|
||
out.append(row)
|
||
}
|
||
status.textContent = files.length > 5 ? '一次最多算 5 个文件' : ''
|
||
compare()
|
||
}
|
||
|
||
onInput(input, runText, 220)
|
||
keyInput.addEventListener('input', DB.debounce(runText, 220))
|
||
upper.addEventListener('change', runText)
|
||
expected.addEventListener('input', compare)
|
||
algoHost.addEventListener('change', runText)
|
||
fileInput.addEventListener('change', () => runFiles(fileInput.files))
|
||
|
||
const p1 = pane('文本')
|
||
p1.append(input, el('div', { class: 'grid2', style: { marginTop: '10px' } }, field('HMAC 密钥(可选)', keyInput),
|
||
el('div', { class: 'row', style: { alignItems: 'flex-end', paddingBottom: '6px' } },
|
||
el('label', { class: 'check' }, upper, el('span', { text: '大写输出' })),
|
||
btn('选文件算 SHA-256', () => fileInput.click()), fileInput, btn('清空', () => { input.value = ''; out.textContent = '' }))))
|
||
const p2 = pane('算法')
|
||
p2.append(algoHost)
|
||
const p3 = pane('结果')
|
||
p3.append(status, out,
|
||
el('div', { style: { marginTop: '14px' } },
|
||
el('label', { class: 'field' }, el('span', { text: '比对(可选)' }), expected),
|
||
verdict))
|
||
root.append(p1, p2, p3)
|
||
runText()
|
||
},
|
||
})
|
||
|
||
/* ================= AES ================= */
|
||
DB.tool({
|
||
id: 'aes',
|
||
name: 'AES 加解密',
|
||
group: 'crypto',
|
||
icon: 'lock',
|
||
desc: 'AES-GCM + PBKDF2 口令派生,输出一段可粘贴的密文包',
|
||
keywords: ['aes', 'gcm', 'encrypt', 'decrypt', '加密', '解密', '对称'],
|
||
mount(root) {
|
||
const plain = el('textarea', { rows: 6, placeholder: '要加密的文本,或粘贴一段密文包…', spellcheck: 'false' })
|
||
const pass = el('input', { type: 'password', placeholder: '口令(越长约好,别忘了)' })
|
||
const show = el('input', { type: 'checkbox' })
|
||
const out = output()
|
||
const err = el('div', { class: 'err' })
|
||
const status = el('div', { class: 'hint' })
|
||
const iterations = 200000
|
||
|
||
const derive = async (password, salt) => {
|
||
const base = await subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveKey'])
|
||
return subtle.deriveKey({ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
||
}
|
||
|
||
const encrypt = async () => {
|
||
err.textContent = ''
|
||
try {
|
||
if (!pass.value) throw new Error('先输入口令')
|
||
const salt = crypto.getRandomValues(new Uint8Array(16))
|
||
const iv = crypto.getRandomValues(new Uint8Array(12))
|
||
const key = await derive(pass.value, salt)
|
||
const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, enc.encode(plain.value))
|
||
const packet = { v: 1, alg: 'AES-GCM', kdf: 'PBKDF2-SHA256', iter: iterations, salt: b64(salt), iv: b64(iv), data: b64(ct) }
|
||
out.set(JSON.stringify(packet))
|
||
status.textContent = '加密完成:把这一段整体发给对方,口令用另一个渠道告诉对方。'
|
||
} catch (e) { err.textContent = '加密失败:' + e.message }
|
||
}
|
||
|
||
const decrypt = async () => {
|
||
err.textContent = ''
|
||
try {
|
||
if (!pass.value) throw new Error('先输入口令')
|
||
const packet = JSON.parse(plain.value)
|
||
if (!packet.data || !packet.iv || !packet.salt) throw new Error('这段内容不是 DevBox 的密文包')
|
||
const key = await derive(pass.value, unb64(packet.salt))
|
||
const pt = await subtle.decrypt({ name: 'AES-GCM', iv: unb64(packet.iv) }, key, unb64(packet.data))
|
||
out.set(new TextDecoder().decode(pt))
|
||
status.textContent = '解密完成。'
|
||
} catch (e) {
|
||
err.textContent = '解密失败:' + (/JSON/.test(e.message) ? '这段不是密文包' : '口令不对,或者内容被改过')
|
||
}
|
||
}
|
||
|
||
show.addEventListener('change', () => { pass.type = show.checked ? 'text' : 'password' })
|
||
const p1 = pane('内容')
|
||
p1.append(plain)
|
||
const p2 = pane('口令')
|
||
p2.append(pass, el('div', { class: 'row', style: { marginTop: '8px' } },
|
||
el('label', { class: 'check' }, show, el('span', { text: '显示口令' })),
|
||
btn('加密', encrypt, 'primary'), btn('解密', decrypt), btn('生成强口令', () => { pass.value = randPassword(24); pass.type = 'text'; show.checked = true })))
|
||
|
||
function randPassword(n) {
|
||
const chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_=+'
|
||
const arr = crypto.getRandomValues(new Uint32Array(n))
|
||
return [...arr].map((v) => chars[v % chars.length]).join('')
|
||
}
|
||
const p3 = pane('输出')
|
||
p3.append(status, out.node, err)
|
||
root.append(p1, p2, p3)
|
||
p1.append(el('p', { class: 'note', text: `口令用 PBKDF2-SHA256 派生(${iterations.toLocaleString()} 次迭代),密文用 AES-256-GCM 认证加密。忘记口令无法找回。` }))
|
||
},
|
||
})
|
||
|
||
/* ================= JWT ================= */
|
||
DB.tool({
|
||
id: 'jwt',
|
||
name: 'JWT 解析',
|
||
group: 'crypto',
|
||
icon: 'key',
|
||
desc: '拆开 header / payload,标出过期时间,可用密钥验证 HS256 签名',
|
||
keywords: ['jwt', 'token', 'jws', 'bearer', '令牌', '签名'],
|
||
mount(root) {
|
||
const token = el('textarea', { rows: 5, placeholder: '粘贴 eyJhbGciOi⋯ 开头的 JWT', spellcheck: 'false', style: { wordBreak: 'break-all' } })
|
||
const secret = el('input', { type: 'text', placeholder: 'HS256 密钥(可选,用来验证签名)' })
|
||
const out = el('div', { class: 'stack' })
|
||
const err = el('div', { class: 'err' })
|
||
|
||
const b64urlDecode = (s) => {
|
||
const t = s.replace(/-/g, '+').replace(/_/g, '/')
|
||
const pad = t.length % 4 ? '='.repeat(4 - (t.length % 4)) : ''
|
||
const bin = atob(t + pad)
|
||
const u8 = new Uint8Array(bin.length)
|
||
for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i)
|
||
return new TextDecoder().decode(u8)
|
||
}
|
||
const timeRow = (k, v) => {
|
||
if (typeof v !== 'number') return null
|
||
const d = new Date(v * 1000)
|
||
const now = Date.now() / 1000
|
||
let tag = ''
|
||
if (k === 'exp') tag = v < now ? '(已过期)' : '(' + relTime(v - now) + '后过期)'
|
||
else if (k === 'nbf') tag = v > now ? '(还没生效)' : ''
|
||
else if (k === 'iat') tag = '(' + relTime(now - v) + '前签发)'
|
||
return [el('dt', { text: k }), el('dd', { text: d.toLocaleString('zh-CN') + ' ' + tag })]
|
||
}
|
||
const relTime = (sec) => {
|
||
const a = Math.abs(sec)
|
||
if (a < 60) return Math.round(a) + ' 秒'
|
||
if (a < 3600) return Math.round(a / 60) + ' 分钟'
|
||
if (a < 86400) return Math.round(a / 3600) + ' 小时'
|
||
return Math.round(a / 86400) + ' 天'
|
||
}
|
||
|
||
const verify = async (parts, alg) => {
|
||
if (!secret.value || !subtle) return null
|
||
try {
|
||
if (!/^HS(256|384|512)$/.test(alg)) return { ok: null, msg: '只支持验证 HS256/384/512' }
|
||
const key = await subtle.importKey('raw', enc.encode(secret.value), { name: 'HMAC', hash: alg.replace('HS', 'SHA-') }, false, ['verify'])
|
||
const data = enc.encode(parts[0] + '.' + parts[1])
|
||
const sig = unb64(parts[2].replace(/-/g, '+').replace(/_/g, '/'))
|
||
const ok = await subtle.verify('HMAC', key, sig, data)
|
||
return { ok, msg: ok ? '签名有效' : '签名不匹配' }
|
||
} catch (e) { return { ok: false, msg: '验证出错:' + e.message } }
|
||
}
|
||
|
||
const run = async () => {
|
||
out.textContent = ''
|
||
err.textContent = ''
|
||
const raw = token.value.trim().replace(/^Bearer\s+/i, '')
|
||
if (!raw) return
|
||
const parts = raw.split('.')
|
||
if (parts.length < 2) { err.textContent = '这不像 JWT:至少要 header.payload 两段'; return }
|
||
let header, payload
|
||
try { header = JSON.parse(b64urlDecode(parts[0])) } catch { err.textContent = 'header 不是合法 JSON'; return }
|
||
try { payload = JSON.parse(b64urlDecode(parts[1])) } catch { err.textContent = 'payload 不是合法 JSON'; return }
|
||
|
||
const h = pane('Header')
|
||
h.append(el('pre', { class: 'out flush', text: JSON.stringify(header, null, 2) }))
|
||
out.append(h)
|
||
|
||
const p = pane('Payload')
|
||
p.append(el('pre', { class: 'out flush', text: JSON.stringify(payload, null, 2) }))
|
||
out.append(p)
|
||
|
||
const claims = el('dl', { class: 'kv' })
|
||
;['iss', 'sub', 'aud', 'jti', 'scope'].forEach((k) => {
|
||
if (payload[k] !== undefined) claims.append(el('dt', { text: k }), el('dd', { text: String(payload[k]) }))
|
||
})
|
||
;['iat', 'nbf', 'exp'].forEach((k) => { const row = timeRow(k, payload[k]); if (row) claims.append(...row) })
|
||
const now = Date.now() / 1000
|
||
const state = payload.exp && payload.exp < now ? ['已过期', 'bad'] : payload.nbf && payload.nbf > now ? ['未生效', 'warn'] : ['有效期内', 'good']
|
||
const st = pane('状态')
|
||
st.append(el('div', { class: 'row' }, el('span', { class: 'chip', html: `<b class="${state[1]}">${state[0]}</b>` }),
|
||
el('span', { class: 'chip', text: '算法 ' + (header.alg || '—') })))
|
||
if (Object.keys(claims.childNodes).length) st.append(el('div', { style: { marginTop: '10px' } }, claims))
|
||
out.append(st)
|
||
|
||
if (secret.value) {
|
||
const v = await verify(parts, header.alg)
|
||
const box = pane('签名验证')
|
||
if (v) box.append(el('div', { class: 'out', text: v.msg }))
|
||
out.append(box)
|
||
}
|
||
if (parts[2]) out.append(el('div', { class: 'hint', text: '签名(Base64Url):' + parts[2].slice(0, 60) + '…' }))
|
||
}
|
||
onInput(token, run, 200)
|
||
onInput(secret, run, 300)
|
||
|
||
const p1 = pane('Token')
|
||
p1.append(token, el('div', { class: 'row', style: { marginTop: '10px' } }, field('密钥(可选)', secret), btn('示例', () => {
|
||
token.value = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMDAyIiwibmFtZSI6IumyqOmxv-WomSIsImlhdCI6MTcwMDAwMDAwMCwiZXhwIjoxOTAwMDAwMDAwfQ.3Xo6wSf2kZ7cK0nZk7wZ0m5Q8Y9kq0hQ3lT9Yx2rS4E'
|
||
run()
|
||
})))
|
||
root.append(p1, err, out)
|
||
run()
|
||
},
|
||
})
|
||
|
||
/* ================= 随机生成 ================= */
|
||
DB.tool({
|
||
id: 'random',
|
||
name: '密码 / UUID 生成',
|
||
group: 'crypto',
|
||
icon: 'shield',
|
||
desc: '强密码带熵值评估,还有 UUID v4、随机密钥与随机字符串',
|
||
keywords: ['password', 'uuid', 'random', 'nanoid', 'key', '密码', '随机', '密钥'],
|
||
mount(root) {
|
||
/* 密码 */
|
||
const len = el('input', { type: 'range', min: 6, max: 64, value: 20 })
|
||
const lenLabel = el('b', { text: '20' })
|
||
const boxes = {}
|
||
for (const [k, label, on] of [['lower', 'a-z', true], ['upper', 'A-Z', true], ['digit', '0-9', true], ['symbol', '!@#$%^&*', true], ['safe', '避开易混字符(0O1lI)', false]]) {
|
||
const box = el('input', { type: 'checkbox', checked: on })
|
||
boxes[k] = box
|
||
boxes[k].el = el('label', { class: 'check' }, box, el('span', { text: label }))
|
||
}
|
||
const passOut = el('input', { type: 'text', readonly: true, style: { fontFamily: 'var(--mono)', fontSize: '15px' } })
|
||
const strength = el('div', { class: 'hint' })
|
||
|
||
const gen = (n, useSafe) => {
|
||
let pool = ''
|
||
if (boxes.lower.checked) pool += 'abcdefghijklmnopqrstuvwxyz'
|
||
if (boxes.upper.checked) pool += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||
if (boxes.digit.checked) pool += '0123456789'
|
||
if (boxes.symbol.checked) pool += '!@#$%^&*()-_=+[]{};:,.?/'
|
||
if (useSafe) pool = pool.replace(/[0O1lI]/g, '')
|
||
if (!pool) pool = 'abcdefghijklmnopqrstuvwxyz'
|
||
const rnd = crypto.getRandomValues(new Uint32Array(n))
|
||
return [...rnd].map((v) => pool[v % pool.length]).join('')
|
||
}
|
||
const paintPass = () => {
|
||
lenLabel.textContent = len.value
|
||
const p = gen(Number(len.value), boxes.safe.checked)
|
||
passOut.value = p
|
||
const pool = 26 * boxes.lower.checked + 26 * boxes.upper.checked + 10 * boxes.digit.checked + 29 * boxes.symbol.checked
|
||
const bits = Math.log2(Math.max(pool, 2)) * Number(len.value)
|
||
const level = bits > 120 ? ['很强', 'good'] : bits > 80 ? ['够强', 'good'] : bits > 55 ? ['一般', 'warn'] : ['偏弱', 'bad']
|
||
strength.innerHTML = `熵约 <b>${bits.toFixed(0)}</b> 位 · <b class="${level[1]}">${level[0]}</b>`
|
||
}
|
||
len.addEventListener('input', paintPass)
|
||
Object.values(boxes).forEach((b) => b.addEventListener('change', paintPass))
|
||
passOut.addEventListener('focus', () => passOut.select())
|
||
|
||
const p1 = pane('密码生成器')
|
||
p1.append(el('div', { class: 'row between' }, el('span', { text: '长度' }), el('div', {}, el('span', { html: ' ' }), lenLabel)))
|
||
p1.append(len)
|
||
p1.append(el('div', { class: 'row', style: { margin: '8px 0' } }, ...Object.values(boxes).map((b) => b.el)))
|
||
p1.append(el('div', { class: 'row' }, passOut, el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(passOut.value) }), el('button', { class: 'btn tiny', text: '换一个', onclick: paintPass })))
|
||
p1.append(strength)
|
||
|
||
/* UUID */
|
||
const uuidOut = el('textarea', { rows: 5, readonly: true, style: { fontFamily: 'var(--mono)', fontSize: '13px' } })
|
||
const uuidCount = el('select', {}, ...[1, 5, 10, 50].map((n) => el('option', { value: n, text: n + ' 个' })))
|
||
const uuidGen = () => {
|
||
const n = Number(uuidCount.value)
|
||
uuidOut.value = Array.from({ length: n }, () => crypto.randomUUID()).join('\n')
|
||
}
|
||
const p2 = pane('UUID v4', el('div', { class: 'row' }, uuidCount, el('button', { class: 'btn tiny', text: '生成', onclick: uuidGen }), el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(uuidOut.value) })))
|
||
p2.querySelector('.row').prepend(el('span', { class: 'spacer' }))
|
||
p2.append(uuidOut)
|
||
|
||
/* 随机密钥与字符串 */
|
||
const keyLen = el('input', { type: 'number', value: 32, min: 8, max: 256 })
|
||
const keyOut = el('input', { type: 'text', readonly: true, style: { fontFamily: 'var(--mono)' } })
|
||
const keyGen = () => {
|
||
const n = Math.max(8, Math.min(256, Number(keyLen.value) || 32))
|
||
const hex = [...crypto.getRandomValues(new Uint8Array(n))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
||
keyOut.value = hex
|
||
}
|
||
const p3 = pane('随机密钥(hex)', el('div', { class: 'row' }, el('span', { text: '字节', style: { color: 'var(--dim-2)', fontSize: '12.5px' } }), el('div', { style: { width: '96px' } }, keyLen), el('button', { class: 'btn tiny', text: '生成', onclick: keyGen }), el('button', { class: 'btn tiny', text: '复制', onclick: () => copy(keyOut.value) })))
|
||
p3.querySelector('.row').prepend(el('span', { class: 'spacer' }))
|
||
p3.append(keyOut)
|
||
|
||
root.append(p1, p2, p3)
|
||
paintPass()
|
||
uuidGen()
|
||
keyGen()
|
||
},
|
||
})
|
||
})()
|