crypt_and_hash.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * \brief Generic file encryption program using generic wrappers for configured
  3. * security.
  4. *
  5. * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  6. * SPDX-License-Identifier: Apache-2.0
  7. *
  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
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  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.
  19. *
  20. * This file is part of mbed TLS (https://tls.mbed.org)
  21. */
  22. /* Enable definition of fileno() even when compiling with -std=c99. Must be
  23. * set before config.h, which pulls in glibc's features.h indirectly.
  24. * Harmless on other platforms. */
  25. #define _POSIX_C_SOURCE 1
  26. #if !defined(MBEDTLS_CONFIG_FILE)
  27. #include "mbedtls/config.h"
  28. #else
  29. #include MBEDTLS_CONFIG_FILE
  30. #endif
  31. #if defined(MBEDTLS_PLATFORM_C)
  32. #include "mbedtls/platform.h"
  33. #else
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #define mbedtls_fprintf fprintf
  37. #define mbedtls_printf printf
  38. #define mbedtls_exit exit
  39. #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
  40. #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
  41. #endif /* MBEDTLS_PLATFORM_C */
  42. #if defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_MD_C) && \
  43. defined(MBEDTLS_FS_IO)
  44. #include "mbedtls/cipher.h"
  45. #include "mbedtls/md.h"
  46. #include "mbedtls/platform_util.h"
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <string.h>
  50. #endif
  51. #if defined(_WIN32)
  52. #include <windows.h>
  53. #if !defined(_WIN32_WCE)
  54. #include <io.h>
  55. #endif
  56. #else
  57. #include <sys/types.h>
  58. #include <unistd.h>
  59. #endif
  60. #define MODE_ENCRYPT 0
  61. #define MODE_DECRYPT 1
  62. #define USAGE \
  63. "\n crypt_and_hash <mode> <input filename> <output filename> <cipher> <mbedtls_md> <key>\n" \
  64. "\n <mode>: 0 = encrypt, 1 = decrypt\n" \
  65. "\n example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
  66. "\n"
  67. #if !defined(MBEDTLS_CIPHER_C) || !defined(MBEDTLS_MD_C) || \
  68. !defined(MBEDTLS_FS_IO)
  69. int main( void )
  70. {
  71. mbedtls_printf("MBEDTLS_CIPHER_C and/or MBEDTLS_MD_C and/or MBEDTLS_FS_IO not defined.\n");
  72. return( 0 );
  73. }
  74. #else
  75. int main( int argc, char *argv[] )
  76. {
  77. int ret = 1, i, n;
  78. int exit_code = MBEDTLS_EXIT_FAILURE;
  79. int mode;
  80. size_t keylen, ilen, olen;
  81. FILE *fkey, *fin = NULL, *fout = NULL;
  82. char *p;
  83. unsigned char IV[16];
  84. unsigned char key[512];
  85. unsigned char digest[MBEDTLS_MD_MAX_SIZE];
  86. unsigned char buffer[1024];
  87. unsigned char output[1024];
  88. unsigned char diff;
  89. const mbedtls_cipher_info_t *cipher_info;
  90. const mbedtls_md_info_t *md_info;
  91. mbedtls_cipher_context_t cipher_ctx;
  92. mbedtls_md_context_t md_ctx;
  93. #if defined(_WIN32_WCE)
  94. long filesize, offset;
  95. #elif defined(_WIN32)
  96. LARGE_INTEGER li_size;
  97. __int64 filesize, offset;
  98. #else
  99. off_t filesize, offset;
  100. #endif
  101. mbedtls_cipher_init( &cipher_ctx );
  102. mbedtls_md_init( &md_ctx );
  103. /*
  104. * Parse the command-line arguments.
  105. */
  106. if( argc != 7 )
  107. {
  108. const int *list;
  109. mbedtls_printf( USAGE );
  110. mbedtls_printf( "Available ciphers:\n" );
  111. list = mbedtls_cipher_list();
  112. while( *list )
  113. {
  114. cipher_info = mbedtls_cipher_info_from_type( *list );
  115. mbedtls_printf( " %s\n", cipher_info->name );
  116. list++;
  117. }
  118. mbedtls_printf( "\nAvailable message digests:\n" );
  119. list = mbedtls_md_list();
  120. while( *list )
  121. {
  122. md_info = mbedtls_md_info_from_type( *list );
  123. mbedtls_printf( " %s\n", mbedtls_md_get_name( md_info ) );
  124. list++;
  125. }
  126. #if defined(_WIN32)
  127. mbedtls_printf( "\n Press Enter to exit this program.\n" );
  128. fflush( stdout ); getchar();
  129. #endif
  130. goto exit;
  131. }
  132. mode = atoi( argv[1] );
  133. if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
  134. {
  135. mbedtls_fprintf( stderr, "invalid operation mode\n" );
  136. goto exit;
  137. }
  138. if( strcmp( argv[2], argv[3] ) == 0 )
  139. {
  140. mbedtls_fprintf( stderr, "input and output filenames must differ\n" );
  141. goto exit;
  142. }
  143. if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
  144. {
  145. mbedtls_fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
  146. goto exit;
  147. }
  148. if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
  149. {
  150. mbedtls_fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
  151. goto exit;
  152. }
  153. /*
  154. * Read the Cipher and MD from the command line
  155. */
  156. cipher_info = mbedtls_cipher_info_from_string( argv[4] );
  157. if( cipher_info == NULL )
  158. {
  159. mbedtls_fprintf( stderr, "Cipher '%s' not found\n", argv[4] );
  160. goto exit;
  161. }
  162. if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info) ) != 0 )
  163. {
  164. mbedtls_fprintf( stderr, "mbedtls_cipher_setup failed\n" );
  165. goto exit;
  166. }
  167. md_info = mbedtls_md_info_from_string( argv[5] );
  168. if( md_info == NULL )
  169. {
  170. mbedtls_fprintf( stderr, "Message Digest '%s' not found\n", argv[5] );
  171. goto exit;
  172. }
  173. if( mbedtls_md_setup( &md_ctx, md_info, 1 ) != 0 )
  174. {
  175. mbedtls_fprintf( stderr, "mbedtls_md_setup failed\n" );
  176. goto exit;
  177. }
  178. /*
  179. * Read the secret key from file or command line
  180. */
  181. if( ( fkey = fopen( argv[6], "rb" ) ) != NULL )
  182. {
  183. keylen = fread( key, 1, sizeof( key ), fkey );
  184. fclose( fkey );
  185. }
  186. else
  187. {
  188. if( memcmp( argv[6], "hex:", 4 ) == 0 )
  189. {
  190. p = &argv[6][4];
  191. keylen = 0;
  192. while( sscanf( p, "%02X", &n ) > 0 &&
  193. keylen < (int) sizeof( key ) )
  194. {
  195. key[keylen++] = (unsigned char) n;
  196. p += 2;
  197. }
  198. }
  199. else
  200. {
  201. keylen = strlen( argv[6] );
  202. if( keylen > (int) sizeof( key ) )
  203. keylen = (int) sizeof( key );
  204. memcpy( key, argv[6], keylen );
  205. }
  206. }
  207. #if defined(_WIN32_WCE)
  208. filesize = fseek( fin, 0L, SEEK_END );
  209. #else
  210. #if defined(_WIN32)
  211. /*
  212. * Support large files (> 2Gb) on Win32
  213. */
  214. li_size.QuadPart = 0;
  215. li_size.LowPart =
  216. SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
  217. li_size.LowPart, &li_size.HighPart, FILE_END );
  218. if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
  219. {
  220. mbedtls_fprintf( stderr, "SetFilePointer(0,FILE_END) failed\n" );
  221. goto exit;
  222. }
  223. filesize = li_size.QuadPart;
  224. #else
  225. if( ( filesize = lseek( fileno( fin ), 0, SEEK_END ) ) < 0 )
  226. {
  227. perror( "lseek" );
  228. goto exit;
  229. }
  230. #endif
  231. #endif
  232. if( fseek( fin, 0, SEEK_SET ) < 0 )
  233. {
  234. mbedtls_fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
  235. goto exit;
  236. }
  237. if( mode == MODE_ENCRYPT )
  238. {
  239. /*
  240. * Generate the initialization vector as:
  241. * IV = MD( filesize || filename )[0..15]
  242. */
  243. for( i = 0; i < 8; i++ )
  244. buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
  245. p = argv[2];
  246. mbedtls_md_starts( &md_ctx );
  247. mbedtls_md_update( &md_ctx, buffer, 8 );
  248. mbedtls_md_update( &md_ctx, (unsigned char *) p, strlen( p ) );
  249. mbedtls_md_finish( &md_ctx, digest );
  250. memcpy( IV, digest, 16 );
  251. /*
  252. * Append the IV at the beginning of the output.
  253. */
  254. if( fwrite( IV, 1, 16, fout ) != 16 )
  255. {
  256. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
  257. goto exit;
  258. }
  259. /*
  260. * Hash the IV and the secret key together 8192 times
  261. * using the result to setup the AES context and HMAC.
  262. */
  263. memset( digest, 0, 32 );
  264. memcpy( digest, IV, 16 );
  265. for( i = 0; i < 8192; i++ )
  266. {
  267. mbedtls_md_starts( &md_ctx );
  268. mbedtls_md_update( &md_ctx, digest, 32 );
  269. mbedtls_md_update( &md_ctx, key, keylen );
  270. mbedtls_md_finish( &md_ctx, digest );
  271. }
  272. if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
  273. MBEDTLS_ENCRYPT ) != 0 )
  274. {
  275. mbedtls_fprintf( stderr, "mbedtls_cipher_setkey() returned error\n");
  276. goto exit;
  277. }
  278. if( mbedtls_cipher_set_iv( &cipher_ctx, IV, 16 ) != 0 )
  279. {
  280. mbedtls_fprintf( stderr, "mbedtls_cipher_set_iv() returned error\n");
  281. goto exit;
  282. }
  283. if( mbedtls_cipher_reset( &cipher_ctx ) != 0 )
  284. {
  285. mbedtls_fprintf( stderr, "mbedtls_cipher_reset() returned error\n");
  286. goto exit;
  287. }
  288. mbedtls_md_hmac_starts( &md_ctx, digest, 32 );
  289. /*
  290. * Encrypt and write the ciphertext.
  291. */
  292. for( offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size( &cipher_ctx ) )
  293. {
  294. ilen = ( (unsigned int) filesize - offset > mbedtls_cipher_get_block_size( &cipher_ctx ) ) ?
  295. mbedtls_cipher_get_block_size( &cipher_ctx ) : (unsigned int) ( filesize - offset );
  296. if( fread( buffer, 1, ilen, fin ) != ilen )
  297. {
  298. mbedtls_fprintf( stderr, "fread(%ld bytes) failed\n", (long) ilen );
  299. goto exit;
  300. }
  301. if( mbedtls_cipher_update( &cipher_ctx, buffer, ilen, output, &olen ) != 0 )
  302. {
  303. mbedtls_fprintf( stderr, "mbedtls_cipher_update() returned error\n");
  304. goto exit;
  305. }
  306. mbedtls_md_hmac_update( &md_ctx, output, olen );
  307. if( fwrite( output, 1, olen, fout ) != olen )
  308. {
  309. mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
  310. goto exit;
  311. }
  312. }
  313. if( mbedtls_cipher_finish( &cipher_ctx, output, &olen ) != 0 )
  314. {
  315. mbedtls_fprintf( stderr, "mbedtls_cipher_finish() returned error\n" );
  316. goto exit;
  317. }
  318. mbedtls_md_hmac_update( &md_ctx, output, olen );
  319. if( fwrite( output, 1, olen, fout ) != olen )
  320. {
  321. mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
  322. goto exit;
  323. }
  324. /*
  325. * Finally write the HMAC.
  326. */
  327. mbedtls_md_hmac_finish( &md_ctx, digest );
  328. if( fwrite( digest, 1, mbedtls_md_get_size( md_info ), fout ) != mbedtls_md_get_size( md_info ) )
  329. {
  330. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", mbedtls_md_get_size( md_info ) );
  331. goto exit;
  332. }
  333. }
  334. if( mode == MODE_DECRYPT )
  335. {
  336. /*
  337. * The encrypted file must be structured as follows:
  338. *
  339. * 00 .. 15 Initialization Vector
  340. * 16 .. 31 Encrypted Block #1
  341. * ..
  342. * N*16 .. (N+1)*16 - 1 Encrypted Block #N
  343. * (N+1)*16 .. (N+1)*16 + n Hash(ciphertext)
  344. */
  345. if( filesize < 16 + mbedtls_md_get_size( md_info ) )
  346. {
  347. mbedtls_fprintf( stderr, "File too short to be encrypted.\n" );
  348. goto exit;
  349. }
  350. if( mbedtls_cipher_get_block_size( &cipher_ctx ) == 0 )
  351. {
  352. mbedtls_fprintf( stderr, "Invalid cipher block size: 0. \n" );
  353. goto exit;
  354. }
  355. /*
  356. * Check the file size.
  357. */
  358. if( cipher_info->mode != MBEDTLS_MODE_GCM &&
  359. ( ( filesize - mbedtls_md_get_size( md_info ) ) %
  360. mbedtls_cipher_get_block_size( &cipher_ctx ) ) != 0 )
  361. {
  362. mbedtls_fprintf( stderr, "File content not a multiple of the block size (%d).\n",
  363. mbedtls_cipher_get_block_size( &cipher_ctx ));
  364. goto exit;
  365. }
  366. /*
  367. * Subtract the IV + HMAC length.
  368. */
  369. filesize -= ( 16 + mbedtls_md_get_size( md_info ) );
  370. /*
  371. * Read the IV and original filesize modulo 16.
  372. */
  373. if( fread( buffer, 1, 16, fin ) != 16 )
  374. {
  375. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
  376. goto exit;
  377. }
  378. memcpy( IV, buffer, 16 );
  379. /*
  380. * Hash the IV and the secret key together 8192 times
  381. * using the result to setup the AES context and HMAC.
  382. */
  383. memset( digest, 0, 32 );
  384. memcpy( digest, IV, 16 );
  385. for( i = 0; i < 8192; i++ )
  386. {
  387. mbedtls_md_starts( &md_ctx );
  388. mbedtls_md_update( &md_ctx, digest, 32 );
  389. mbedtls_md_update( &md_ctx, key, keylen );
  390. mbedtls_md_finish( &md_ctx, digest );
  391. }
  392. if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
  393. MBEDTLS_DECRYPT ) != 0 )
  394. {
  395. mbedtls_fprintf( stderr, "mbedtls_cipher_setkey() returned error\n" );
  396. goto exit;
  397. }
  398. if( mbedtls_cipher_set_iv( &cipher_ctx, IV, 16 ) != 0 )
  399. {
  400. mbedtls_fprintf( stderr, "mbedtls_cipher_set_iv() returned error\n" );
  401. goto exit;
  402. }
  403. if( mbedtls_cipher_reset( &cipher_ctx ) != 0 )
  404. {
  405. mbedtls_fprintf( stderr, "mbedtls_cipher_reset() returned error\n" );
  406. goto exit;
  407. }
  408. mbedtls_md_hmac_starts( &md_ctx, digest, 32 );
  409. /*
  410. * Decrypt and write the plaintext.
  411. */
  412. for( offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size( &cipher_ctx ) )
  413. {
  414. ilen = ( (unsigned int) filesize - offset > mbedtls_cipher_get_block_size( &cipher_ctx ) ) ?
  415. mbedtls_cipher_get_block_size( &cipher_ctx ) : (unsigned int) ( filesize - offset );
  416. if( fread( buffer, 1, ilen, fin ) != ilen )
  417. {
  418. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n",
  419. mbedtls_cipher_get_block_size( &cipher_ctx ) );
  420. goto exit;
  421. }
  422. mbedtls_md_hmac_update( &md_ctx, buffer, ilen );
  423. if( mbedtls_cipher_update( &cipher_ctx, buffer, ilen, output,
  424. &olen ) != 0 )
  425. {
  426. mbedtls_fprintf( stderr, "mbedtls_cipher_update() returned error\n" );
  427. goto exit;
  428. }
  429. if( fwrite( output, 1, olen, fout ) != olen )
  430. {
  431. mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
  432. goto exit;
  433. }
  434. }
  435. /*
  436. * Verify the message authentication code.
  437. */
  438. mbedtls_md_hmac_finish( &md_ctx, digest );
  439. if( fread( buffer, 1, mbedtls_md_get_size( md_info ), fin ) != mbedtls_md_get_size( md_info ) )
  440. {
  441. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", mbedtls_md_get_size( md_info ) );
  442. goto exit;
  443. }
  444. /* Use constant-time buffer comparison */
  445. diff = 0;
  446. for( i = 0; i < mbedtls_md_get_size( md_info ); i++ )
  447. diff |= digest[i] ^ buffer[i];
  448. if( diff != 0 )
  449. {
  450. mbedtls_fprintf( stderr, "HMAC check failed: wrong key, "
  451. "or file corrupted.\n" );
  452. goto exit;
  453. }
  454. /*
  455. * Write the final block of data
  456. */
  457. mbedtls_cipher_finish( &cipher_ctx, output, &olen );
  458. if( fwrite( output, 1, olen, fout ) != olen )
  459. {
  460. mbedtls_fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
  461. goto exit;
  462. }
  463. }
  464. exit_code = MBEDTLS_EXIT_SUCCESS;
  465. exit:
  466. if( fin )
  467. fclose( fin );
  468. if( fout )
  469. fclose( fout );
  470. /* Zeroize all command line arguments to also cover
  471. the case when the user has missed or reordered some,
  472. in which case the key might not be in argv[6]. */
  473. for( i = 0; i < argc; i++ )
  474. mbedtls_platform_zeroize( argv[i], strlen( argv[i] ) );
  475. mbedtls_platform_zeroize( IV, sizeof( IV ) );
  476. mbedtls_platform_zeroize( key, sizeof( key ) );
  477. mbedtls_platform_zeroize( buffer, sizeof( buffer ) );
  478. mbedtls_platform_zeroize( output, sizeof( output ) );
  479. mbedtls_platform_zeroize( digest, sizeof( digest ) );
  480. mbedtls_cipher_free( &cipher_ctx );
  481. mbedtls_md_free( &md_ctx );
  482. return( exit_code );
  483. }
  484. #endif /* MBEDTLS_CIPHER_C && MBEDTLS_MD_C && MBEDTLS_FS_IO */