2 * \brief Generic file encryption program using generic wrappers for configured
5 * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
6 * SPDX-License-Identifier: Apache-2.0
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may
9 * not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * This file is part of mbed TLS (https://tls.mbed.org)
23 /* Enable definition of fileno() even when compiling with -std=c99. Must be
24 * set before config.h, which pulls in glibc's features.h indirectly.
25 * Harmless on other platforms. */
26 #define _POSIX_C_SOURCE 1
28 #if !defined(MBEDTLS_CONFIG_FILE)
29 #include "mbedtls/config.h"
31 #include MBEDTLS_CONFIG_FILE
34 #if defined(MBEDTLS_PLATFORM_C)
35 #include "mbedtls/platform.h"
39 #define mbedtls_fprintf fprintf
40 #define mbedtls_printf printf
41 #define mbedtls_exit exit
42 #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
43 #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
44 #endif /* MBEDTLS_PLATFORM_C */
46 #if defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_MD_C) && \
47 defined(MBEDTLS_FS_IO)
48 #include "mbedtls/cipher.h"
49 #include "mbedtls/md.h"
50 #include "mbedtls/platform_util.h"
59 #if !defined(_WIN32_WCE)
63 #include <sys/types.h>
67 #define MODE_ENCRYPT 0
68 #define MODE_DECRYPT 1
71 "\n crypt_and_hash <mode> <input filename> <output filename> <cipher> <mbedtls_md> <key>\n" \
72 "\n <mode>: 0 = encrypt, 1 = decrypt\n" \
73 "\n example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
76 #if !defined(MBEDTLS_CIPHER_C) || !defined(MBEDTLS_MD_C) || \
77 !defined(MBEDTLS_FS_IO)
80 mbedtls_printf("MBEDTLS_CIPHER_C and/or MBEDTLS_MD_C and/or MBEDTLS_FS_IO not defined.\n");
85 #if defined(MBEDTLS_CHECK_PARAMS)
86 #include "mbedtls/platform_util.h"
87 void mbedtls_param_failed( const char *failure_condition,
91 mbedtls_printf( "%s:%i: Input param failed - %s\n",
92 file, line, failure_condition );
93 mbedtls_exit( MBEDTLS_EXIT_FAILURE );
97 int main( int argc, char *argv[] )
100 int exit_code = MBEDTLS_EXIT_FAILURE;
102 size_t keylen, ilen, olen;
103 FILE *fkey, *fin = NULL, *fout = NULL;
106 unsigned char IV[16];
107 unsigned char key[512];
108 unsigned char digest[MBEDTLS_MD_MAX_SIZE];
109 unsigned char buffer[1024];
110 unsigned char output[1024];
113 const mbedtls_cipher_info_t *cipher_info;
114 const mbedtls_md_info_t *md_info;
115 mbedtls_cipher_context_t cipher_ctx;
116 mbedtls_md_context_t md_ctx;
117 #if defined(_WIN32_WCE)
118 long filesize, offset;
119 #elif defined(_WIN32)
120 LARGE_INTEGER li_size;
121 __int64 filesize, offset;
123 off_t filesize, offset;
126 mbedtls_cipher_init( &cipher_ctx );
127 mbedtls_md_init( &md_ctx );
130 * Parse the command-line arguments.
136 mbedtls_printf( USAGE );
138 mbedtls_printf( "Available ciphers:\n" );
139 list = mbedtls_cipher_list();
142 cipher_info = mbedtls_cipher_info_from_type( *list );
143 mbedtls_printf( " %s\n", cipher_info->name );
147 mbedtls_printf( "\nAvailable message digests:\n" );
148 list = mbedtls_md_list();
151 md_info = mbedtls_md_info_from_type( *list );
152 mbedtls_printf( " %s\n", mbedtls_md_get_name( md_info ) );
157 mbedtls_printf( "\n Press Enter to exit this program.\n" );
158 fflush( stdout ); getchar();
164 mode = atoi( argv[1] );
166 if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
168 mbedtls_fprintf( stderr, "invalid operation mode\n" );
172 if( strcmp( argv[2], argv[3] ) == 0 )
174 mbedtls_fprintf( stderr, "input and output filenames must differ\n" );
178 if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
180 mbedtls_fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
184 if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
186 mbedtls_fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
191 * Read the Cipher and MD from the command line
193 cipher_info = mbedtls_cipher_info_from_string( argv[4] );
194 if( cipher_info == NULL )
196 mbedtls_fprintf( stderr, "Cipher '%s' not found\n", argv[4] );
199 if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info) ) != 0 )
201 mbedtls_fprintf( stderr, "mbedtls_cipher_setup failed\n" );
205 md_info = mbedtls_md_info_from_string( argv[5] );
206 if( md_info == NULL )
208 mbedtls_fprintf( stderr, "Message Digest '%s' not found\n", argv[5] );
212 if( mbedtls_md_setup( &md_ctx, md_info, 1 ) != 0 )
214 mbedtls_fprintf( stderr, "mbedtls_md_setup failed\n" );
219 * Read the secret key from file or command line
221 if( ( fkey = fopen( argv[6], "rb" ) ) != NULL )
223 keylen = fread( key, 1, sizeof( key ), fkey );
228 if( memcmp( argv[6], "hex:", 4 ) == 0 )
233 while( sscanf( p, "%02X", &n ) > 0 &&
234 keylen < (int) sizeof( key ) )
236 key[keylen++] = (unsigned char) n;
242 keylen = strlen( argv[6] );
244 if( keylen > (int) sizeof( key ) )
245 keylen = (int) sizeof( key );
247 memcpy( key, argv[6], keylen );
251 #if defined(_WIN32_WCE)
252 filesize = fseek( fin, 0L, SEEK_END );
256 * Support large files (> 2Gb) on Win32
258 li_size.QuadPart = 0;
260 SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
261 li_size.LowPart, &li_size.HighPart, FILE_END );
263 if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
265 mbedtls_fprintf( stderr, "SetFilePointer(0,FILE_END) failed\n" );
269 filesize = li_size.QuadPart;
271 if( ( filesize = lseek( fileno( fin ), 0, SEEK_END ) ) < 0 )
279 if( fseek( fin, 0, SEEK_SET ) < 0 )
281 mbedtls_fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
285 if( mode == MODE_ENCRYPT )
288 * Generate the initialization vector as:
289 * IV = MD( filesize || filename )[0..15]
291 for( i = 0; i < 8; i++ )
292 buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
296 mbedtls_md_starts( &md_ctx );
297 mbedtls_md_update( &md_ctx, buffer, 8 );
298 mbedtls_md_update( &md_ctx, (unsigned char *) p, strlen( p ) );
299 mbedtls_md_finish( &md_ctx, digest );
301 memcpy( IV, digest, 16 );
304 * Append the IV at the beginning of the output.
306 if( fwrite( IV, 1, 16, fout ) != 16 )
308 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
313 * Hash the IV and the secret key together 8192 times
314 * using the result to setup the AES context and HMAC.
316 memset( digest, 0, 32 );
317 memcpy( digest, IV, 16 );
319 for( i = 0; i < 8192; i++ )
321 mbedtls_md_starts( &md_ctx );
322 mbedtls_md_update( &md_ctx, digest, 32 );
323 mbedtls_md_update( &md_ctx, key, keylen );
324 mbedtls_md_finish( &md_ctx, digest );
328 if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
329 MBEDTLS_ENCRYPT ) != 0 )
331 mbedtls_fprintf( stderr, "mbedtls_cipher_setkey() returned error\n");
334 if( mbedtls_cipher_set_iv( &cipher_ctx, IV, 16 ) != 0 )
336 mbedtls_fprintf( stderr, "mbedtls_cipher_set_iv() returned error\n");
339 if( mbedtls_cipher_reset( &cipher_ctx ) != 0 )
341 mbedtls_fprintf( stderr, "mbedtls_cipher_reset() returned error\n");
345 mbedtls_md_hmac_starts( &md_ctx, digest, 32 );
348 * Encrypt and write the ciphertext.
350 for( offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size( &cipher_ctx ) )
352 ilen = ( (unsigned int) filesize - offset > mbedtls_cipher_get_block_size( &cipher_ctx ) ) ?
353 mbedtls_cipher_get_block_size( &cipher_ctx ) : (unsigned int) ( filesize - offset );
355 if( fread( buffer, 1, ilen, fin ) != ilen )
357 mbedtls_fprintf( stderr, "fread(%ld bytes) failed\n", (long) ilen );
361 if( mbedtls_cipher_update( &cipher_ctx, buffer, ilen, output, &olen ) != 0 )
363 mbedtls_fprintf( stderr, "mbedtls_cipher_update() returned error\n");
367 mbedtls_md_hmac_update( &md_ctx, output, olen );
369 if( fwrite( output, 1, olen, fout ) != olen )
371 mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
376 if( mbedtls_cipher_finish( &cipher_ctx, output, &olen ) != 0 )
378 mbedtls_fprintf( stderr, "mbedtls_cipher_finish() returned error\n" );
381 mbedtls_md_hmac_update( &md_ctx, output, olen );
383 if( fwrite( output, 1, olen, fout ) != olen )
385 mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
390 * Finally write the HMAC.
392 mbedtls_md_hmac_finish( &md_ctx, digest );
394 if( fwrite( digest, 1, mbedtls_md_get_size( md_info ), fout ) != mbedtls_md_get_size( md_info ) )
396 mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", mbedtls_md_get_size( md_info ) );
401 if( mode == MODE_DECRYPT )
404 * The encrypted file must be structured as follows:
406 * 00 .. 15 Initialization Vector
407 * 16 .. 31 Encrypted Block #1
409 * N*16 .. (N+1)*16 - 1 Encrypted Block #N
410 * (N+1)*16 .. (N+1)*16 + n Hash(ciphertext)
412 if( filesize < 16 + mbedtls_md_get_size( md_info ) )
414 mbedtls_fprintf( stderr, "File too short to be encrypted.\n" );
418 if( mbedtls_cipher_get_block_size( &cipher_ctx ) == 0 )
420 mbedtls_fprintf( stderr, "Invalid cipher block size: 0. \n" );
425 * Check the file size.
427 if( cipher_info->mode != MBEDTLS_MODE_GCM &&
428 ( ( filesize - mbedtls_md_get_size( md_info ) ) %
429 mbedtls_cipher_get_block_size( &cipher_ctx ) ) != 0 )
431 mbedtls_fprintf( stderr, "File content not a multiple of the block size (%d).\n",
432 mbedtls_cipher_get_block_size( &cipher_ctx ));
437 * Subtract the IV + HMAC length.
439 filesize -= ( 16 + mbedtls_md_get_size( md_info ) );
442 * Read the IV and original filesize modulo 16.
444 if( fread( buffer, 1, 16, fin ) != 16 )
446 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
450 memcpy( IV, buffer, 16 );
453 * Hash the IV and the secret key together 8192 times
454 * using the result to setup the AES context and HMAC.
456 memset( digest, 0, 32 );
457 memcpy( digest, IV, 16 );
459 for( i = 0; i < 8192; i++ )
461 mbedtls_md_starts( &md_ctx );
462 mbedtls_md_update( &md_ctx, digest, 32 );
463 mbedtls_md_update( &md_ctx, key, keylen );
464 mbedtls_md_finish( &md_ctx, digest );
467 if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
468 MBEDTLS_DECRYPT ) != 0 )
470 mbedtls_fprintf( stderr, "mbedtls_cipher_setkey() returned error\n" );
474 if( mbedtls_cipher_set_iv( &cipher_ctx, IV, 16 ) != 0 )
476 mbedtls_fprintf( stderr, "mbedtls_cipher_set_iv() returned error\n" );
480 if( mbedtls_cipher_reset( &cipher_ctx ) != 0 )
482 mbedtls_fprintf( stderr, "mbedtls_cipher_reset() returned error\n" );
486 mbedtls_md_hmac_starts( &md_ctx, digest, 32 );
489 * Decrypt and write the plaintext.
491 for( offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size( &cipher_ctx ) )
493 ilen = ( (unsigned int) filesize - offset > mbedtls_cipher_get_block_size( &cipher_ctx ) ) ?
494 mbedtls_cipher_get_block_size( &cipher_ctx ) : (unsigned int) ( filesize - offset );
496 if( fread( buffer, 1, ilen, fin ) != ilen )
498 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n",
499 mbedtls_cipher_get_block_size( &cipher_ctx ) );
503 mbedtls_md_hmac_update( &md_ctx, buffer, ilen );
504 if( mbedtls_cipher_update( &cipher_ctx, buffer, ilen, output,
507 mbedtls_fprintf( stderr, "mbedtls_cipher_update() returned error\n" );
511 if( fwrite( output, 1, olen, fout ) != olen )
513 mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
519 * Verify the message authentication code.
521 mbedtls_md_hmac_finish( &md_ctx, digest );
523 if( fread( buffer, 1, mbedtls_md_get_size( md_info ), fin ) != mbedtls_md_get_size( md_info ) )
525 mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", mbedtls_md_get_size( md_info ) );
529 /* Use constant-time buffer comparison */
531 for( i = 0; i < mbedtls_md_get_size( md_info ); i++ )
532 diff |= digest[i] ^ buffer[i];
536 mbedtls_fprintf( stderr, "HMAC check failed: wrong key, "
537 "or file corrupted.\n" );
542 * Write the final block of data
544 mbedtls_cipher_finish( &cipher_ctx, output, &olen );
546 if( fwrite( output, 1, olen, fout ) != olen )
548 mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
553 exit_code = MBEDTLS_EXIT_SUCCESS;
561 /* Zeroize all command line arguments to also cover
562 the case when the user has missed or reordered some,
563 in which case the key might not be in argv[6]. */
564 for( i = 0; i < argc; i++ )
565 mbedtls_platform_zeroize( argv[i], strlen( argv[i] ) );
567 mbedtls_platform_zeroize( IV, sizeof( IV ) );
568 mbedtls_platform_zeroize( key, sizeof( key ) );
569 mbedtls_platform_zeroize( buffer, sizeof( buffer ) );
570 mbedtls_platform_zeroize( output, sizeof( output ) );
571 mbedtls_platform_zeroize( digest, sizeof( digest ) );
573 mbedtls_cipher_free( &cipher_ctx );
574 mbedtls_md_free( &md_ctx );
578 #endif /* MBEDTLS_CIPHER_C && MBEDTLS_MD_C && MBEDTLS_FS_IO */