1 /*
2 * AES-256 file encryption program
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 *
7 * This file is provided under the Apache License 2.0, or the
8 * GNU General Public License v2.0 or later.
9 *
10 * **********
11 * Apache License 2.0:
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License"); you may
14 * not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
21 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 *
25 * **********
26 *
27 * **********
28 * GNU General Public License v2.0 or later:
29 *
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2 of the License, or
33 * (at your option) any later version.
34 *
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
39 *
40 * You should have received a copy of the GNU General Public License along
41 * with this program; if not, write to the Free Software Foundation, Inc.,
42 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
43 *
44 * **********
45 */
46
47 /* Enable definition of fileno() even when compiling with -std=c99. Must be
48 * set before config.h, which pulls in glibc's features.h indirectly.
49 * Harmless on other platforms. */
50 #define _POSIX_C_SOURCE 1
51
52 #if !defined(MBEDTLS_CONFIG_FILE)
53 #include "mbedtls/config.h"
54 #else
55 #include MBEDTLS_CONFIG_FILE
56 #endif
57
58 #if defined(MBEDTLS_PLATFORM_C)
59 #include "mbedtls/platform.h"
60 #else
61 #include <stdio.h>
62 #include <stdlib.h>
63 #define mbedtls_fprintf fprintf
64 #define mbedtls_printf printf
65 #define mbedtls_exit exit
66 #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
67 #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
68 #endif /* MBEDTLS_PLATFORM_C */
69
70 #include "mbedtls/aes.h"
71 #include "mbedtls/md.h"
72 #include "mbedtls/platform_util.h"
73
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77
78 #if defined(_WIN32)
79 #include <windows.h>
80 #if !defined(_WIN32_WCE)
81 #include <io.h>
82 #endif
83 #else
84 #include <sys/types.h>
85 #include <unistd.h>
86 #endif
87
88 #define MODE_ENCRYPT 0
89 #define MODE_DECRYPT 1
90
91 #define USAGE \
92 "\n aescrypt2 <mode> <input filename> <output filename> <key>\n" \
93 "\n <mode>: 0 = encrypt, 1 = decrypt\n" \
94 "\n example: aescrypt2 0 file file.aes hex:E76B2413958B00E193\n" \
95 "\n"
96
97 #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_SHA256_C) || \
98 !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_MD_C)
main(void)99 int main( void )
100 {
101 mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_SHA256_C "
102 "and/or MBEDTLS_FS_IO and/or MBEDTLS_MD_C "
103 "not defined.\n");
104 mbedtls_exit( 0 );
105 }
106 #else
107
108
main(int argc,char * argv[])109 int main( int argc, char *argv[] )
110 {
111 int ret = 0;
112 int exit_code = MBEDTLS_EXIT_FAILURE;
113
114 unsigned int i, n;
115 int mode, lastn;
116 size_t keylen;
117 FILE *fkey, *fin = NULL, *fout = NULL;
118
119 char *p;
120
121 unsigned char IV[16];
122 unsigned char tmp[16];
123 unsigned char key[512];
124 unsigned char digest[32];
125 unsigned char buffer[1024];
126 unsigned char diff;
127
128 mbedtls_aes_context aes_ctx;
129 mbedtls_md_context_t sha_ctx;
130
131 #if defined(_WIN32_WCE)
132 long filesize, offset;
133 #elif defined(_WIN32)
134 LARGE_INTEGER li_size;
135 __int64 filesize, offset;
136 #else
137 off_t filesize, offset;
138 #endif
139
140 mbedtls_aes_init( &aes_ctx );
141 mbedtls_md_init( &sha_ctx );
142
143 ret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
144 if( ret != 0 )
145 {
146 mbedtls_printf( " ! mbedtls_md_setup() returned -0x%04x\n", -ret );
147 goto exit;
148 }
149
150 /*
151 * Parse the command-line arguments.
152 */
153 if( argc != 5 )
154 {
155 mbedtls_printf( USAGE );
156
157 #if defined(_WIN32)
158 mbedtls_printf( "\n Press Enter to exit this program.\n" );
159 fflush( stdout ); getchar();
160 #endif
161
162 goto exit;
163 }
164
165 mode = atoi( argv[1] );
166 memset( IV, 0, sizeof( IV ) );
167 memset( key, 0, sizeof( key ) );
168 memset( digest, 0, sizeof( digest ) );
169 memset( buffer, 0, sizeof( buffer ) );
170
171 if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
172 {
173 mbedtls_fprintf( stderr, "invalide operation mode\n" );
174 goto exit;
175 }
176
177 if( strcmp( argv[2], argv[3] ) == 0 )
178 {
179 mbedtls_fprintf( stderr, "input and output filenames must differ\n" );
180 goto exit;
181 }
182
183 if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
184 {
185 mbedtls_fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
186 goto exit;
187 }
188
189 if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
190 {
191 mbedtls_fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
192 goto exit;
193 }
194
195 /*
196 * Read the secret key from file or command line
197 */
198 if( ( fkey = fopen( argv[4], "rb" ) ) != NULL )
199 {
200 keylen = fread( key, 1, sizeof( key ), fkey );
201 fclose( fkey );
202 }
203 else
204 {
205 if( memcmp( argv[4], "hex:", 4 ) == 0 )
206 {
207 p = &argv[4][4];
208 keylen = 0;
209
210 while( sscanf( p, "%02X", &n ) > 0 &&
211 keylen < (int) sizeof( key ) )
212 {
213 key[keylen++] = (unsigned char) n;
214 p += 2;
215 }
216 }
217 else
218 {
219 keylen = strlen( argv[4] );
220
221 if( keylen > (int) sizeof( key ) )
222 keylen = (int) sizeof( key );
223
224 memcpy( key, argv[4], keylen );
225 }
226 }
227
228 #if defined(_WIN32_WCE)
229 filesize = fseek( fin, 0L, SEEK_END );
230 #else
231 #if defined(_WIN32)
232 /*
233 * Support large files (> 2Gb) on Win32
234 */
235 li_size.QuadPart = 0;
236 li_size.LowPart =
237 SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
238 li_size.LowPart, &li_size.HighPart, FILE_END );
239
240 if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
241 {
242 mbedtls_fprintf( stderr, "SetFilePointer(0,FILE_END) failed\n" );
243 goto exit;
244 }
245
246 filesize = li_size.QuadPart;
247 #else
248 if( ( filesize = lseek( fileno( fin ), 0, SEEK_END ) ) < 0 )
249 {
250 perror( "lseek" );
251 goto exit;
252 }
253 #endif
254 #endif
255
256 if( fseek( fin, 0, SEEK_SET ) < 0 )
257 {
258 mbedtls_fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
259 goto exit;
260 }
261
262 if( mode == MODE_ENCRYPT )
263 {
264 /*
265 * Generate the initialization vector as:
266 * IV = SHA-256( filesize || filename )[0..15]
267 */
268 for( i = 0; i < 8; i++ )
269 buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
270
271 p = argv[2];
272
273 mbedtls_md_starts( &sha_ctx );
274 mbedtls_md_update( &sha_ctx, buffer, 8 );
275 mbedtls_md_update( &sha_ctx, (unsigned char *) p, strlen( p ) );
276 mbedtls_md_finish( &sha_ctx, digest );
277
278 memcpy( IV, digest, 16 );
279
280 /*
281 * The last four bits in the IV are actually used
282 * to store the file size modulo the AES block size.
283 */
284 lastn = (int)( filesize & 0x0F );
285
286 IV[15] = (unsigned char)
287 ( ( IV[15] & 0xF0 ) | lastn );
288
289 /*
290 * Append the IV at the beginning of the output.
291 */
292 if( fwrite( IV, 1, 16, fout ) != 16 )
293 {
294 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
295 goto exit;
296 }
297
298 /*
299 * Hash the IV and the secret key together 8192 times
300 * using the result to setup the AES context and HMAC.
301 */
302 memset( digest, 0, 32 );
303 memcpy( digest, IV, 16 );
304
305 for( i = 0; i < 8192; i++ )
306 {
307 mbedtls_md_starts( &sha_ctx );
308 mbedtls_md_update( &sha_ctx, digest, 32 );
309 mbedtls_md_update( &sha_ctx, key, keylen );
310 mbedtls_md_finish( &sha_ctx, digest );
311 }
312
313 mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 );
314 mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
315
316 /*
317 * Encrypt and write the ciphertext.
318 */
319 for( offset = 0; offset < filesize; offset += 16 )
320 {
321 n = ( filesize - offset > 16 ) ? 16 : (int)
322 ( filesize - offset );
323
324 if( fread( buffer, 1, n, fin ) != (size_t) n )
325 {
326 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", n );
327 goto exit;
328 }
329
330 for( i = 0; i < 16; i++ )
331 buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
332
333 mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, buffer, buffer );
334 mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
335
336 if( fwrite( buffer, 1, 16, fout ) != 16 )
337 {
338 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
339 goto exit;
340 }
341
342 memcpy( IV, buffer, 16 );
343 }
344
345 /*
346 * Finally write the HMAC.
347 */
348 mbedtls_md_hmac_finish( &sha_ctx, digest );
349
350 if( fwrite( digest, 1, 32, fout ) != 32 )
351 {
352 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
353 goto exit;
354 }
355 }
356
357 if( mode == MODE_DECRYPT )
358 {
359 /*
360 * The encrypted file must be structured as follows:
361 *
362 * 00 .. 15 Initialization Vector
363 * 16 .. 31 AES Encrypted Block #1
364 * ..
365 * N*16 .. (N+1)*16 - 1 AES Encrypted Block #N
366 * (N+1)*16 .. (N+1)*16 + 32 HMAC-SHA-256(ciphertext)
367 */
368 if( filesize < 48 )
369 {
370 mbedtls_fprintf( stderr, "File too short to be encrypted.\n" );
371 goto exit;
372 }
373
374 if( ( filesize & 0x0F ) != 0 )
375 {
376 mbedtls_fprintf( stderr, "File size not a multiple of 16.\n" );
377 goto exit;
378 }
379
380 /*
381 * Subtract the IV + HMAC length.
382 */
383 filesize -= ( 16 + 32 );
384
385 /*
386 * Read the IV and original filesize modulo 16.
387 */
388 if( fread( buffer, 1, 16, fin ) != 16 )
389 {
390 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
391 goto exit;
392 }
393
394 memcpy( IV, buffer, 16 );
395 lastn = IV[15] & 0x0F;
396
397 /*
398 * Hash the IV and the secret key together 8192 times
399 * using the result to setup the AES context and HMAC.
400 */
401 memset( digest, 0, 32 );
402 memcpy( digest, IV, 16 );
403
404 for( i = 0; i < 8192; i++ )
405 {
406 mbedtls_md_starts( &sha_ctx );
407 mbedtls_md_update( &sha_ctx, digest, 32 );
408 mbedtls_md_update( &sha_ctx, key, keylen );
409 mbedtls_md_finish( &sha_ctx, digest );
410 }
411
412 mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 );
413 mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
414
415 /*
416 * Decrypt and write the plaintext.
417 */
418 for( offset = 0; offset < filesize; offset += 16 )
419 {
420 if( fread( buffer, 1, 16, fin ) != 16 )
421 {
422 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
423 goto exit;
424 }
425
426 memcpy( tmp, buffer, 16 );
427
428 mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
429 mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_DECRYPT, buffer, buffer );
430
431 for( i = 0; i < 16; i++ )
432 buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
433
434 memcpy( IV, tmp, 16 );
435
436 n = ( lastn > 0 && offset == filesize - 16 )
437 ? lastn : 16;
438
439 if( fwrite( buffer, 1, n, fout ) != (size_t) n )
440 {
441 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", n );
442 goto exit;
443 }
444 }
445
446 /*
447 * Verify the message authentication code.
448 */
449 mbedtls_md_hmac_finish( &sha_ctx, digest );
450
451 if( fread( buffer, 1, 32, fin ) != 32 )
452 {
453 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 32 );
454 goto exit;
455 }
456
457 /* Use constant-time buffer comparison */
458 diff = 0;
459 for( i = 0; i < 32; i++ )
460 diff |= digest[i] ^ buffer[i];
461
462 if( diff != 0 )
463 {
464 mbedtls_fprintf( stderr, "HMAC check failed: wrong key, "
465 "or file corrupted.\n" );
466 goto exit;
467 }
468 }
469
470 exit_code = MBEDTLS_EXIT_SUCCESS;
471
472 exit:
473 if( fin )
474 fclose( fin );
475 if( fout )
476 fclose( fout );
477
478 /* Zeroize all command line arguments to also cover
479 the case when the user has missed or reordered some,
480 in which case the key might not be in argv[4]. */
481 for( i = 0; i < (unsigned int) argc; i++ )
482 mbedtls_platform_zeroize( argv[i], strlen( argv[i] ) );
483
484 mbedtls_platform_zeroize( IV, sizeof( IV ) );
485 mbedtls_platform_zeroize( key, sizeof( key ) );
486 mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
487 mbedtls_platform_zeroize( buffer, sizeof( buffer ) );
488 mbedtls_platform_zeroize( digest, sizeof( digest ) );
489
490 mbedtls_aes_free( &aes_ctx );
491 mbedtls_md_free( &sha_ctx );
492
493 mbedtls_exit( exit_code );
494 }
495 #endif /* MBEDTLS_AES_C && MBEDTLS_SHA256_C && MBEDTLS_FS_IO */
496