在 NodeJs 中使用 AES GCM 加密的流媒体视频

Gau*_*sak 6 javascript cryptography aes node.js hapi.js

我有一些从 S3 流式传输未加密视频的代码,现在我想让它适用于加密视频文件,为此我使用 AES GCM。

但是html5播放器无法播放。我尝试解密完整文件并且它有效(没有流媒体)。任何建议将不胜感激。该代码适用于 HapisJS。

      const file = 'test/movie.mp4.enc';
      const s3Bucket = new S3();
      const paramsWholeFile = { Bucket: 'mybucket-v1', Key: file};
      const headWholeFile = await s3Bucket.headObject(paramsWholeFile).promise();
      const fileSize = headWholeFile.ContentLength!;

      const range = req.headers.range;
      console.log(range);

      const parts = range.replace(/bytes=/, "").split("-")
      let start = parseInt(parts[0], 10);
      if (start > 0) {
        start -= (start % 16); // reading from the beginning of AES block
      }

      let end = parts[1]
        ? parseInt(parts[1], 10) - parseInt(parts[1], 10) % 16 # reading until the latest AES block
        : fileSize - 1;

      const chunksize = (end - start) + 1;
      //const file = Fs.createReadStream(path, {start, end})
      const params = { Bucket: 'mybucket-v1', Key: file, Range: `bytes=${start}-`};
      const object = s3Bucket.getObject(params);
      const stream = object.createReadStream();

      const dataKey = await CipherService.getDataKey(headWholeFile.Metadata!['x-amz-key']);
      const authTag = headWholeFile.Metadata!['x-amz-auth-tag'];

      const iv = new Buffer(headWholeFile.Metadata!['x-amz-iv'], 'base64');
      const decipher = Crypto.createDecipheriv(
        'aes-256-gcm',
        dataKey.Plaintext as Buffer,
        iv
      );
      decipher.setAuthTag(new Buffer(authTag , 'base64'));
      const decryptedStream = stream.pipe(decipher);

      const response = h.response(decryptedStream).code(206);
      response.header('Content-Range', `bytes ${start}-${end}/${fileSize}`);
      response.header('Accept-Ranges', `bytes`);
      response.header('Content-Length', `${chunksize}`);
      response.header('Content-Type', `video/mp4`);
      return response;
Run Code Online (Sandbox Code Playgroud)