c# - 在没有 IV 的情况下解密使用 AES-128 加密的 M3U8 播放列表

标签 c# aes http-live-streaming m3u8

我目前正在构建一个用于下载 M3U8 播放列表的应用程序,但我遇到了一个问题:如果播放列表是使用 AES-128 加密的,例如有这样一行:

#EXT-X-KEY:METHOD=AES-128,URI="https://website.com/link.key",IV=0xblablabla

我必须在将段写入输出文件之前对其进行解密,如果存在 IV,则以下代码对我有用,但如果 IV 属性不存在,则解密会产生错误的结果:

var iv = "parsed iv"; // empty if not present
var key_url = "parsed keyurl";

var AES = new AesManaged()
{
    Mode = CipherMode.CBC,
    Key = await Client.GetByteArrayAsync(key_url)
};

if (!string.IsNullOrEmpty(iv))
    AES.IV = Functions.HexToByte(iv.StartsWith("0x") ? iv.Remove(0, 2) : iv);
else
    AES.IV = new byte[16];

//...

using (FileStream fs = new FileStream("file.ts", FileMode.Create, FileAccess.Write, FileShare.Read))
{
    var data = DownloadSegment(...); // Downloads segment as byte array (encrypted)

    byte[] temp = new byte[data.Length];

    ICryptoTransform transform = AES.CreateDecryptor();
    using (MemoryStream memoryStream = new MemoryStream(data))
    {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read))
        {
            cryptoStream.Read(temp, 0, data.Length);
        }
    }

    await fs.WriteAsync(temp, 0, temp.Length);
}

(这显然只是一个代码片段,包含解密部分,因为所有解析和下载工作正常)。

如果不存在 IV,你们有谁知道如何解密 M3U8 播放列表文件中的 AES-128 加密段,例如只是

#EXT-X-KEY:METHOD=AES-128,URI="https://website.com/link.key"?

非常感谢任何帮助。提前致谢!

最佳答案

HLS 规范指出 [1]:

An encryption method of AES-128 signals that Media Segments are completely encrypted using the Advanced Encryption Standard (AES) [AES_128] with a 128-bit key, Cipher Block Chaining (CBC), and Public-Key Cryptography Standards #7 (PKCS7) padding [RFC5652]. CBC is restarted on each segment boundary, using either the Initialization Vector (IV) attribute value or the Media Sequence Number as the IV; see Section 5.2.

因此您必须在变体播放列表中使用 EXT-X-MEDIA-SEQUENCE 标签的值。一定要外推,即为每个段增加它。

[1] https://www.rfc-editor.org/rfc/rfc8216#section-4.3.2.4

关于c# - 在没有 IV 的情况下解密使用 AES-128 加密的 M3U8 播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628791/

相关文章:

c# - BacgroundWorkerCompleted 不执行

encryption - 解密 ZigBee paquets

c# - MySQL 中带有波兰语字符的 AES_DECRYPT() 和 AES_ENCRYPT()

ios - AVPlayer seekToTime 下载大量消耗大量数据的媒体段文件

ffmpeg - 向ffmpeg m3u8文件添加标签的问题

c# - 使用 AngularJS 的 Web API 异步方法

c# - 在 File.Copy 之后文件正在被另一个进程使用

C# 列表从末尾删除,真的是 O(n) 吗?

javascript - 在 Node js 中加速 AES 解密

Nginx RTMP/HLS - 流式传输到 ffmpeg 并输出 HLS