Appearance
实现 OtpTotp 工具
分类:developer | 标签:OTP、2FA、TOTP 基于 TOTP 的动态验证码生成
2.1 功能说明
基于 TOTP 的动态验证码生成
2.1.1 使用指南
功能说明
基于 RFC 6238 的 TOTP,使用共享密钥(Base32)与当前时间步长(默认 30 秒)生成 6 位动态验证码。纯浏览器本地计算,不上传密钥。
使用场景
2FA 调试、验证码核对、验证器接入测试。
2.2 代码实现
2.2.1 组件结构
本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-input、el-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。
2.2.2 核心逻辑概览
<script setup> 中定义的主要函数/方法:
b32decode()compute()tick()copy()
2.2.3 关键实现代码
以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。
vue
import { ref, onUnmounted } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'
const secret = ref('')
const digits = ref(6)
const period = ref(30)
const code = ref('')
const error = ref('')
const pct = ref(0)
const remain = ref(0)
let timer = null
function b32decode(s) {
const ALPH = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
s = s.replace(/=+$/, '').toUpperCase().replace(/\s/g, '')
let bits = '', bytes = []
for (const c of s) {
const v = ALPH.indexOf(c)
if (v < 0) throw new Error('包含非法 Base32 字符: ' + c)
bits += v.toString(2).padStart(5, '0')
}
for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8), 2))
return new Uint8Array(bytes)
}
async function compute() {
error.value = code.value = ''
const s = secret.value.trim().replace(/\s/g, '')
if (!s) return
let key
try { key = b32decode(s) } catch (e) { error.value = e.message; return }
const epoch = Math.floor(Date.now() / 1000)
const counter = Math.floor(epoch / period.value)
remain.value = period.value - (epoch % period.value)
pct.value = Math.round((remain.value / period.value) * 100)
const buf = new ArrayBuffer(8)
const dv = new DataView(buf)
dv.setUint32(0, Math.floor(counter / 0x100000000))
dv.setUint32(4, counter >>> 0)
try {
const cryptoKey = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-1' }, false, ['sign'])
const sig = new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, buf))
const off = sig[sig.length - 1] & 0x0f
const bin = ((sig[off] & 0x7f) << 24) | ((sig[off + 1] & 0xff) << 16) | ((sig[off + 2] & 0xff) << 8) | (sig[off + 3] & 0xff)
code.value = (bin % Math.pow(10, digits.value)).toString().padStart(digits.value, '0')
} catch (e) { error.value = '计算失败:' + e.message }
}
function tick() { compute() }
function copy() { if (code.value) navigator.clipboard?.writeText(code.value) }
timer = setInterval(tick, 1000)
onUnmounted(() => clearInterval(timer))2.3 效果截图
