源码分享-M3U8数据流ts的AES-128解密并合并

源码依赖开源软件OpenSSL的crypto/aes/aes_core.c、crypto/aes/aes.h、crypto/aes/aes_locl.h共3个文件。

#include 
#include 
#include 
#include "aes.h"

#define M3U8_PATH "C:/Source/1/m3u8/"
#define M3U8_KEY "03c01165beea11bd"
#define M3U8_OUT_FILE "C:/Source/1/all.ts"
#define M3U8_COUNT 0xFFFF

int decodeAES128CBC(const char *inPath, FILE *out,
                  const char userKey[16], unsigned char ivec[16]) {
    FILE *in;
    int i, n;
    unsigned char outTemp[16], inTemp[16];
    AES_KEY key;

    in = fopen(inPath, "rb");
    if (in == NULL) return errno;

    fseek(in, 0L, SEEK_END);
    n = (int) (ftell(in) / 16);
    fseek(in, 0L, SEEK_SET);

    AES_set_decrypt_key((const unsigned char*) userKey, 128, &key);

    while (n > 0) {
        fread(inTemp, 1, 16, in);
        AES_decrypt(inTemp, outTemp, &key);
        for (i = 0; i < 16; i++) {
            outTemp[i] ^= ivec[i];
            ivec[i] = inTemp[i];
        }
        if (n == 1) {
            fwrite(outTemp, 1, 16 - outTemp[15], out);
            break;
        } else {
            fwrite(outTemp, 1, 16, out);
        }
        n--;
    }

    fclose(in);
    return 0;
}

void setIV(unsigned char ivec[16], int index) {
    unsigned int *ivPtr = (unsigned int*) ivec;
    ivPtr[0] = ivPtr[1] = ivPtr[2] = 0;

    ivec[12] = index >> 24;
    ivec[13] = index >> 16;
    ivec[14] = index >> 8;
    ivec[15] = index;
}

int main()
{
    FILE *out;
    unsigned char iv[16];
    char inPath[MAX_PATH] = M3U8_PATH;
    int err, i, in;

    out = fopen(M3U8_OUT_FILE, "wb");
    if (out == NULL) {
        fprintf(stderr, "%s : %s\n", strerror(errno), M3U8_OUT_FILE);
        return 0;
    }

    in = strlen(inPath);
    for (i = 0; i < M3U8_COUNT; i++) {
        sprintf(inPath + in, "%d.ts", i);
        setIV(iv, i);
        err = decodeAES128CBC(inPath, out, M3U8_KEY, iv);
        if (err) {
            fprintf(stderr, "%s : %d\n", strerror(err), i);
            break;
        }
    }
    fclose(out);
    return 0;
}

 

你可能感兴趣的:(其他,M3U8,AES-128,ts,合并,源码)