开发WordPress短信OTP登录注册插件:OTP传输加密及JS实现咨询
OTP验证码传输的加密必要性及JS实现方案
1. 将OTP验证码发送至服务器时是否需要加密?
需要加密,核心原因如下:
- 即便用了WordPress nonce防范CSRF攻击,OTP本身是直接验证用户身份的敏感凭证,明文传输时,若网站未启用HTTPS,会被网络窃听直接获取,导致账号被冒用;
- 就算是HTTPS环境,传输层的SSL加密已经提供基础防护,但额外的应用层加密能多一层保障——比如避免服务器日志意外记录明文OTP,或是降低中间人攻击下的会话劫持风险。
2. 若需要加密,可使用哪些JavaScript代码实现?
推荐两种基于非对称加密的方案(用服务器公钥加密,仅服务器私钥可解密):
方案一:基于jsencrypt库实现RSA加密
先将jsencrypt核心代码嵌入前端(避免外部依赖),用服务器生成的公钥加密OTP:
// 初始化加密实例,填入服务器生成的公钥 const encrypt = new JSEncrypt(); encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----你的公钥内容-----END PUBLIC KEY-----'); // 获取用户输入的OTP const otpCode = document.getElementById('otp-input').value; // 加密OTP const encryptedOtp = encrypt.encrypt(otpCode); // 发送加密后的OTP到服务器 fetch('/wp-json/your-plugin/v1/verify-otp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': document.getElementById('wp-nonce').value }, body: JSON.stringify({ encrypted_otp: encryptedOtp }) });
服务器端可通过openssl_private_decrypt函数用私钥解密。
方案二:使用浏览器原生Web Crypto API
无需外部库,直接用浏览器原生API实现RSA加密:
async function encryptOtp(otp, publicKey) { // 解析公钥 const key = await window.crypto.subtle.importKey( 'spki', new TextEncoder().encode(publicKey), { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['encrypt'] ); // 加密OTP const encryptedBuffer = await window.crypto.subtle.encrypt( { name: 'RSA-OAEP' }, key, new TextEncoder().encode(otp) ); // 转换为Base64字符串便于传输 return btoa(String.fromCharCode(...new Uint8Array(encryptedBuffer))); } // 使用示例 const publicKey = '-----BEGIN PUBLIC KEY-----你的公钥内容-----END PUBLIC KEY-----'; const otpCode = document.getElementById('otp-input').value; encryptOtp(otpCode, publicKey).then(encryptedOtp => { fetch('/wp-json/your-plugin/v1/verify-otp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': document.getElementById('wp-nonce').value }, body: JSON.stringify({ encrypted_otp: encryptedOtp }) }); });
注意:Web Crypto API仅支持HTTPS环境(本地localhost开发除外),公钥可直接硬编码在前端,私钥必须严格保存在服务器端,禁止泄露。
内容的提问来源于stack exchange,提问作者ayoob zare
相关产品推荐
相关产品推荐

