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
26 #include "aes_internal.h"
29 #include "random_seed.h"
31 #define AES_BLOCK_SIZE (16)
33 typedef struct AVAESCTR
{
34 uint8_t counter
[AES_BLOCK_SIZE
];
35 uint8_t encrypted_counter
[AES_BLOCK_SIZE
];
40 struct AVAESCTR
*av_aes_ctr_alloc(void)
42 return av_mallocz(sizeof(struct AVAESCTR
));
45 void av_aes_ctr_set_iv(struct AVAESCTR
*a
, const uint8_t* iv
)
47 memcpy(a
->counter
, iv
, AES_CTR_IV_SIZE
);
48 memset(a
->counter
+ AES_CTR_IV_SIZE
, 0, sizeof(a
->counter
) - AES_CTR_IV_SIZE
);
52 void av_aes_ctr_set_full_iv(struct AVAESCTR
*a
, const uint8_t* iv
)
54 memcpy(a
->counter
, iv
, sizeof(a
->counter
));
58 const uint8_t* av_aes_ctr_get_iv(struct AVAESCTR
*a
)
63 void av_aes_ctr_set_random_iv(struct AVAESCTR
*a
)
67 iv
[0] = av_get_random_seed();
68 iv
[1] = av_get_random_seed();
70 av_aes_ctr_set_iv(a
, (uint8_t*)iv
);
73 int av_aes_ctr_init(struct AVAESCTR
*a
, const uint8_t *key
)
75 av_aes_init(&a
->aes
, key
, 128, 0);
77 memset(a
->counter
, 0, sizeof(a
->counter
));
83 void av_aes_ctr_free(struct AVAESCTR
*a
)
88 static void av_aes_ctr_increment_be64(uint8_t* counter
)
92 for (cur_pos
= counter
+ 7; cur_pos
>= counter
; cur_pos
--) {
100 void av_aes_ctr_increment_iv(struct AVAESCTR
*a
)
102 av_aes_ctr_increment_be64(a
->counter
);
103 memset(a
->counter
+ AES_CTR_IV_SIZE
, 0, sizeof(a
->counter
) - AES_CTR_IV_SIZE
);
107 void av_aes_ctr_crypt(struct AVAESCTR
*a
, uint8_t *dst
, const uint8_t *src
, int count
)
109 const uint8_t* src_end
= src
+ count
;
110 const uint8_t* cur_end_pos
;
111 uint8_t* encrypted_counter_pos
;
113 while (src
< src_end
) {
114 if (a
->block_offset
== 0) {
115 av_aes_crypt(&a
->aes
, a
->encrypted_counter
, a
->counter
, 1, NULL
, 0);
117 av_aes_ctr_increment_be64(a
->counter
+ 8);
120 encrypted_counter_pos
= a
->encrypted_counter
+ a
->block_offset
;
121 cur_end_pos
= src
+ AES_BLOCK_SIZE
- a
->block_offset
;
122 cur_end_pos
= FFMIN(cur_end_pos
, src_end
);
124 a
->block_offset
+= cur_end_pos
- src
;
125 a
->block_offset
&= (AES_BLOCK_SIZE
- 1);
127 while (src
< cur_end_pos
) {
128 *dst
++ = *src
++ ^ *encrypted_counter_pos
++;