crypt_and_hash.c 17 KB

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