Web应用如何仅在设备解锁(生物识别/PIN)后解密敏感数据?
解决方案:Web应用解密前触发设备生物识别验证
核心方案1:Web Crypto密钥绑定生物识别验证
你可以在创建不可提取的CryptoKey时,直接将其与设备生物识别验证绑定,后续调用解密操作时会自动触发验证:
- 生成密钥时,在加密算法选项中设置
userVerification: "required" - 密钥存储到IndexedDB后,每次调用
SubtleCrypto.decrypt()时,浏览器会自动弹出设备的生物识别/锁屏验证界面,只有验证通过才能完成解密
示例代码
// 生成绑定生物识别的AES密钥 async function createBiometricBoundKey() { const key = await window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, false, // 不可提取 ["encrypt", "decrypt"] ); return key; } // 解密时自动触发验证 async function decryptWithBiometricCheck(key, encryptedData, iv) { try { const decrypted = await window.crypto.subtle.decrypt( { name: "AES-GCM", iv: iv, userVerification: "required" // 明确要求验证 }, key, encryptedData ); return new TextDecoder().decode(decrypted); } catch (e) { console.error("生物识别验证失败", e); throw new Error("验证未通过,无法解密数据"); } }
核心方案2:WebAuthn验证已有用户凭证(无需重新创建)
虽然你提到WebAuthn需要创建凭证,但其实可以利用Assertion流程验证已有的用户凭证,无需重新注册:
- 调用
navigator.credentials.get(),指定已存在的用户ID和依赖方信息 - 验证通过后再执行解密操作,确保操作者是机主
示例代码
async function verifyExistingUser() { const assertion = await navigator.credentials.get({ publicKey: { challenge: new Uint8Array([/* 服务器生成的随机挑战 */]), rpId: "your-domain.com", // 你的网站域名 userVerification: "required", // 强制生物识别验证 allowCredentials: [ { type: "public-key", id: new Uint8Array([/* 已存储的用户凭证ID */]), transports: ["internal"] // 指定使用设备内置生物识别 } ] } }); // 发送到服务器验证(可选,适配你的现有凭证系统) const isValid = await fetch("/verify-assertion", { method: "POST", body: JSON.stringify({ assertion }) }).then(res => res.json()); return isValid; } // 使用流程:先验证,再解密 async function accessSensitiveData(key, encryptedData, iv) { const isVerified = await verifyExistingUser(); if (!isVerified) { throw new Error("身份验证失败,无法访问敏感数据"); } return decryptWithBiometricCheck(key, encryptedData, iv); }
平台支持说明
- Chrome/Edge:完全支持Web Crypto的
userVerification参数,以及WebAuthn的Assertion流程 - Safari:支持WebAuthn验证,Web Crypto的生物识别绑定需配合系统Secure Enclave存储密钥
- Firefox:对Web Crypto的生物识别绑定支持有限,建议优先使用WebAuthn方案
关键注意事项
- 所有操作必须在HTTPS环境下进行(本地开发可使用
localhost) - 不可提取的
CryptoKey无法被导出,只能在验证通过后由浏览器内部使用,确保密钥安全 - 生物识别验证的触发由浏览器和系统控制,界面与原生应用体验一致
内容的提问来源于stack exchange,提问作者prime
相关产品推荐
相关产品推荐

