我有一个文件,我已经使用crypto.createCipher对其进行了加密,现在我想对该文件进行流传输并在流传输时解密。
我编写了以下代码,但是当我设置“ Content-Range”和“ accept-Ranges”标头时,流媒体无法正常工作。
如何使用内容范围对它进行流式传输和解密?
const path = "file path";
const stat = fs.statSync(path);
const fileSize = stat.size;
const range = req.headers.range;
const algorithm = 'aes-256-ctr';
const password = '123456';
const encrypt = crypto.createCipher(algorithm,password);
const decrypt = crypto.createDecipher(algorithm,password);
if (range) {
const parts = range.replace(/bytes=/,"").split("-");
const start = parseInt(parts[0],10);
const end = parts[1] ? parseInt(parts[1],10) : fileSize - 1;
const chunksize = end - start + 1;
const file = fs.createReadStream(path,{ start,end });
const head = {
"Content-Range": `bytes ${start}-${end}/${fileSize}`,"accept-Ranges": "bytes","Content-Length": chunksize,"Content-Type": "video/mp4"
};
res.writeHead(200,head);
file
.pipe(decrypt)
.pipe(res);
} else {
const head = {
"Content-Length": fileSize,"Content-Type": "video/mp4"
};
res.writeHead(200,head);
fs.createReadStream(path).pipe(decrypt).pipe(res);
}