3 * Copyright (c) 2015 Eran Kornblau <erankor at gmail dot com>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "random_seed.h"
27 #define AES_BLOCK_SIZE (16)
29 typedef struct AVAESCTR {
31 uint8_t counter[AES_BLOCK_SIZE];
32 uint8_t encrypted_counter[AES_BLOCK_SIZE];
36 struct AVAESCTR *av_aes_ctr_alloc(void)
38 return av_mallocz(sizeof(struct AVAESCTR));
41 void av_aes_ctr_set_iv(struct AVAESCTR *a, const uint8_t* iv)
43 memcpy(a->counter, iv, AES_CTR_IV_SIZE);
44 memset(a->counter + AES_CTR_IV_SIZE, 0, sizeof(a->counter) - AES_CTR_IV_SIZE);
48 void av_aes_ctr_set_full_iv(struct AVAESCTR *a, const uint8_t* iv)
50 memcpy(a->counter, iv, sizeof(a->counter));
54 const uint8_t* av_aes_ctr_get_iv(struct AVAESCTR *a)
59 void av_aes_ctr_set_random_iv(struct AVAESCTR *a)
63 iv[0] = av_get_random_seed();
64 iv[1] = av_get_random_seed();
66 av_aes_ctr_set_iv(a, (uint8_t*)iv);
69 int av_aes_ctr_init(struct AVAESCTR *a, const uint8_t *key)
71 a->aes = av_aes_alloc();
73 return AVERROR(ENOMEM);
76 av_aes_init(a->aes, key, 128, 0);
78 memset(a->counter, 0, sizeof(a->counter));
84 void av_aes_ctr_free(struct AVAESCTR *a)
92 static void av_aes_ctr_increment_be64(uint8_t* counter)
96 for (cur_pos = counter + 7; cur_pos >= counter; cur_pos--) {
104 void av_aes_ctr_increment_iv(struct AVAESCTR *a)
106 av_aes_ctr_increment_be64(a->counter);
107 memset(a->counter + AES_CTR_IV_SIZE, 0, sizeof(a->counter) - AES_CTR_IV_SIZE);
111 void av_aes_ctr_crypt(struct AVAESCTR *a, uint8_t *dst, const uint8_t *src, int count)
113 const uint8_t* src_end = src + count;
114 const uint8_t* cur_end_pos;
115 uint8_t* encrypted_counter_pos;
117 while (src < src_end) {
118 if (a->block_offset == 0) {
119 av_aes_crypt(a->aes, a->encrypted_counter, a->counter, 1, NULL, 0);
121 av_aes_ctr_increment_be64(a->counter + 8);
124 encrypted_counter_pos = a->encrypted_counter + a->block_offset;
125 cur_end_pos = src + AES_BLOCK_SIZE - a->block_offset;
126 cur_end_pos = FFMIN(cur_end_pos, src_end);
128 a->block_offset += cur_end_pos - src;
129 a->block_offset &= (AES_BLOCK_SIZE - 1);
131 while (src < cur_end_pos) {
132 *dst++ = *src++ ^ *encrypted_counter_pos++;