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