Node.js实现兼容PHP OpenSSL AES-256-CTR的解密功能
Node.js 兼容PHP逻辑的AES-256-CTR解密实现
对齐规则
- 加密算法固定使用
aes-256-ctr,与PHP端配置一致 - nonce(即IV)长度为16字节,和PHP
openssl_cipher_iv_length返回值一致 - 密文结构为
nonce + 原始密文,支持base64编码输入/原始二进制输入两种模式 - 解密失败统一返回
false,与PHP端返回行为完全对齐
完整代码
const crypto = require('crypto'); // 与PHP hex2bin逻辑对齐的转换函数 const hex2bin = s => s.match(/../g).map(c => String.fromCharCode(parseInt(c, 16))).join``; /** * 解密函数 * @param {string|Buffer} message 待解密内容 * @param {boolean} [encoded=true] 待解密内容是否为base64编码,默认true * @returns {string|boolean} 解密成功返回utf8格式明文,失败返回false */ function token_decrypt(message, encoded = true) { try { const encryptMethod = 'aes-256-ctr'; const nonceSize = 16; // 处理密钥:对齐OpenSSL规则,AES-256要求32字节密钥,不足位补0x00 const rawKey = hex2bin('KEY123'); const encryptKey = Buffer.alloc(32); encryptKey.write(rawKey, 0, rawKey.length, 'binary'); // 解析输入密文为Buffer let cipherBuffer; if (encoded) { cipherBuffer = Buffer.from(message, 'base64'); // 校验base64解码合法性 if (cipherBuffer.length === 0 && message.length > 0) return false; } else { cipherBuffer = Buffer.isBuffer(message) ? message : Buffer.from(message, 'binary'); } // 密文长度小于nonce长度时直接判定非法 if (cipherBuffer.length < nonceSize) return false; // 拆分nonce和实际密文 const nonce = cipherBuffer.subarray(0, nonceSize); const ciphertext = cipherBuffer.subarray(nonceSize); // 初始化解密器,CTR为流模式无需填充 const decipher = crypto.createDecipheriv(encryptMethod, encryptKey, nonce); decipher.setAutoPadding(false); // 执行解密拼接结果 const plainBuf = Buffer.concat([decipher.update(ciphertext), decipher.final()]); return plainBuf.toString('utf8'); } catch (err) { return false; } }
调用方式
// 解密base64格式密文(对应PHP调用:$this->token_decrypt($msg, true)) const plaintext = token_decrypt('替换成你的实际密文'); console.log(plaintext); // 解密原始二进制密文(对应PHP调用:$this->token_decrypt($msg, false)) // const plaintext = token_decrypt(rawBinaryData, false);
注意点
- 全程使用Node.js内置
crypto模块,无需安装第三方依赖 - 密钥处理逻辑对齐OpenSSL默认行为:传入密钥长度不足32字节时自动补0,避免两侧密钥不一致导致解密失败
- 所有二进制操作均通过Buffer实现,避免二进制转字符串导致的编码错误、截取偏移问题
- 覆盖base64非法、密文长度不足、解密校验失败等异常场景,统一返回false
内容的提问来源于stack exchange,提问作者OneRice
相关产品推荐
相关产品推荐

