source: trunk/programs/aes/crypt_and_hash.c @ 1122

Revision 1122, 13.0 KB checked in by paul, 6 months ago (diff)
  • Lots of minimal changes to better support WINCE as a build target
Line 
1/*
2 *  \brief  Generic file encryption program using generic wrappers for configured
3 *          security.
4 *
5 *  Copyright (C) 2006-2011, Brainspark B.V.
6 *
7 *  This file is part of PolarSSL (http://www.polarssl.org)
8 *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
9 *
10 *  All rights reserved.
11 *
12 *  This program is free software; you can redistribute it and/or modify
13 *  it under the terms of the GNU General Public License as published by
14 *  the Free Software Foundation; either version 2 of the License, or
15 *  (at your option) any later version.
16 *
17 *  This program is distributed in the hope that it will be useful,
18 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 *  GNU General Public License for more details.
21 *
22 *  You should have received a copy of the GNU General Public License along
23 *  with this program; if not, write to the Free Software Foundation, Inc.,
24 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 */
26
27#ifndef _CRT_SECURE_NO_DEPRECATE
28#define _CRT_SECURE_NO_DEPRECATE 1
29#endif
30
31#if defined(_WIN32)
32#include <windows.h>
33#if !defined(_WIN32_WCE)
34#include <io.h>
35#endif
36#else
37#include <sys/types.h>
38#include <unistd.h>
39#endif
40
41#include <string.h>
42#include <stdlib.h>
43#include <stdio.h>
44#include <time.h>
45
46#include "polarssl/config.h"
47
48#include "polarssl/cipher.h"
49#include "polarssl/md.h"
50
51#define MODE_ENCRYPT    0
52#define MODE_DECRYPT    1
53
54#define USAGE   \
55    "\n  crypt_and_hash <mode> <input filename> <output filename> <cipher> <md> <key>\n" \
56    "\n   <mode>: 0 = encrypt, 1 = decrypt\n" \
57    "\n  example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
58    "\n"
59
60#if !defined(POLARSSL_CIPHER_C) || !defined(POLARSSL_MD_C)
61int main( int argc, char *argv[] )
62{
63    ((void) argc);
64    ((void) argv);
65
66    printf("POLARSSL_CIPHER_C and/or POLARSSL_MD_C not defined.\n");
67    return( 0 );
68}
69#else
70int main( int argc, char *argv[] )
71{
72    int ret = 1, i, n;
73    int mode, lastn;
74    size_t keylen, ilen, olen;
75    FILE *fkey, *fin = NULL, *fout = NULL;
76
77    char *p;
78    unsigned char IV[16];
79    unsigned char key[512];
80    unsigned char digest[POLARSSL_MD_MAX_SIZE];
81    unsigned char buffer[1024];
82    unsigned char output[1024];
83
84    const cipher_info_t *cipher_info;
85    const md_info_t *md_info;
86    cipher_context_t cipher_ctx;
87    md_context_t md_ctx;
88#if defined(_WIN32_WCE)
89    long filesize, offset;
90#elif defined(_WIN32)
91       LARGE_INTEGER li_size;
92    __int64 filesize, offset;
93#else
94      off_t filesize, offset;
95#endif
96
97    memset( &cipher_ctx, 0, sizeof( cipher_context_t ));
98    memset( &md_ctx, 0, sizeof( md_context_t ));
99
100    /*
101     * Parse the command-line arguments.
102     */
103    if( argc != 7 )
104    {
105        const int *list;
106
107        printf( USAGE );
108
109        printf( "Available ciphers:\n" );
110        list = cipher_list();
111        while( *list )
112        {
113            cipher_info = cipher_info_from_type( *list );
114            printf( "  %s\n", cipher_info->name );
115            list++;
116        }
117
118        printf( "\nAvailable message digests:\n" );
119        list = md_list();
120        while( *list )
121        {
122            md_info = md_info_from_type( *list );
123            printf( "  %s\n", md_info->name );
124            list++;
125        }
126
127#if defined(_WIN32)
128        printf( "\n  Press Enter to exit this program.\n" );
129        fflush( stdout ); getchar();
130#endif
131
132        goto exit;
133    }
134
135    mode = atoi( argv[1] );
136
137    if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
138    {
139        fprintf( stderr, "invalid operation mode\n" );
140        goto exit;
141    }
142
143    if( strcmp( argv[2], argv[3] ) == 0 )
144    {
145        fprintf( stderr, "input and output filenames must differ\n" );
146        goto exit;
147    }
148
149    if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
150    {
151        fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
152        goto exit;
153    }
154
155    if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
156    {
157        fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
158        goto exit;
159    }
160
161    /*
162     * Read the Cipher and MD from the command line
163     */
164    cipher_info = cipher_info_from_string( argv[4] );
165    if( cipher_info == NULL )
166    {
167        fprintf( stderr, "Cipher '%s' not found\n", argv[4] );
168        goto exit;
169    }
170    cipher_init_ctx( &cipher_ctx, cipher_info);
171
172    md_info = md_info_from_string( argv[5] );
173    if( md_info == NULL )
174    {
175        fprintf( stderr, "Message Digest '%s' not found\n", argv[5] );
176        goto exit;
177    }
178    md_init_ctx( &md_ctx, md_info);
179
180    /*
181     * Read the secret key and clean the command line.
182     */
183    if( ( fkey = fopen( argv[6], "rb" ) ) != NULL )
184    {
185        keylen = fread( key, 1, sizeof( key ), fkey );
186        fclose( fkey );
187    }
188    else
189    {
190        if( memcmp( argv[6], "hex:", 4 ) == 0 )
191        {
192            p = &argv[6][4];
193            keylen = 0;
194
195            while( sscanf( p, "%02X", &n ) > 0 &&
196                   keylen < (int) sizeof( key ) )
197            {
198                key[keylen++] = (unsigned char) n;
199                p += 2;
200            }
201        }
202        else
203        {
204            keylen = strlen( argv[6] );
205
206            if( keylen > (int) sizeof( key ) )
207                keylen = (int) sizeof( key );
208
209            memcpy( key, argv[6], keylen );
210        }
211    }
212
213    memset( argv[6], 0, strlen( argv[6] ) );
214
215#if defined(_WIN32_WCE)
216    filesize = fseek( fin, 0L, SEEK_END );
217#else
218#if defined(_WIN32)
219    /*
220     * Support large files (> 2Gb) on Win32
221     */
222    li_size.QuadPart = 0;
223    li_size.LowPart  =
224        SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
225                        li_size.LowPart, &li_size.HighPart, FILE_END );
226
227    if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
228    {
229        fprintf( stderr, "SetFilePointer(0,FILE_END) failed\n" );
230        goto exit;
231    }
232
233    filesize = li_size.QuadPart;
234#else
235    if( ( filesize = lseek( fileno( fin ), 0, SEEK_END ) ) < 0 )
236    {
237        perror( "lseek" );
238        goto exit;
239    }
240#endif
241#endif
242
243    if( fseek( fin, 0, SEEK_SET ) < 0 )
244    {
245        fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
246        goto exit;
247    }
248
249    if( mode == MODE_ENCRYPT )
250    {
251        /*
252         * Generate the initialization vector as:
253         * IV = SHA-256( filesize || filename )[0..15]
254         */
255        for( i = 0; i < 8; i++ )
256            buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
257
258        p = argv[2];
259
260        md_starts( &md_ctx );
261        md_update( &md_ctx, buffer, 8 );
262        md_update( &md_ctx, (unsigned char *) p, strlen( p ) );
263        md_finish( &md_ctx, digest );
264
265        memcpy( IV, digest, 16 );
266
267        /*
268         * The last four bits in the IV are actually used
269         * to store the file size modulo the AES block size.
270         */
271        lastn = (int)( filesize & 0x0F );
272
273        IV[15] = (unsigned char)
274            ( ( IV[15] & 0xF0 ) | lastn );
275
276        /*
277         * Append the IV at the beginning of the output.
278         */
279        if( fwrite( IV, 1, 16, fout ) != 16 )
280        {
281            fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
282            goto exit;
283        }
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
292        for( i = 0; i < 8192; i++ )
293        {
294            md_starts( &md_ctx );
295            md_update( &md_ctx, digest, 32 );
296            md_update( &md_ctx, key, keylen );
297            md_finish( &md_ctx, digest );
298
299        }
300
301        memset( key, 0, sizeof( key ) );
302
303        cipher_setkey( &cipher_ctx, digest, cipher_info->key_length,
304            POLARSSL_ENCRYPT );
305        cipher_reset( &cipher_ctx, IV);
306
307        md_hmac_starts( &md_ctx, digest, 32 );
308
309        /*
310         * Encrypt and write the ciphertext.
311         */
312        for( offset = 0; offset < filesize; offset += cipher_get_block_size( &cipher_ctx ) )
313        {
314            ilen = ( (unsigned int) filesize - offset > cipher_get_block_size( &cipher_ctx ) ) ?
315                cipher_get_block_size( &cipher_ctx ) : (unsigned int) ( filesize - offset );
316
317            if( fread( buffer, 1, ilen, fin ) != ilen )
318            {
319                fprintf( stderr, "fread(%ld bytes) failed\n", (long) n );
320                goto exit;
321            }
322
323            cipher_update( &cipher_ctx, buffer, ilen, output, &olen );
324            md_hmac_update( &md_ctx, output, olen );
325
326            if( fwrite( output, 1, olen, fout ) != olen )
327            {
328                fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
329                goto exit;
330            }
331        }
332
333        cipher_finish( &cipher_ctx, output, &olen );
334        md_hmac_update( &md_ctx, output, olen );
335
336        if( fwrite( output, 1, olen, fout ) != olen )
337        {
338            fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
339            goto exit;
340        }
341        /*
342         * Finally write the HMAC.
343         */
344        md_hmac_finish( &md_ctx, digest );
345
346        if( fwrite( digest, 1, md_get_size( md_info), fout ) != md_get_size( md_info) )
347        {
348            fprintf( stderr, "fwrite(%d bytes) failed\n", md_get_size( md_info) );
349            goto exit;
350        }
351    }
352
353    if( mode == MODE_DECRYPT )
354    {
355        /*
356         *  The encrypted file must be structured as follows:
357         *
358         *        00 .. 15              Initialization Vector
359         *        16 .. 31              AES Encrypted Block #1
360         *           ..
361         *      N*16 .. (N+1)*16 - 1    AES Encrypted Block #N
362         *  (N+1)*16 .. (N+1)*16 + 32   HMAC-SHA-256(ciphertext)
363         */
364        if( filesize < 16 + md_get_size( md_info) )
365        {
366            fprintf( stderr, "File too short to be encrypted.\n" );
367            goto exit;
368        }
369
370        if( ( filesize & 0x0F ) != 0 )
371        {
372            fprintf( stderr, "File size not a multiple of 16.\n" );
373            goto exit;
374        }
375
376        /*
377         * Substract the IV + HMAC length.
378         */
379        filesize -= ( 16 + md_get_size( md_info ) );
380
381        /*
382         * Read the IV and original filesize modulo 16.
383         */
384        if( fread( buffer, 1, 16, fin ) != 16 )
385        {
386            fprintf( stderr, "fread(%d bytes) failed\n", 16 );
387            goto exit;
388        }
389
390        memcpy( IV, buffer, 16 );
391        lastn = IV[15] & 0x0F;
392
393        /*
394         * Hash the IV and the secret key together 8192 times
395         * using the result to setup the AES context and HMAC.
396         */
397        memset( digest, 0,  32 );
398        memcpy( digest, IV, 16 );
399
400        for( i = 0; i < 8192; i++ )
401        {
402            md_starts( &md_ctx );
403            md_update( &md_ctx, digest, 32 );
404            md_update( &md_ctx, key, keylen );
405            md_finish( &md_ctx, digest );
406        }
407
408        memset( key, 0, sizeof( key ) );
409
410        cipher_setkey( &cipher_ctx, digest, cipher_info->key_length,
411            POLARSSL_DECRYPT );
412        cipher_reset( &cipher_ctx, IV);
413
414        md_hmac_starts( &md_ctx, digest, 32 );
415
416        /*
417         * Decrypt and write the plaintext.
418         */
419        for( offset = 0; offset < filesize; offset += cipher_get_block_size( &cipher_ctx ) )
420        {
421            if( fread( buffer, 1, cipher_get_block_size( &cipher_ctx ), fin ) !=
422                (size_t) cipher_get_block_size( &cipher_ctx ) )
423            {
424                fprintf( stderr, "fread(%d bytes) failed\n",
425                    cipher_get_block_size( &cipher_ctx ) );
426                goto exit;
427            }
428
429            md_hmac_update( &md_ctx, buffer, cipher_get_block_size( &cipher_ctx ) );
430            cipher_update( &cipher_ctx, buffer, cipher_get_block_size( &cipher_ctx ),
431                output, &olen );
432
433            if( fwrite( output, 1, olen, fout ) != olen )
434            {
435                fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
436                goto exit;
437            }
438        }
439
440        /*
441         * Write the final block of data
442         */
443        cipher_finish( &cipher_ctx, output, &olen );
444
445        if( fwrite( output, 1, olen, fout ) != olen )
446        {
447            fprintf( stderr, "fwrite(%ld bytes) failed\n", (long) olen );
448            goto exit;
449        }
450
451        /*
452         * Verify the message authentication code.
453         */
454        md_hmac_finish( &md_ctx, digest );
455
456        if( fread( buffer, 1, md_get_size( md_info ), fin ) != md_get_size( md_info ) )
457        {
458            fprintf( stderr, "fread(%d bytes) failed\n", md_get_size( md_info ) );
459            goto exit;
460        }
461
462        if( memcmp( digest, buffer, md_get_size( md_info ) ) != 0 )
463        {
464            fprintf( stderr, "HMAC check failed: wrong key, "
465                             "or file corrupted.\n" );
466            goto exit;
467        }
468    }
469
470    ret = 0;
471
472exit:
473    if( fin )
474        fclose( fin );
475    if( fout )
476        fclose( fout );
477
478    memset( buffer, 0, sizeof( buffer ) );
479    memset( digest, 0, sizeof( digest ) );
480
481    cipher_free_ctx( &cipher_ctx );
482    md_free_ctx( &md_ctx );
483
484    return( ret );
485}
486#endif /* POLARSSL_CIPHER_C && POLARSSL_MD_C */
Note: See TracBrowser for help on using the repository browser.

What are you looking for?