Commit f1674502 authored by Roy Marmelstein's avatar Roy Marmelstein

Delete minizip

parent a4ce93c6
More changes since 1.1
- Added support for AE-2 zip files
- Fixed error in AE-1 not testing CRC32
Credits
Steven Christy
Changes since 1.1
- Added PKZIP spanning support
- Added AES encryption support
- Added I/O buffering
- Clean up & changed unzLocateFile to support custom comparison function
- Clean up, removed zipRemoveExtraInfoBlock
Credits
Nathan Moinvaziri
Change in 1.1
- Added ZIP64 support for unzip ( by Even Rouault )
- Added ZIP64 support for zip ( by Mathias Svensson )
- Reverted some changed that Even Rouault did.
- Bunch of patches received from Gulles Vollant that he received for MiniZip from various users.
- Added unzip patch for BZIP Compression method (patch create by Daniel Borca)
- Added BZIP Compress method for zip
- Did some refactoring and code cleanup
Credits
Gilles Vollant - Original MiniZip author
Even Rouault - ZIP64 unzip Support
2007-2008
- Addition of cpl_unzGetCurrentFileZStreamPos
- Decoration of symbol names unz* -> cpl_unz*
- Remove old C style function prototypes
- Add unzip support for ZIP64
Daniel Borca - BZip Compression method support in unzip
Mathias Svensson - ZIP64 zip support ( http://result42.com )
Oct-2009 unzip.c
- Removed cpl_* from symbol names
- Fixed problem if uncompressed size was > 4G and compressed size was <4G
should only read the compressed/uncompressed size from the Zip64 format if
the size from normal header was 0xffffffff
- Applied some bug fixes from patches received from Gilles Vollant
- Applied support to unzip files with compression method BZIP2 (bzip2 lib is required)
Patch created by Daniel Borca
Oct-2009 zip.c
- Remove old C style function prototypes
- Added Zip64 Support when creating new file archives
- Did some code cleanup and refactoring to get better overview of some functions.
- Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data
It is used when recreting zip archive with RAW when deleting items from a zip.
ZIP64 data is automaticly added to items that needs it, and existing ZIP64
data need to be removed.
- Added support for BZIP2 as compression mode (bzip2 lib is required)
Oct-2009 ioapi.x
- Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux.
- Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
More if/def section may be needed to support other platforms
- Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
(but you should use iowin32.c for windows instead)
Change in 1.01e (12 feb 05)
- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter)
- Fix possible memory leak in unzip.c (Zoran Stevanovic)
Change in 1.01b (20 may 04)
- Integrate patch from Debian package (Mark Brown)
- Add tools mztools from Xavier Roche
Change in 1.01 (8 may 04)
- Fix buffer overrun risk in unzip.c (Xavier Roche)
- Fix a minor buffer insecurity in minizip.c (Mike Whittaker)
Change in 1.00: (10 sept 03)
- Rename to 1.00
- Cosmetic code change
Change in 0.22: (19 May 03)
- Crypting support (unless you define NOCRYPT)
- Append file in existing zipfile
Change in 0.21: (10 Mar 03)
- Bug fixes
Change in 0.17: (27 Jan 02)
- Bug fixes
Change in 0.16: (19 Jan 02)
- Support of ioapi for virtualize zip file access
Change in 0.15: (19 Mar 98)
- Fix memory leak in minizip.c
Change in 0.14: (10 Mar 98)
- Fix bugs in minizip.c sample for zipping big file
- Fix problem in month in date handling
- Fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for comment handling
Change in 0.13: (6 Mar 98)
- Fix bugs in zip.c
- Add real minizip sample
Change in 0.12: (4 Mar 98)
- Add zip.c and zip.h for creates .zip file
- Fix change_file_date in miniunz.c for Unix (Jean-loup Gailly)
- Fix miniunz.c for file without specific record for directory
Change in 0.11: (3 Mar 98)
- Fix bug in unzGetCurrentFileInfo for get extra field and comment
- Enhance miniunz sample, remove the bad unztst.c sample
Change in 0.10: (2 Mar 98)
- Fix bug in unzReadCurrentFile
- Rename unzip* to unz* function and structure
- Remove Windows-like hungary notation variable name
- Modify some structure in unzip.h
- Add somes comment in source
- Remove unzipGetcCurrentFile function
- Replace ZUNZEXPORT by ZEXPORT
- Add unzGetLocalExtrafield for get the local extrafield info
- Add a new sample, miniunz.c
Change in 0.4: (25 Feb 98)
- Suppress the type unzipFileInZip.
Only on file in the zipfile can be open at the same time
- Fix somes typo in code
- Added tm_unz structure in unzip_file_info (date/time in readable format)
Change unknown?
- Added unzGetOffset (RX '2004)
- Added unzGetFilePos & unzGoToFilePos (Ryan Haksi)
- Added unzGetCurrentFileZStreamPos64 (GDAL)
#ifndef SSZipCommon
#define SSZipCommon
/* tm_unz contain date/time info */
typedef struct tm_unz_s
{
unsigned int tm_sec; /* seconds after the minute - [0,59] */
unsigned int tm_min; /* minutes after the hour - [0,59] */
unsigned int tm_hour; /* hours since midnight - [0,23] */
unsigned int tm_mday; /* day of the month - [1,31] */
unsigned int tm_mon; /* months since January - [0,11] */
unsigned int tm_year; /* years - [1980..2044] */
} tm_unz;
typedef struct unz_file_info_s
{
unsigned long version; /* version made by 2 bytes */
unsigned long version_needed; /* version needed to extract 2 bytes */
unsigned long flag; /* general purpose bit flag 2 bytes */
unsigned long compression_method; /* compression method 2 bytes */
unsigned long dosDate; /* last mod file date in Dos fmt 4 bytes */
unsigned long crc; /* crc-32 4 bytes */
unsigned long compressed_size; /* compressed size 4 bytes */
unsigned long uncompressed_size; /* uncompressed size 4 bytes */
unsigned long size_filename; /* filename length 2 bytes */
unsigned long size_file_extra; /* extra field length 2 bytes */
unsigned long size_file_comment; /* file comment length 2 bytes */
unsigned long disk_num_start; /* disk number start 2 bytes */
unsigned long internal_fa; /* internal file attributes 2 bytes */
unsigned long external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info;
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info64_s
{
unsigned long version; /* version made by 2 bytes */
unsigned long version_needed; /* version needed to extract 2 bytes */
unsigned long flag; /* general purpose bit flag 2 bytes */
unsigned long compression_method; /* compression method 2 bytes */
unsigned long dosDate; /* last mod file date in Dos fmt 4 bytes */
unsigned long crc; /* crc-32 4 bytes */
unsigned long long compressed_size; /* compressed size 8 bytes */
unsigned long long uncompressed_size; /* uncompressed size 8 bytes */
unsigned long size_filename; /* filename length 2 bytes */
unsigned long size_file_extra; /* extra field length 2 bytes */
unsigned long size_file_comment; /* file comment length 2 bytes */
unsigned long disk_num_start; /* disk number start 2 bytes */
unsigned long internal_fa; /* internal file attributes 2 bytes */
unsigned long external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
unsigned long long disk_offset;
unsigned long size_file_extra_internal;
} unz_file_info64;
typedef struct unz_global_info_s
{
unsigned long number_entry; /* total number of entries in
the central dir on this disk */
unsigned long number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
unsigned long size_comment; /* size of the global comment of the zipfile */
} unz_global_info;
typedef struct unz_global_info64
{
unsigned long long number_entry; /* total number of entries in
the central dir on this disk */
unsigned long number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
unsigned long size_comment; /* size of the global comment of the zipfile */
} unz_global_info64;
#endif
\ No newline at end of file
Condition of use and distribution are the same as zlib:
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
\ No newline at end of file
CC=cc
CFLAGS=-O -I../.. -DHAVE_AES
UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a libaes.a
ZIP_OBJS = minizip.o zip.o ioapi.o ../../libz.a libaes.a
TEST_FILES = test.zip readme.old readme.txt
.c.o:
$(CC) -c $(CFLAGS) $*.c
all: miniunz minizip
libaes.a:
cd aes; $(MAKE) $(MFLAGS)
miniunz: $(UNZ_OBJS) libaes.a
$(CC) $(CFLAGS) -o $@ $(UNZ_OBJS)
minizip: $(ZIP_OBJS) libaes.a
$(CC) $(CFLAGS) -o $@ $(ZIP_OBJS)
.PHONY: test clean
test: miniunz minizip
@rm -f $(TEST_FILES)
@cp README.md readme.txt
@touch -t 200712301223.44 readme.txt
./minizip test.zip readme.txt
./miniunz -l test.zip
mv readme.txt readme.old
./miniunz test.zip
@diff -q README.md readme.txt || echo "Test failed: files differ"
@[[ "$$(stat -c %Y readme.txt)" = "$$(stat -c %Y readme.old)" ]] || echo "Test failed: timestamp not preserved"
@rm -f $(TEST_FILES)
clean:
/bin/rm -f *.o *~ minizip miniunz $(TEST_FILES)
lib_LTLIBRARIES = libminizip.la
if COND_DEMOS
bin_PROGRAMS = miniunzip minizip
endif
zlib_top_srcdir = $(top_srcdir)/../..
zlib_top_builddir = $(top_builddir)/../..
AM_CPPFLAGS = -I$(zlib_top_srcdir)
AM_LDFLAGS = -L$(zlib_top_builddir)
if WIN32
iowin32_src = iowin32.c
iowin32_h = iowin32.h
endif
libminizip_la_SOURCES = \
ioapi.c \
unzip.c \
zip.c \
${iowin32_src}
libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz
minizip_includedir = $(includedir)/minizip
minizip_include_HEADERS = \
crypt.h \
ioapi.h \
unzip.h \
zip.h \
${iowin32_h}
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = minizip.pc
EXTRA_PROGRAMS = miniunzip minizip
miniunzip_SOURCES = miniunz.c
miniunzip_LDADD = libminizip.la
minizip_SOURCES = minizip.c
minizip_LDADD = libminizip.la -lz
Minizip zlib contribution that includes:
- AES encryption
- I/O buffering
- PKWARE disk spanning
- Visual Studio 2008 project files
It also has the latest bug fixes that having been found all over the internet including the minizip forum and zlib developer's mailing list.
*AES Encryption*
+ Requires #define HAVE_AES
+ Requires AES library files
When zipping with a password it will always use AES 256-bit encryption.
When unzipping it will use AES decryption only if necessary.
*I/O Buffering*
Improves I/O performance by buffering read and write operations.
```
zlib_filefunc64_def filefunc64 = {0};
ourbuffer_t buffered = {0};
fill_win32_filefunc64(&buffered->filefunc64);
fill_buffer_filefunc64(&filefunc64, buffered);
unzOpen2_64(filename, &filefunc64)
```
*PKWARE disk spanning*
To create an archive with multiple disks use zipOpen3_64 supplying a disk_size value in bytes.
```
extern zipFile ZEXPORT zipOpen3_64 OF((const void *pathname, int append,
ZPOS64_T disk_size, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def));
```
The central directory is the only data stored in the .zip and doesn't follow disk_size restrictions.
When unzipping it will automatically determine when in needs to span disks.
*I/O Memory*
To unzip from a zip file in memory use fill_memory_filefunc and supply a proper ourmemory_t structure.
```
zlib_filefunc_def filefunc32 = {0};
ourmemory_t unzmem = {0};
unzmem.size = bufsize;
unzmem.base = (char *)malloc(unzmem.size);
memcpy(unzmem.base, buffer, unzmem.size);
fill_memory_filefunc(&filefunc32, &unzmem);
unzOpen2("__notused__", &filefunc32);
```
To create a zip file in memory use fill_memory_filefunc and supply a proper ourmemory_t structure. It is important
not to forget to free zipmem->base when finished. If grow is set, zipmem->base will expand to fit the size of the zip.
If grow is not set be sure to fill out zipmem.base and zipmem.size.
```
zlib_filefunc_def filefunc32 = {0};
ourmemory_t zipmem = {0};
zipmem.grow = 1;
fill_memory_filefunc(&filefunc32, &zipmem);
zipOpen3("__notused__", APPEND_STATUS_CREATE, 0, 0, &filefunc32);
```
*BZIP2*
+ Requires #define HAVE_BZIP2
+ Requires BZIP2 library
*Windows RT*
+ Requires #define IOWIN32_USING_WINRT_API
CC=cc
CFLAGS=-O -DHAVE_AES
OBJS=aescrypt.o aeskey.o aestab.o entropy.o fileenc.o hmac.o prng.o pwd2key.o sha1.o
ARFLAGS=rv
.c.o:
$(CC) -c $(CFLAGS) $*.c
libaes.a: $(OBJS)
$(ECHO) $(AR) $(ARFLAGS) ../libaes.a $?
$(AR) $(ARFLAGS) ../libaes.a $?
$(RANLIB) ../libaes.a
all: libaes.a
.PHONY: clean
clean:
rm *.o *.a
\ No newline at end of file
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
This file contains the definitions required to use AES in C. See aesopt.h
for optimisation details.
*/
#ifndef _AES_H
#define _AES_H
#include <stdlib.h>
/* This include is used to find 8 & 32 bit unsigned integer types */
#include "brg_types.h"
#if defined(__cplusplus)
extern "C"
{
#endif
#define AES_128 /* if a fast 128 bit key scheduler is needed */
#define AES_192 /* if a fast 192 bit key scheduler is needed */
#define AES_256 /* if a fast 256 bit key scheduler is needed */
#define AES_VAR /* if variable key size scheduler is needed */
#define AES_MODES /* if support is needed for modes */
/* The following must also be set in assembler files if being used */
#define AES_ENCRYPT /* if support for encryption is needed */
#define AES_DECRYPT /* if support for decryption is needed */
#define AES_REV_DKS /* define to reverse decryption key schedule */
#define AES_BLOCK_SIZE 16 /* the AES block size in bytes */
#define N_COLS 4 /* the number of columns in the state */
/* The key schedule length is 11, 13 or 15 16-byte blocks for 128, */
/* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes */
/* or 44, 52 or 60 32-bit words. */
#if defined( AES_VAR ) || defined( AES_256 )
#define KS_LENGTH 60
#elif defined( AES_192 )
#define KS_LENGTH 52
#else
#define KS_LENGTH 44
#endif
#define AES_RETURN INT_RETURN
/* the character array 'inf' in the following structures is used */
/* to hold AES context information. This AES code uses cx->inf.b[0] */
/* to hold the number of rounds multiplied by 16. The other three */
/* elements can be used by code that implements additional modes */
typedef union
{ uint_32t l;
uint_8t b[4];
} aes_inf;
typedef struct
{ uint_32t ks[KS_LENGTH];
aes_inf inf;
} aes_encrypt_ctx;
typedef struct
{ uint_32t ks[KS_LENGTH];
aes_inf inf;
} aes_decrypt_ctx;
/* This routine must be called before first use if non-static */
/* tables are being used */
AES_RETURN aes_init(void);
/* Key lengths in the range 16 <= key_len <= 32 are given in bytes, */
/* those in the range 128 <= key_len <= 256 are given in bits */
#if defined( AES_ENCRYPT )
#if defined( AES_128 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_192 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_256 ) || defined( AES_VAR)
AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_VAR )
AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]);
#endif
AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]);
#endif
#if defined( AES_DECRYPT )
#if defined( AES_128 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_192 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_256 ) || defined( AES_VAR)
AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_VAR )
AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]);
#endif
AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]);
#endif
#if defined( AES_MODES )
/* Multiple calls to the following subroutines for multiple block */
/* ECB, CBC, CFB, OFB and CTR mode encryption can be used to handle */
/* long messages incremantally provided that the context AND the iv */
/* are preserved between all such calls. For the ECB and CBC modes */
/* each individual call within a series of incremental calls must */
/* process only full blocks (i.e. len must be a multiple of 16) but */
/* the CFB, OFB and CTR mode calls can handle multiple incremental */
/* calls of any length. Each mode is reset when a new AES key is */
/* set but ECB and CBC operations can be reset without setting a */
/* new key by setting a new IV value. To reset CFB, OFB and CTR */
/* without setting the key, aes_mode_reset() must be called and the */
/* IV must be set. NOTE: All these calls update the IV on exit so */
/* this has to be reset if a new operation with the same IV as the */
/* previous one is required (or decryption follows encryption with */
/* the same IV array). */
AES_RETURN aes_test_alignment_detection(unsigned int n);
AES_RETURN aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, const aes_encrypt_ctx cx[1]);
AES_RETURN aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, const aes_decrypt_ctx cx[1]);
AES_RETURN aes_cbc_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, const aes_encrypt_ctx cx[1]);
AES_RETURN aes_cbc_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, const aes_decrypt_ctx cx[1]);
AES_RETURN aes_mode_reset(aes_encrypt_ctx cx[1]);
AES_RETURN aes_cfb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
AES_RETURN aes_cfb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
#define aes_ofb_encrypt aes_ofb_crypt
#define aes_ofb_decrypt aes_ofb_crypt
AES_RETURN aes_ofb_crypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
typedef void cbuf_inc(unsigned char *cbuf);
#define aes_ctr_encrypt aes_ctr_crypt
#define aes_ctr_decrypt aes_ctr_crypt
AES_RETURN aes_ctr_crypt(const unsigned char *ibuf, unsigned char *obuf,
int len, unsigned char *cbuf, cbuf_inc ctr_inc, aes_encrypt_ctx cx[1]);
#endif
#if defined(__cplusplus)
}
#endif
#endif
This diff is collapsed.
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
*/
#include "aesopt.h"
#include "aestab.h"
#if defined(__cplusplus)
extern "C"
{
#endif
#define si(y,x,k,c) (s(y,c) = word_in(x, c) ^ (k)[c])
#define so(y,x,c) word_out(y, c, s(x,c))
#if defined(ARRAYS)
#define locals(y,x) x[4],y[4]
#else
#define locals(y,x) x##0,x##1,x##2,x##3,y##0,y##1,y##2,y##3
#endif
#define l_copy(y, x) s(y,0) = s(x,0); s(y,1) = s(x,1); \
s(y,2) = s(x,2); s(y,3) = s(x,3);
#define state_in(y,x,k) si(y,x,k,0); si(y,x,k,1); si(y,x,k,2); si(y,x,k,3)
#define state_out(y,x) so(y,x,0); so(y,x,1); so(y,x,2); so(y,x,3)
#define round(rm,y,x,k) rm(y,x,k,0); rm(y,x,k,1); rm(y,x,k,2); rm(y,x,k,3)
#if ( FUNCS_IN_C & ENCRYPTION_IN_C )
/* Visual C++ .Net v7.1 provides the fastest encryption code when using
Pentium optimiation with small code but this is poor for decryption
so we need to control this with the following VC++ pragmas
*/
#if defined( _MSC_VER ) && !defined( _WIN64 )
#pragma optimize( "s", on )
#endif
/* Given the column (c) of the output state variable, the following
macros give the input state variables which are needed in its
computation for each row (r) of the state. All the alternative
macros give the same end values but expand into different ways
of calculating these values. In particular the complex macro
used for dynamically variable block sizes is designed to expand
to a compile time constant whenever possible but will expand to
conditional clauses on some branches (I am grateful to Frank
Yellin for this construction)
*/
#define fwd_var(x,r,c)\
( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\
: r == 1 ? ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))\
: r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\
: ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2)))
#if defined(FT4_SET)
#undef dec_fmvars
#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,n),fwd_var,rf1,c))
#elif defined(FT1_SET)
#undef dec_fmvars
#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(f,n),fwd_var,rf1,c))
#else
#define fwd_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ fwd_mcol(no_table(x,t_use(s,box),fwd_var,rf1,c)))
#endif
#if defined(FL4_SET)
#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(f,l),fwd_var,rf1,c))
#elif defined(FL1_SET)
#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(f,l),fwd_var,rf1,c))
#else
#define fwd_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(s,box),fwd_var,rf1,c))
#endif
AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1])
{ uint_32t locals(b0, b1);
const uint_32t *kp;
#if defined( dec_fmvars )
dec_fmvars; /* declare variables for fwd_mcol() if needed */
#endif
if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 )
return EXIT_FAILURE;
kp = cx->ks;
state_in(b0, in, kp);
#if (ENC_UNROLL == FULL)
switch(cx->inf.b[0])
{
case 14 * 16:
round(fwd_rnd, b1, b0, kp + 1 * N_COLS);
round(fwd_rnd, b0, b1, kp + 2 * N_COLS);
kp += 2 * N_COLS;
case 12 * 16:
round(fwd_rnd, b1, b0, kp + 1 * N_COLS);
round(fwd_rnd, b0, b1, kp + 2 * N_COLS);
kp += 2 * N_COLS;
case 10 * 16:
round(fwd_rnd, b1, b0, kp + 1 * N_COLS);
round(fwd_rnd, b0, b1, kp + 2 * N_COLS);
round(fwd_rnd, b1, b0, kp + 3 * N_COLS);
round(fwd_rnd, b0, b1, kp + 4 * N_COLS);
round(fwd_rnd, b1, b0, kp + 5 * N_COLS);
round(fwd_rnd, b0, b1, kp + 6 * N_COLS);
round(fwd_rnd, b1, b0, kp + 7 * N_COLS);
round(fwd_rnd, b0, b1, kp + 8 * N_COLS);
round(fwd_rnd, b1, b0, kp + 9 * N_COLS);
round(fwd_lrnd, b0, b1, kp +10 * N_COLS);
}
#else
#if (ENC_UNROLL == PARTIAL)
{ uint_32t rnd;
for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd)
{
kp += N_COLS;
round(fwd_rnd, b1, b0, kp);
kp += N_COLS;
round(fwd_rnd, b0, b1, kp);
}
kp += N_COLS;
round(fwd_rnd, b1, b0, kp);
#else
{ uint_32t rnd;
for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd)
{
kp += N_COLS;
round(fwd_rnd, b1, b0, kp);
l_copy(b0, b1);
}
#endif
kp += N_COLS;
round(fwd_lrnd, b0, b1, kp);
}
#endif
state_out(out, b0);
return EXIT_SUCCESS;
}
#endif
#if ( FUNCS_IN_C & DECRYPTION_IN_C)
/* Visual C++ .Net v7.1 provides the fastest encryption code when using
Pentium optimiation with small code but this is poor for decryption
so we need to control this with the following VC++ pragmas
*/
#if defined( _MSC_VER ) && !defined( _WIN64 )
#pragma optimize( "t", on )
#endif
/* Given the column (c) of the output state variable, the following
macros give the input state variables which are needed in its
computation for each row (r) of the state. All the alternative
macros give the same end values but expand into different ways
of calculating these values. In particular the complex macro
used for dynamically variable block sizes is designed to expand
to a compile time constant whenever possible but will expand to
conditional clauses on some branches (I am grateful to Frank
Yellin for this construction)
*/
#define inv_var(x,r,c)\
( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\
: r == 1 ? ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))\
: r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\
: ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0)))
#if defined(IT4_SET)
#undef dec_imvars
#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,n),inv_var,rf1,c))
#elif defined(IT1_SET)
#undef dec_imvars
#define inv_rnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,upr,t_use(i,n),inv_var,rf1,c))
#else
#define inv_rnd(y,x,k,c) (s(y,c) = inv_mcol((k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c)))
#endif
#if defined(IL4_SET)
#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ four_tables(x,t_use(i,l),inv_var,rf1,c))
#elif defined(IL1_SET)
#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ one_table(x,ups,t_use(i,l),inv_var,rf1,c))
#else
#define inv_lrnd(y,x,k,c) (s(y,c) = (k)[c] ^ no_table(x,t_use(i,box),inv_var,rf1,c))
#endif
/* This code can work with the decryption key schedule in the */
/* order that is used for encrytpion (where the 1st decryption */
/* round key is at the high end ot the schedule) or with a key */
/* schedule that has been reversed to put the 1st decryption */
/* round key at the low end of the schedule in memory (when */
/* AES_REV_DKS is defined) */
#ifdef AES_REV_DKS
#define key_ofs 0
#define rnd_key(n) (kp + n * N_COLS)
#else
#define key_ofs 1
#define rnd_key(n) (kp - n * N_COLS)
#endif
AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1])
{ uint_32t locals(b0, b1);
#if defined( dec_imvars )
dec_imvars; /* declare variables for inv_mcol() if needed */
#endif
const uint_32t *kp;
if( cx->inf.b[0] != 10 * 16 && cx->inf.b[0] != 12 * 16 && cx->inf.b[0] != 14 * 16 )
return EXIT_FAILURE;
kp = cx->ks + (key_ofs ? (cx->inf.b[0] >> 2) : 0);
state_in(b0, in, kp);
#if (DEC_UNROLL == FULL)
kp = cx->ks + (key_ofs ? 0 : (cx->inf.b[0] >> 2));
switch(cx->inf.b[0])
{
case 14 * 16:
round(inv_rnd, b1, b0, rnd_key(-13));
round(inv_rnd, b0, b1, rnd_key(-12));
case 12 * 16:
round(inv_rnd, b1, b0, rnd_key(-11));
round(inv_rnd, b0, b1, rnd_key(-10));
case 10 * 16:
round(inv_rnd, b1, b0, rnd_key(-9));
round(inv_rnd, b0, b1, rnd_key(-8));
round(inv_rnd, b1, b0, rnd_key(-7));
round(inv_rnd, b0, b1, rnd_key(-6));
round(inv_rnd, b1, b0, rnd_key(-5));
round(inv_rnd, b0, b1, rnd_key(-4));
round(inv_rnd, b1, b0, rnd_key(-3));
round(inv_rnd, b0, b1, rnd_key(-2));
round(inv_rnd, b1, b0, rnd_key(-1));
round(inv_lrnd, b0, b1, rnd_key( 0));
}
#else
#if (DEC_UNROLL == PARTIAL)
{ uint_32t rnd;
for(rnd = 0; rnd < (cx->inf.b[0] >> 5) - 1; ++rnd)
{
kp = rnd_key(1);
round(inv_rnd, b1, b0, kp);
kp = rnd_key(1);
round(inv_rnd, b0, b1, kp);
}
kp = rnd_key(1);
round(inv_rnd, b1, b0, kp);
#else
{ uint_32t rnd;
for(rnd = 0; rnd < (cx->inf.b[0] >> 4) - 1; ++rnd)
{
kp = rnd_key(1);
round(inv_rnd, b1, b0, kp);
l_copy(b0, b1);
}
#endif
kp = rnd_key(1);
round(inv_lrnd, b0, b1, kp);
}
#endif
state_out(out, b0);
return EXIT_SUCCESS;
}
#endif
#if defined(__cplusplus)
}
#endif
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
This file contains the code for declaring the tables needed to implement
AES. The file aesopt.h is assumed to be included before this header file.
If there are no global variables, the definitions here can be used to put
the AES tables in a structure so that a pointer can then be added to the
AES context to pass them to the AES routines that need them. If this
facility is used, the calling program has to ensure that this pointer is
managed appropriately. In particular, the value of the t_dec(in,it) item
in the table structure must be set to zero in order to ensure that the
tables are initialised. In practice the three code sequences in aeskey.c
that control the calls to aes_init() and the aes_init() routine itself will
have to be changed for a specific implementation. If global variables are
available it will generally be preferable to use them with the precomputed
FIXED_TABLES option that uses static global tables.
The following defines can be used to control the way the tables
are defined, initialised and used in embedded environments that
require special features for these purposes
the 't_dec' construction is used to declare fixed table arrays
the 't_set' construction is used to set fixed table values
the 't_use' construction is used to access fixed table values
256 byte tables:
t_xxx(s,box) => forward S box
t_xxx(i,box) => inverse S box
256 32-bit word OR 4 x 256 32-bit word tables:
t_xxx(f,n) => forward normal round
t_xxx(f,l) => forward last round
t_xxx(i,n) => inverse normal round
t_xxx(i,l) => inverse last round
t_xxx(l,s) => key schedule table
t_xxx(i,m) => key schedule table
Other variables and tables:
t_xxx(r,c) => the rcon table
*/
#if !defined( _AESTAB_H )
#define _AESTAB_H
#if defined(__cplusplus)
extern "C" {
#endif
#define t_dec(m,n) t_##m##n
#define t_set(m,n) t_##m##n
#define t_use(m,n) t_##m##n
#if defined(FIXED_TABLES)
# if !defined( __GNUC__ ) && (defined( __MSDOS__ ) || defined( __WIN16__ ))
/* make tables far data to avoid using too much DGROUP space (PG) */
# define CONST const far
# else
# define CONST const
# endif
#else
# define CONST
#endif
#if defined(DO_TABLES)
# define EXTERN
#else
# define EXTERN extern
#endif
#if defined(_MSC_VER) && defined(TABLE_ALIGN)
#define ALIGN __declspec(align(TABLE_ALIGN))
#else
#define ALIGN
#endif
#if defined( __WATCOMC__ ) && ( __WATCOMC__ >= 1100 )
# define XP_DIR __cdecl
#else
# define XP_DIR
#endif
#if defined(DO_TABLES) && defined(FIXED_TABLES)
#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] = b(e)
#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] = { b(e), b(f), b(g), b(h) }
EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH] = rc_data(w0);
#else
#define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256]
#define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256]
EXTERN ALIGN CONST uint_32t t_dec(r,c)[RC_LENGTH];
#endif
#if defined( SBX_SET )
d_1(uint_8t, t_dec(s,box), sb_data, h0);
#endif
#if defined( ISB_SET )
d_1(uint_8t, t_dec(i,box), isb_data, h0);
#endif
#if defined( FT1_SET )
d_1(uint_32t, t_dec(f,n), sb_data, u0);
#endif
#if defined( FT4_SET )
d_4(uint_32t, t_dec(f,n), sb_data, u0, u1, u2, u3);
#endif
#if defined( FL1_SET )
d_1(uint_32t, t_dec(f,l), sb_data, w0);
#endif
#if defined( FL4_SET )
d_4(uint_32t, t_dec(f,l), sb_data, w0, w1, w2, w3);
#endif
#if defined( IT1_SET )
d_1(uint_32t, t_dec(i,n), isb_data, v0);
#endif
#if defined( IT4_SET )
d_4(uint_32t, t_dec(i,n), isb_data, v0, v1, v2, v3);
#endif
#if defined( IL1_SET )
d_1(uint_32t, t_dec(i,l), isb_data, w0);
#endif
#if defined( IL4_SET )
d_4(uint_32t, t_dec(i,l), isb_data, w0, w1, w2, w3);
#endif
#if defined( LS1_SET )
#if defined( FL1_SET )
#undef LS1_SET
#else
d_1(uint_32t, t_dec(l,s), sb_data, w0);
#endif
#endif
#if defined( LS4_SET )
#if defined( FL4_SET )
#undef LS4_SET
#else
d_4(uint_32t, t_dec(l,s), sb_data, w0, w1, w2, w3);
#endif
#endif
#if defined( IM1_SET )
d_1(uint_32t, t_dec(i,m), mm_data, v0);
#endif
#if defined( IM4_SET )
d_4(uint_32t, t_dec(i,m), mm_data, v0, v1, v2, v3);
#endif
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
*/
#ifndef _BRG_ENDIAN_H
#define _BRG_ENDIAN_H
#define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */
#define IS_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */
/* Include files where endian defines and byteswap functions may reside */
#if defined( __sun )
# include <sys/isa_defs.h>
#elif defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __NetBSD__ )
# include <sys/endian.h>
#elif defined( BSD ) && ( BSD >= 199103 ) || defined( __APPLE__ ) || \
defined( __CYGWIN32__ ) || defined( __DJGPP__ ) || defined( __osf__ )
# include <machine/endian.h>
#elif defined( __linux__ ) || defined( __GNUC__ ) || defined( __GNU_LIBRARY__ )
# if !defined( __MINGW32__ ) && !defined( _AIX )
# include <endian.h>
# if !defined( __BEOS__ )
# include <byteswap.h>
# endif
# endif
#endif
/* Now attempt to set the define for platform byte order using any */
/* of the four forms SYMBOL, _SYMBOL, __SYMBOL & __SYMBOL__, which */
/* seem to encompass most endian symbol definitions */
#if defined( BIG_ENDIAN ) && defined( LITTLE_ENDIAN )
# if defined( BYTE_ORDER ) && BYTE_ORDER == BIG_ENDIAN
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
# elif defined( BYTE_ORDER ) && BYTE_ORDER == LITTLE_ENDIAN
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
# endif
#elif defined( BIG_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( LITTLE_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif
#if defined( _BIG_ENDIAN ) && defined( _LITTLE_ENDIAN )
# if defined( _BYTE_ORDER ) && _BYTE_ORDER == _BIG_ENDIAN
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
# elif defined( _BYTE_ORDER ) && _BYTE_ORDER == _LITTLE_ENDIAN
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
# endif
#elif defined( _BIG_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( _LITTLE_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif
#if defined( __BIG_ENDIAN ) && defined( __LITTLE_ENDIAN )
# if defined( __BYTE_ORDER ) && __BYTE_ORDER == __BIG_ENDIAN
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
# elif defined( __BYTE_ORDER ) && __BYTE_ORDER == __LITTLE_ENDIAN
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
# endif
#elif defined( __BIG_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( __LITTLE_ENDIAN )
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif
#if defined( __BIG_ENDIAN__ ) && defined( __LITTLE_ENDIAN__ )
# if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __BIG_ENDIAN__
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
# elif defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __LITTLE_ENDIAN__
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
# endif
#elif defined( __BIG_ENDIAN__ )
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( __LITTLE_ENDIAN__ )
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif
/* if the platform byte order could not be determined, then try to */
/* set this define using common machine defines */
#if !defined(PLATFORM_BYTE_ORDER)
#if defined( __alpha__ ) || defined( __alpha ) || defined( i386 ) || \
defined( __i386__ ) || defined( _M_I86 ) || defined( _M_IX86 ) || \
defined( __OS2__ ) || defined( sun386 ) || defined( __TURBOC__ ) || \
defined( vax ) || defined( vms ) || defined( VMS ) || \
defined( __VMS ) || defined( _M_X64 )
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#elif defined( AMIGA ) || defined( applec ) || defined( __AS400__ ) || \
defined( _CRAY ) || defined( __hppa ) || defined( __hp9000 ) || \
defined( ibm370 ) || defined( mc68000 ) || defined( m68k ) || \
defined( __MRC__ ) || defined( __MVS__ ) || defined( __MWERKS__ ) || \
defined( sparc ) || defined( __sparc) || defined( SYMANTEC_C ) || \
defined( __VOS__ ) || defined( __TIGCC__ ) || defined( __TANDEM ) || \
defined( THINK_C ) || defined( __VMCMS__ ) || defined( _AIX )
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif 0 /* **** EDIT HERE IF NECESSARY **** */
# define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#elif 0 /* **** EDIT HERE IF NECESSARY **** */
# define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#else
# error Please edit lines 126 or 128 in brg_endian.h to set the platform byte order
#endif
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
The redistribution and use of this software (with or without changes)
is allowed without the payment of fees or royalties provided that:
source code distributions include the above copyright notice, this
list of conditions and the following disclaimer;
binary distributions include the above copyright notice, this list
of conditions and the following disclaimer in their documentation.
This software is provided 'as is' with no explicit or implied warranties
in respect of its operation, including, but not limited to, correctness
and fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 20/12/2007
The unsigned integer types defined here are of the form uint_<nn>t where
<nn> is the length of the type; for example, the unsigned 32-bit type is
'uint_32t'. These are NOT the same as the 'C99 integer types' that are
defined in the inttypes.h and stdint.h headers since attempts to use these
types have shown that support for them is still highly variable. However,
since the latter are of the form uint<nn>_t, a regular expression search
and replace (in VC++ search on 'uint_{:z}t' and replace with 'uint\1_t')
can be used to convert the types used here to the C99 standard types.
*/
#ifndef _BRG_TYPES_H
#define _BRG_TYPES_H
#if defined(__cplusplus)
extern "C" {
#endif
#include <limits.h>
#if defined( _MSC_VER ) && ( _MSC_VER >= 1300 )
# include <stddef.h>
# define ptrint_t intptr_t
#elif defined( __ECOS__ )
# define intptr_t unsigned int
# define ptrint_t intptr_t
#elif defined( __GNUC__ ) && ( __GNUC__ >= 3 )
# include <stdint.h>
# define ptrint_t intptr_t
#else
# define ptrint_t int
#endif
#ifndef BRG_UI8
# define BRG_UI8
# if UCHAR_MAX == 255u
typedef unsigned char uint_8t;
# else
# error Please define uint_8t as an 8-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI16
# define BRG_UI16
# if USHRT_MAX == 65535u
typedef unsigned short uint_16t;
# else
# error Please define uint_16t as a 16-bit unsigned short type in brg_types.h
# endif
#endif
#ifndef BRG_UI32
# define BRG_UI32
# if UINT_MAX == 4294967295u
# define li_32(h) 0x##h##u
typedef unsigned int uint_32t;
# elif ULONG_MAX == 4294967295u
# define li_32(h) 0x##h##ul
typedef unsigned long uint_32t;
# elif defined( _CRAY )
# error This code needs 32-bit data types, which Cray machines do not provide
# else
# error Please define uint_32t as a 32-bit unsigned integer type in brg_types.h
# endif
#endif
#ifndef BRG_UI64
# if defined( __BORLANDC__ ) && !defined( __MSDOS__ )
# define BRG_UI64
# define li_64(h) 0x##h##ui64
typedef unsigned __int64 uint_64t;
# elif defined( _MSC_VER ) && ( _MSC_VER < 1300 ) /* 1300 == VC++ 7.0 */
# define BRG_UI64
# define li_64(h) 0x##h##ui64
typedef unsigned __int64 uint_64t;
# elif defined( __sun ) && defined( ULONG_MAX ) && ULONG_MAX == 0xfffffffful
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# elif defined( __MVS__ )
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned int long long uint_64t;
# elif defined( UINT_MAX ) && UINT_MAX > 4294967295u
# if UINT_MAX == 18446744073709551615u
# define BRG_UI64
# define li_64(h) 0x##h##u
typedef unsigned int uint_64t;
# endif
# elif defined( ULONG_MAX ) && ULONG_MAX > 4294967295u
# if ULONG_MAX == 18446744073709551615ul
# define BRG_UI64
# define li_64(h) 0x##h##ul
typedef unsigned long uint_64t;
# endif
# elif defined( ULLONG_MAX ) && ULLONG_MAX > 4294967295u
# if ULLONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# elif defined( ULONG_LONG_MAX ) && ULONG_LONG_MAX > 4294967295u
# if ULONG_LONG_MAX == 18446744073709551615ull
# define BRG_UI64
# define li_64(h) 0x##h##ull
typedef unsigned long long uint_64t;
# endif
# endif
#endif
#if !defined( BRG_UI64 )
# if defined( NEED_UINT_64T )
# error Please define uint_64t as an unsigned 64 bit type in brg_types.h
# endif
#endif
#ifndef RETURN_VALUES
# define RETURN_VALUES
# if defined( DLL_EXPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllexport ) void __stdcall
# define INT_RETURN __declspec( dllexport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllexport__ ) void
# define INT_RETURN __declspec( __dllexport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( DLL_IMPORT )
# if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
# define VOID_RETURN __declspec( dllimport ) void __stdcall
# define INT_RETURN __declspec( dllimport ) int __stdcall
# elif defined( __GNUC__ )
# define VOID_RETURN __declspec( __dllimport__ ) void
# define INT_RETURN __declspec( __dllimport__ ) int
# else
# error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
# endif
# elif defined( __WATCOMC__ )
# define VOID_RETURN void __cdecl
# define INT_RETURN int __cdecl
# else
# define VOID_RETURN void
# define INT_RETURN int
# endif
#endif
/* These defines are used to detect and set the memory alignment of pointers.
Note that offsets are in bytes.
ALIGN_OFFSET(x,n) return the positive or zero offset of
the memory addressed by the pointer 'x'
from an address that is aligned on an
'n' byte boundary ('n' is a power of 2)
ALIGN_FLOOR(x,n) return a pointer that points to memory
that is aligned on an 'n' byte boundary
and is not higher than the memory address
pointed to by 'x' ('n' is a power of 2)
ALIGN_CEIL(x,n) return a pointer that points to memory
that is aligned on an 'n' byte boundary
and is not lower than the memory address
pointed to by 'x' ('n' is a power of 2)
*/
#define ALIGN_OFFSET(x,n) (((ptrint_t)(x)) & ((n) - 1))
#define ALIGN_FLOOR(x,n) ((uint_8t*)(x) - ( ((ptrint_t)(x)) & ((n) - 1)))
#define ALIGN_CEIL(x,n) ((uint_8t*)(x) + (-((ptrint_t)(x)) & ((n) - 1)))
/* These defines are used to declare buffers in a way that allows
faster operations on longer variables to be used. In all these
defines 'size' must be a power of 2 and >= 8. NOTE that the
buffer size is in bytes but the type length is in bits
UNIT_TYPEDEF(x,size) declares a variable 'x' of length
'size' bits
BUFR_TYPEDEF(x,size,bsize) declares a buffer 'x' of length 'bsize'
bytes defined as an array of variables
each of 'size' bits (bsize must be a
multiple of size / 8)
UNIT_CAST(x,size) casts a variable to a type of
length 'size' bits
UPTR_CAST(x,size) casts a pointer to a pointer to a
varaiable of length 'size' bits
*/
#define UI_TYPE(size) uint_##size##t
#define UNIT_TYPEDEF(x,size) typedef UI_TYPE(size) x
#define BUFR_TYPEDEF(x,size,bsize) typedef UI_TYPE(size) x[bsize / (size >> 3)]
#define UNIT_CAST(x,size) ((UI_TYPE(size) )(x))
#define UPTR_CAST(x,size) ((UI_TYPE(size)*)(x))
#if defined(__cplusplus)
}
#endif
#endif
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
#ifdef _WIN32
int entropy_fun(unsigned char buf[], unsigned int len)
{
HCRYPTPROV provider;
unsigned __int64 pentium_tsc[1];
unsigned int i;
int result = 0;
if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
{
result = CryptGenRandom(provider, len, buf);
CryptReleaseContext(provider, 0);
if (result)
return len;
}
QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc);
for(i = 0; i < 8 && i < len; ++i)
buf[i] = ((unsigned char*)pentium_tsc)[i];
return i;
}
#else
int entropy_fun(unsigned char buf[], unsigned int len)
{
int frand = open("/dev/random", O_RDONLY);
int rlen = 0;
if (frand != -1)
{
rlen = read(frand, buf, len);
close(frand);
}
return rlen;
}
#endif
#if defined(__cplusplus)
}
#endif
#ifndef _ENTROPY_FUN_H
#define _ENTROPY_FUN_H
#if defined(__cplusplus)
extern "C"
{
#endif
int entropy_fun(unsigned char buf[], unsigned int len);
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
-------------------------------------------------------------------------
Issue Date: 24/01/2003
This file implements password based file encryption and authentication
using AES in CTR mode, HMAC-SHA1 authentication and RFC2898 password
based key derivation.
*/
#include <memory.h>
#include "fileenc.h"
#if defined(__cplusplus)
extern "C"
{
#endif
/* subroutine for data encryption/decryption */
/* this could be speeded up a lot by aligning */
/* buffers and using 32 bit operations */
static void encr_data(unsigned char data[], unsigned long d_len, fcrypt_ctx cx[1])
{ unsigned long i = 0, pos = cx->encr_pos;
while(i < d_len)
{
if(pos == AES_BLOCK_SIZE)
{ unsigned int j = 0;
/* increment encryption nonce */
while(j < 8 && !++cx->nonce[j])
++j;
/* encrypt the nonce to form next xor buffer */
aes_encrypt(cx->nonce, cx->encr_bfr, cx->encr_ctx);
pos = 0;
}
data[i++] ^= cx->encr_bfr[pos++];
}
cx->encr_pos = pos;
}
int fcrypt_init(
int mode, /* the mode to be used (input) */
const unsigned char pwd[], /* the user specified password (input) */
unsigned int pwd_len, /* the length of the password (input) */
const unsigned char salt[], /* the salt (input) */
#ifdef PASSWORD_VERIFIER
unsigned char pwd_ver[PWD_VER_LENGTH], /* 2 byte password verifier (output) */
#endif
fcrypt_ctx cx[1]) /* the file encryption context (output) */
{ unsigned char kbuf[2 * MAX_KEY_LENGTH + PWD_VER_LENGTH];
if(pwd_len > MAX_PWD_LENGTH)
return PASSWORD_TOO_LONG;
if(mode < 1 || mode > 3)
return BAD_MODE;
cx->mode = mode;
cx->pwd_len = pwd_len;
/* derive the encryption and authentication keys and the password verifier */
derive_key(pwd, pwd_len, salt, SALT_LENGTH(mode), KEYING_ITERATIONS,
kbuf, 2 * KEY_LENGTH(mode) + PWD_VER_LENGTH);
/* initialise the encryption nonce and buffer pos */
cx->encr_pos = AES_BLOCK_SIZE;
/* if we need a random component in the encryption */
/* nonce, this is where it would have to be set */
memset(cx->nonce, 0, AES_BLOCK_SIZE * sizeof(unsigned char));
/* initialise for encryption using key 1 */
aes_encrypt_key(kbuf, KEY_LENGTH(mode), cx->encr_ctx);
/* initialise for authentication using key 2 */
hmac_sha_begin(cx->auth_ctx);
hmac_sha_key(kbuf + KEY_LENGTH(mode), KEY_LENGTH(mode), cx->auth_ctx);
#ifdef PASSWORD_VERIFIER
memcpy(pwd_ver, kbuf + 2 * KEY_LENGTH(mode), PWD_VER_LENGTH);
#endif
return GOOD_RETURN;
}
/* perform 'in place' encryption and authentication */
void fcrypt_encrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1])
{
encr_data(data, data_len, cx);
hmac_sha_data(data, data_len, cx->auth_ctx);
}
/* perform 'in place' authentication and decryption */
void fcrypt_decrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1])
{
hmac_sha_data(data, data_len, cx->auth_ctx);
encr_data(data, data_len, cx);
}
/* close encryption/decryption and return the MAC value */
int fcrypt_end(unsigned char mac[], fcrypt_ctx cx[1])
{
hmac_sha_end(mac, MAC_LENGTH(cx->mode), cx->auth_ctx);
return MAC_LENGTH(cx->mode); /* return MAC length in bytes */
}
#if defined(__cplusplus)
}
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 24/01/2003
This file contains the header file for fileenc.c, which implements password
based file encryption and authentication using AES in CTR mode, HMAC-SHA1
authentication and RFC2898 password based key derivation.
*/
#ifndef _FENC_H
#define _FENC_H
#include "aes.h"
#include "hmac.h"
#include "pwd2key.h"
#define PASSWORD_VERIFIER
#define MAX_KEY_LENGTH 32
#define MAX_PWD_LENGTH 128
#define MAX_SALT_LENGTH 16
#define KEYING_ITERATIONS 1000
#ifdef PASSWORD_VERIFIER
#define PWD_VER_LENGTH 2
#else
#define PWD_VER_LENGTH 0
#endif
#define GOOD_RETURN 0
#define PASSWORD_TOO_LONG -100
#define BAD_MODE -101
/*
Field lengths (in bytes) versus File Encryption Mode (0 < mode < 4)
Mode Key Salt MAC Overhead
1 16 8 10 18
2 24 12 10 22
3 32 16 10 26
The following macros assume that the mode value is correct.
*/
#define KEY_LENGTH(mode) (8 * (mode & 3) + 8)
#define SALT_LENGTH(mode) (4 * (mode & 3) + 4)
#define MAC_LENGTH(mode) (10)
/* the context for file encryption */
#if defined(__cplusplus)
extern "C"
{
#endif
typedef struct
{ unsigned char nonce[AES_BLOCK_SIZE]; /* the CTR nonce */
unsigned char encr_bfr[AES_BLOCK_SIZE]; /* encrypt buffer */
aes_encrypt_ctx encr_ctx[1]; /* encryption context */
hmac_ctx auth_ctx[1]; /* authentication context */
unsigned int encr_pos; /* block position (enc) */
unsigned int pwd_len; /* password length */
unsigned int mode; /* File encryption mode */
} fcrypt_ctx;
/* initialise file encryption or decryption */
int fcrypt_init(
int mode, /* the mode to be used (input) */
const unsigned char pwd[], /* the user specified password (input) */
unsigned int pwd_len, /* the length of the password (input) */
const unsigned char salt[], /* the salt (input) */
#ifdef PASSWORD_VERIFIER
unsigned char pwd_ver[PWD_VER_LENGTH], /* 2 byte password verifier (output) */
#endif
fcrypt_ctx cx[1]); /* the file encryption context (output) */
/* perform 'in place' encryption or decryption and authentication */
void fcrypt_encrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]);
void fcrypt_decrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]);
/* close encryption/decryption and return the MAC value */
/* the return value is the length of the MAC */
int fcrypt_end(unsigned char mac[], /* the MAC value (output) */
fcrypt_ctx cx[1]); /* the context (input) */
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 26/08/2003
This is an implementation of HMAC, the FIPS standard keyed hash function
*/
#include "hmac.h"
#include "brg_types.h"
#if defined(__cplusplus)
extern "C"
{
#endif
/* initialise the HMAC context to zero */
void hmac_sha_begin(hmac_ctx cx[1])
{
memset(cx, 0, sizeof(hmac_ctx));
}
/* input the HMAC key (can be called multiple times) */
int hmac_sha_key(const unsigned char key[], unsigned long key_len, hmac_ctx cx[1])
{
if(cx->klen == HMAC_IN_DATA) /* error if further key input */
return HMAC_BAD_MODE; /* is attempted in data mode */
if(cx->klen + key_len > HASH_INPUT_SIZE) /* if the key has to be hashed */
{
if(cx->klen <= HASH_INPUT_SIZE) /* if the hash has not yet been */
{ /* started, initialise it and */
sha_begin(cx->ctx); /* hash stored key characters */
sha_hash(cx->key, cx->klen, cx->ctx);
}
sha_hash(key, key_len, cx->ctx); /* hash long key data into hash */
}
else /* otherwise store key data */
memcpy(cx->key + cx->klen, key, key_len);
cx->klen += key_len; /* update the key length count */
return HMAC_OK;
}
/* input the HMAC data (can be called multiple times) - */
/* note that this call terminates the key input phase */
void hmac_sha_data(const unsigned char data[], unsigned long data_len, hmac_ctx cx[1])
{ unsigned int i;
if(cx->klen != HMAC_IN_DATA) /* if not yet in data phase */
{
if(cx->klen > HASH_INPUT_SIZE) /* if key is being hashed */
{ /* complete the hash and */
sha_end(cx->key, cx->ctx); /* store the result as the */
cx->klen = HASH_OUTPUT_SIZE; /* key and set new length */
}
/* pad the key if necessary */
memset(cx->key + cx->klen, 0, HASH_INPUT_SIZE - cx->klen);
/* xor ipad into key value */
for(i = 0; i < (HASH_INPUT_SIZE >> 2); ++i)
((uint_32t*)cx->key)[i] ^= 0x36363636;
/* and start hash operation */
sha_begin(cx->ctx);
sha_hash(cx->key, HASH_INPUT_SIZE, cx->ctx);
/* mark as now in data mode */
cx->klen = HMAC_IN_DATA;
}
/* hash the data (if any) */
if(data_len)
sha_hash(data, data_len, cx->ctx);
}
/* compute and output the MAC value */
void hmac_sha_end(unsigned char mac[], unsigned long mac_len, hmac_ctx cx[1])
{ unsigned char dig[HASH_OUTPUT_SIZE];
unsigned int i;
/* if no data has been entered perform a null data phase */
if(cx->klen != HMAC_IN_DATA)
hmac_sha_data((const unsigned char*)0, 0, cx);
sha_end(dig, cx->ctx); /* complete the inner hash */
/* set outer key value using opad and removing ipad */
for(i = 0; i < (HASH_INPUT_SIZE >> 2); ++i)
((uint_32t*)cx->key)[i] ^= 0x36363636 ^ 0x5c5c5c5c;
/* perform the outer hash operation */
sha_begin(cx->ctx);
sha_hash(cx->key, HASH_INPUT_SIZE, cx->ctx);
sha_hash(dig, HASH_OUTPUT_SIZE, cx->ctx);
sha_end(dig, cx->ctx);
/* output the hash value */
for(i = 0; i < mac_len; ++i)
mac[i] = dig[i];
}
/* 'do it all in one go' subroutine */
void hmac_sha(const unsigned char key[], unsigned long key_len,
const unsigned char data[], unsigned long data_len,
unsigned char mac[], unsigned long mac_len)
{ hmac_ctx cx[1];
hmac_sha_begin(cx);
hmac_sha_key(key, key_len, cx);
hmac_sha_data(data, data_len, cx);
hmac_sha_end(mac, mac_len, cx);
}
#if defined(__cplusplus)
}
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 26/08/2003
This is an implementation of HMAC, the FIPS standard keyed hash function
*/
#ifndef _HMAC_H
#define _HMAC_H
#include <memory.h>
#if defined(__cplusplus)
extern "C"
{
#endif
#define USE_SHA1
#if !defined(USE_SHA1) && !defined(USE_SHA256)
#error define USE_SHA1 or USE_SHA256 to set the HMAC hash algorithm
#endif
#ifdef USE_SHA1
#include "sha1.h"
#define HASH_INPUT_SIZE SHA1_BLOCK_SIZE
#define HASH_OUTPUT_SIZE SHA1_DIGEST_SIZE
#define sha_ctx sha1_ctx
#define sha_begin sha1_begin
#define sha_hash sha1_hash
#define sha_end sha1_end
#endif
#ifdef USE_SHA256
#include "sha2.h"
#define HASH_INPUT_SIZE SHA256_BLOCK_SIZE
#define HASH_OUTPUT_SIZE SHA256_DIGEST_SIZE
#define sha_ctx sha256_ctx
#define sha_begin sha256_begin
#define sha_hash sha256_hash
#define sha_end sha256_end
#endif
#define HMAC_OK 0
#define HMAC_BAD_MODE -1
#define HMAC_IN_DATA 0xffffffff
typedef struct
{ unsigned char key[HASH_INPUT_SIZE];
sha_ctx ctx[1];
unsigned long klen;
} hmac_ctx;
void hmac_sha_begin(hmac_ctx cx[1]);
int hmac_sha_key(const unsigned char key[], unsigned long key_len, hmac_ctx cx[1]);
void hmac_sha_data(const unsigned char data[], unsigned long data_len, hmac_ctx cx[1]);
void hmac_sha_end(unsigned char mac[], unsigned long mac_len, hmac_ctx cx[1]);
void hmac_sha(const unsigned char key[], unsigned long key_len,
const unsigned char data[], unsigned long data_len,
unsigned char mac[], unsigned long mac_len);
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 24/01/2003
This file implements a random data pool based on the use of an external
entropy function. It is based on the ideas advocated by Peter Gutmann in
his work on pseudo random sequence generators. It is not a 'paranoid'
random sequence generator and no attempt is made to protect the pool
from prying eyes either by memory locking or by techniques to obscure
its location in memory.
*/
#include <memory.h>
#include "prng.h"
#if defined(__cplusplus)
extern "C"
{
#endif
/* mix a random data pool using the SHA1 compression function (as */
/* suggested by Peter Gutmann in his paper on random pools) */
static void prng_mix(unsigned char buf[])
{ unsigned int i, len;
sha1_ctx ctx[1];
/*lint -e{663} unusual array to pointer conversion */
for(i = 0; i < PRNG_POOL_SIZE; i += SHA1_DIGEST_SIZE)
{
/* copy digest size pool block into SHA1 hash block */
memcpy(ctx->hash, buf + (i ? i : PRNG_POOL_SIZE)
- SHA1_DIGEST_SIZE, SHA1_DIGEST_SIZE);
/* copy data from pool into the SHA1 data buffer */
len = PRNG_POOL_SIZE - i;
memcpy(ctx->wbuf, buf + i, (len > SHA1_BLOCK_SIZE ? SHA1_BLOCK_SIZE : len));
if(len < SHA1_BLOCK_SIZE)
memcpy(((char*)ctx->wbuf) + len, buf, SHA1_BLOCK_SIZE - len);
/* compress using the SHA1 compression function */
sha1_compile(ctx);
/* put digest size block back into the random pool */
memcpy(buf + i, ctx->hash, SHA1_DIGEST_SIZE);
}
}
/* refresh the output buffer and update the random pool by adding */
/* entropy and remixing */
static void update_pool(prng_ctx ctx[1])
{ unsigned int i = 0;
/* transfer random pool data to the output buffer */
memcpy(ctx->obuf, ctx->rbuf, PRNG_POOL_SIZE);
/* enter entropy data into the pool */
while(i < PRNG_POOL_SIZE)
i += ctx->entropy(ctx->rbuf + i, PRNG_POOL_SIZE - i);
/* invert and xor the original pool data into the pool */
for(i = 0; i < PRNG_POOL_SIZE; ++i)
ctx->rbuf[i] ^= ~ctx->obuf[i];
/* mix the pool and the output buffer */
prng_mix(ctx->rbuf);
prng_mix(ctx->obuf);
}
void prng_init(prng_entropy_fn fun, prng_ctx ctx[1])
{ int i;
/* clear the buffers and the counter in the context */
memset(ctx, 0, sizeof(prng_ctx));
/* set the pointer to the entropy collection function */
ctx->entropy = fun;
/* initialise the random data pool */
update_pool(ctx);
/* mix the pool a minimum number of times */
for(i = 0; i < PRNG_MIN_MIX; ++i)
prng_mix(ctx->rbuf);
/* update the pool to prime the pool output buffer */
update_pool(ctx);
}
/* provide random bytes from the random data pool */
void prng_rand(unsigned char data[], unsigned int data_len, prng_ctx ctx[1])
{ unsigned char *rp = data;
unsigned int len, pos = ctx->pos;
while(data_len)
{
/* transfer 'data_len' bytes (or the number of bytes remaining */
/* the pool output buffer if less) into the output */
len = (data_len < PRNG_POOL_SIZE - pos ? data_len : PRNG_POOL_SIZE - pos);
memcpy(rp, ctx->obuf + pos, len);
rp += len; /* update ouput buffer position pointer */
pos += len; /* update pool output buffer pointer */
data_len -= len; /* update the remaining data count */
/* refresh the random pool if necessary */
if(pos == PRNG_POOL_SIZE)
{
update_pool(ctx); pos = 0;
}
}
ctx->pos = pos;
}
void prng_end(prng_ctx ctx[1])
{
/* ensure the data in the context is destroyed */
memset(ctx, 0, sizeof(prng_ctx));
}
#if defined(__cplusplus)
}
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 24/01/2003
This is the header file for an implementation of a random data pool based on
the use of an external entropy function (inspired by Peter Gutmann's work).
*/
#ifndef _PRNG_H
#define _PRNG_H
#include "sha1.h"
#define PRNG_POOL_LEN 256 /* minimum random pool size */
#define PRNG_MIN_MIX 20 /* min initial pool mixing iterations */
/* ensure that pool length is a multiple of the SHA1 digest size */
#define PRNG_POOL_SIZE (SHA1_DIGEST_SIZE * (1 + (PRNG_POOL_LEN - 1) / SHA1_DIGEST_SIZE))
#if defined(__cplusplus)
extern "C"
{
#endif
/* A function for providing entropy is a parameter in the prng_init() */
/* call. This function has the following form and returns a maximum */
/* of 'len' bytes of pseudo random data in the buffer 'buf'. It can */
/* return less than 'len' bytes but will be repeatedly called for more */
/* data in this case. */
typedef int (*prng_entropy_fn)(unsigned char buf[], unsigned int len);
typedef struct
{ unsigned char rbuf[PRNG_POOL_SIZE]; /* the random pool */
unsigned char obuf[PRNG_POOL_SIZE]; /* pool output buffer */
unsigned int pos; /* output buffer position */
prng_entropy_fn entropy; /* entropy function pointer */
} prng_ctx;
/* initialise the random stream generator */
void prng_init(prng_entropy_fn fun, prng_ctx ctx[1]);
/* obtain random bytes from the generator */
void prng_rand(unsigned char data[], unsigned int data_len, prng_ctx ctx[1]);
/* close the random stream generator */
void prng_end(prng_ctx ctx[1]);
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 26/08/2003
This is an implementation of RFC2898, which specifies key derivation from
a password and a salt value.
*/
#include <memory.h>
#include "hmac.h"
#if defined(__cplusplus)
extern "C"
{
#endif
void derive_key(const unsigned char pwd[], /* the PASSWORD */
unsigned int pwd_len, /* and its length */
const unsigned char salt[], /* the SALT and its */
unsigned int salt_len, /* length */
unsigned int iter, /* the number of iterations */
unsigned char key[], /* space for the output key */
unsigned int key_len)/* and its required length */
{
unsigned int i, j, k, n_blk;
unsigned char uu[HASH_OUTPUT_SIZE], ux[HASH_OUTPUT_SIZE];
hmac_ctx c1[1], c2[1], c3[1];
/* set HMAC context (c1) for password */
hmac_sha_begin(c1);
hmac_sha_key(pwd, pwd_len, c1);
/* set HMAC context (c2) for password and salt */
memcpy(c2, c1, sizeof(hmac_ctx));
hmac_sha_data(salt, salt_len, c2);
/* find the number of SHA blocks in the key */
n_blk = 1 + (key_len - 1) / HASH_OUTPUT_SIZE;
for(i = 0; i < n_blk; ++i) /* for each block in key */
{
/* ux[] holds the running xor value */
memset(ux, 0, HASH_OUTPUT_SIZE);
/* set HMAC context (c3) for password and salt */
memcpy(c3, c2, sizeof(hmac_ctx));
/* enter additional data for 1st block into uu */
uu[0] = (unsigned char)((i + 1) >> 24);
uu[1] = (unsigned char)((i + 1) >> 16);
uu[2] = (unsigned char)((i + 1) >> 8);
uu[3] = (unsigned char)(i + 1);
/* this is the key mixing iteration */
for(j = 0, k = 4; j < iter; ++j)
{
/* add previous round data to HMAC */
hmac_sha_data(uu, k, c3);
/* obtain HMAC for uu[] */
hmac_sha_end(uu, HASH_OUTPUT_SIZE, c3);
/* xor into the running xor block */
for(k = 0; k < HASH_OUTPUT_SIZE; ++k)
ux[k] ^= uu[k];
/* set HMAC context (c3) for password */
memcpy(c3, c1, sizeof(hmac_ctx));
}
/* compile key blocks into the key output */
j = 0; k = i * HASH_OUTPUT_SIZE;
while(j < HASH_OUTPUT_SIZE && k < key_len)
key[k++] = ux[j++];
}
}
#ifdef TEST
#include <stdio.h>
struct
{ unsigned int pwd_len;
unsigned int salt_len;
unsigned int it_count;
unsigned char *pwd;
unsigned char salt[32];
unsigned char key[32];
} tests[] =
{
{ 8, 4, 5, (unsigned char*)"password",
{
0x12, 0x34, 0x56, 0x78
},
{
0x5c, 0x75, 0xce, 0xf0, 0x1a, 0x96, 0x0d, 0xf7,
0x4c, 0xb6, 0xb4, 0x9b, 0x9e, 0x38, 0xe6, 0xb5
}
},
{ 8, 8, 5, (unsigned char*)"password",
{
0x12, 0x34, 0x56, 0x78, 0x78, 0x56, 0x34, 0x12
},
{
0xd1, 0xda, 0xa7, 0x86, 0x15, 0xf2, 0x87, 0xe6,
0xa1, 0xc8, 0xb1, 0x20, 0xd7, 0x06, 0x2a, 0x49
}
},
{ 8, 21, 1, (unsigned char*)"password",
{
"ATHENA.MIT.EDUraeburn"
},
{
0xcd, 0xed, 0xb5, 0x28, 0x1b, 0xb2, 0xf8, 0x01,
0x56, 0x5a, 0x11, 0x22, 0xb2, 0x56, 0x35, 0x15
}
},
{ 8, 21, 2, (unsigned char*)"password",
{
"ATHENA.MIT.EDUraeburn"
},
{
0x01, 0xdb, 0xee, 0x7f, 0x4a, 0x9e, 0x24, 0x3e,
0x98, 0x8b, 0x62, 0xc7, 0x3c, 0xda, 0x93, 0x5d
}
},
{ 8, 21, 1200, (unsigned char*)"password",
{
"ATHENA.MIT.EDUraeburn"
},
{
0x5c, 0x08, 0xeb, 0x61, 0xfd, 0xf7, 0x1e, 0x4e,
0x4e, 0xc3, 0xcf, 0x6b, 0xa1, 0xf5, 0x51, 0x2b
}
}
};
int main()
{ unsigned int i, j, key_len = 256;
unsigned char key[256];
printf("\nTest of RFC2898 Password Based Key Derivation");
for(i = 0; i < 5; ++i)
{
derive_key(tests[i].pwd, tests[i].pwd_len, tests[i].salt,
tests[i].salt_len, tests[i].it_count, key, key_len);
printf("\ntest %i: ", i + 1);
printf("key %s", memcmp(tests[i].key, key, 16) ? "is bad" : "is good");
for(j = 0; j < key_len && j < 64; j += 4)
{
if(j % 16 == 0)
printf("\n");
printf("0x%02x%02x%02x%02x ", key[j], key[j + 1], key[j + 2], key[j + 3]);
}
printf(j < key_len ? " ... \n" : "\n");
}
printf("\n");
return 0;
}
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 26/08/2003
This is an implementation of RFC2898, which specifies key derivation from
a password and a salt value.
*/
#ifndef PWD2KEY_H
#define PWD2KEY_H
#if defined(__cplusplus)
extern "C"
{
#endif
void derive_key(
const unsigned char pwd[], /* the PASSWORD, and */
unsigned int pwd_len, /* its length */
const unsigned char salt[], /* the SALT and its */
unsigned int salt_len, /* length */
unsigned int iter, /* the number of iterations */
unsigned char key[], /* space for the output key */
unsigned int key_len); /* and its required length */
#if defined(__cplusplus)
}
#endif
#endif
/*
---------------------------------------------------------------------------
Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved.
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
---------------------------------------------------------------------------
Issue Date: 01/08/2005
This is a byte oriented version of SHA1 that operates on arrays of bytes
stored in memory.
*/
#include <string.h> /* for memcpy() etc. */
#include "sha1.h"
#include "brg_endian.h"
#if defined(__cplusplus)
extern "C"
{
#endif
#if defined( _MSC_VER ) && ( _MSC_VER > 800 )
#pragma intrinsic(memcpy)
#endif
#if 0 && defined(_MSC_VER)
#define rotl32 _lrotl
#define rotr32 _lrotr
#else
#define rotl32(x,n) (((x) << n) | ((x) >> (32 - n)))
#define rotr32(x,n) (((x) >> n) | ((x) << (32 - n)))
#endif
#if !defined(bswap_32)
#define bswap_32(x) ((rotr32((x), 24) & 0x00ff00ff) | (rotr32((x), 8) & 0xff00ff00))
#endif
#if (PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN)
#define SWAP_BYTES
#else
#undef SWAP_BYTES
#endif
#if defined(SWAP_BYTES)
#define bsw_32(p,n) \
{ int _i = (n); while(_i--) ((uint_32t*)p)[_i] = bswap_32(((uint_32t*)p)[_i]); }
#else
#define bsw_32(p,n)
#endif
#define SHA1_MASK (SHA1_BLOCK_SIZE - 1)
#if 0
#define ch(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
#define parity(x,y,z) ((x) ^ (y) ^ (z))
#define maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#else /* Discovered by Rich Schroeppel and Colin Plumb */
#define ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define parity(x,y,z) ((x) ^ (y) ^ (z))
#define maj(x,y,z) (((x) & (y)) | ((z) & ((x) ^ (y))))
#endif
/* Compile 64 bytes of hash data into SHA1 context. Note */
/* that this routine assumes that the byte order in the */
/* ctx->wbuf[] at this point is in such an order that low */
/* address bytes in the ORIGINAL byte stream will go in */
/* this buffer to the high end of 32-bit words on BOTH big */
/* and little endian systems */
#ifdef ARRAY
#define q(v,n) v[n]
#else
#define q(v,n) v##n
#endif
#define one_cycle(v,a,b,c,d,e,f,k,h) \
q(v,e) += rotr32(q(v,a),27) + \
f(q(v,b),q(v,c),q(v,d)) + k + h; \
q(v,b) = rotr32(q(v,b), 2)
#define five_cycle(v,f,k,i) \
one_cycle(v, 0,1,2,3,4, f,k,hf(i )); \
one_cycle(v, 4,0,1,2,3, f,k,hf(i+1)); \
one_cycle(v, 3,4,0,1,2, f,k,hf(i+2)); \
one_cycle(v, 2,3,4,0,1, f,k,hf(i+3)); \
one_cycle(v, 1,2,3,4,0, f,k,hf(i+4))
VOID_RETURN sha1_compile(sha1_ctx ctx[1])
{ uint_32t *w = ctx->wbuf;
#ifdef ARRAY
uint_32t v[5];
memcpy(v, ctx->hash, 5 * sizeof(uint_32t));
#else
uint_32t v0, v1, v2, v3, v4;
v0 = ctx->hash[0]; v1 = ctx->hash[1];
v2 = ctx->hash[2]; v3 = ctx->hash[3];
v4 = ctx->hash[4];
#endif
#define hf(i) w[i]
five_cycle(v, ch, 0x5a827999, 0);
five_cycle(v, ch, 0x5a827999, 5);
five_cycle(v, ch, 0x5a827999, 10);
one_cycle(v,0,1,2,3,4, ch, 0x5a827999, hf(15)); \
#undef hf
#define hf(i) (w[(i) & 15] = rotl32( \
w[((i) + 13) & 15] ^ w[((i) + 8) & 15] \
^ w[((i) + 2) & 15] ^ w[(i) & 15], 1))
one_cycle(v,4,0,1,2,3, ch, 0x5a827999, hf(16));
one_cycle(v,3,4,0,1,2, ch, 0x5a827999, hf(17));
one_cycle(v,2,3,4,0,1, ch, 0x5a827999, hf(18));
one_cycle(v,1,2,3,4,0, ch, 0x5a827999, hf(19));
five_cycle(v, parity, 0x6ed9eba1, 20);
five_cycle(v, parity, 0x6ed9eba1, 25);
five_cycle(v, parity, 0x6ed9eba1, 30);
five_cycle(v, parity, 0x6ed9eba1, 35);
five_cycle(v, maj, 0x8f1bbcdc, 40);
five_cycle(v, maj, 0x8f1bbcdc, 45);
five_cycle(v, maj, 0x8f1bbcdc, 50);
five_cycle(v, maj, 0x8f1bbcdc, 55);
five_cycle(v, parity, 0xca62c1d6, 60);
five_cycle(v, parity, 0xca62c1d6, 65);
five_cycle(v, parity, 0xca62c1d6, 70);
five_cycle(v, parity, 0xca62c1d6, 75);
#ifdef ARRAY
ctx->hash[0] += v[0]; ctx->hash[1] += v[1];
ctx->hash[2] += v[2]; ctx->hash[3] += v[3];
ctx->hash[4] += v[4];
#else
ctx->hash[0] += v0; ctx->hash[1] += v1;
ctx->hash[2] += v2; ctx->hash[3] += v3;
ctx->hash[4] += v4;
#endif
}
VOID_RETURN sha1_begin(sha1_ctx ctx[1])
{
ctx->count[0] = ctx->count[1] = 0;
ctx->hash[0] = 0x67452301;
ctx->hash[1] = 0xefcdab89;
ctx->hash[2] = 0x98badcfe;
ctx->hash[3] = 0x10325476;
ctx->hash[4] = 0xc3d2e1f0;
}
/* SHA1 hash data in an array of bytes into hash buffer and */
/* call the hash_compile function as required. */
VOID_RETURN sha1_hash(const unsigned char data[], unsigned long len, sha1_ctx ctx[1])
{ uint_32t pos = (uint_32t)(ctx->count[0] & SHA1_MASK),
space = SHA1_BLOCK_SIZE - pos;
const unsigned char *sp = data;
if((ctx->count[0] += len) < len)
++(ctx->count[1]);
while(len >= space) /* tranfer whole blocks if possible */
{
memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space);
sp += space; len -= space; space = SHA1_BLOCK_SIZE; pos = 0;
bsw_32(ctx->wbuf, SHA1_BLOCK_SIZE >> 2);
sha1_compile(ctx);
}
memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len);
}
/* SHA1 final padding and digest calculation */
VOID_RETURN sha1_end(unsigned char hval[], sha1_ctx ctx[1])
{ uint_32t i = (uint_32t)(ctx->count[0] & SHA1_MASK);
/* put bytes in the buffer in an order in which references to */
/* 32-bit words will put bytes with lower addresses into the */
/* top of 32 bit words on BOTH big and little endian machines */
bsw_32(ctx->wbuf, (i + 3) >> 2);
/* we now need to mask valid bytes and add the padding which is */
/* a single 1 bit and as many zero bits as necessary. Note that */
/* we can always add the first padding byte here because the */
/* buffer always has at least one empty slot */
ctx->wbuf[i >> 2] &= 0xffffff80 << 8 * (~i & 3);
ctx->wbuf[i >> 2] |= 0x00000080 << 8 * (~i & 3);
/* we need 9 or more empty positions, one for the padding byte */
/* (above) and eight for the length count. If there is not */
/* enough space, pad and empty the buffer */
if(i > SHA1_BLOCK_SIZE - 9)
{
if(i < 60) ctx->wbuf[15] = 0;
sha1_compile(ctx);
i = 0;
}
else /* compute a word index for the empty buffer positions */
i = (i >> 2) + 1;
while(i < 14) /* and zero pad all but last two positions */
ctx->wbuf[i++] = 0;
/* the following 32-bit length fields are assembled in the */
/* wrong byte order on little endian machines but this is */
/* corrected later since they are only ever used as 32-bit */
/* word values. */
ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 29);
ctx->wbuf[15] = ctx->count[0] << 3;
sha1_compile(ctx);
/* extract the hash value as bytes in case the hash buffer is */
/* misaligned for 32-bit words */
for(i = 0; i < SHA1_DIGEST_SIZE; ++i)
hval[i] = (unsigned char)(ctx->hash[i >> 2] >> (8 * (~i & 3)));
}
VOID_RETURN sha1(unsigned char hval[], const unsigned char data[], unsigned long len)
{ sha1_ctx cx[1];
sha1_begin(cx); sha1_hash(data, len, cx); sha1_end(hval, cx);
}
#if defined(__cplusplus)
}
#endif
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#include <sys/stat.h>
#import "zlib.h"
#import "zconf.h"
#include "crypt.h"
#include "ioapi.h"
#include "mztools.h"
#include "unzip.h"
#include "zip.h"
#include "common.h"
#include "aes_via_ace.h"
#include "aes.h"
#include "aesopt.h"
#include "aestab.h"
#include "brg_endian.h"
#include "brg_types.h"
#include "entropy.h"
#include "fileenc.h"
#include "hmac.h"
#include "prng.h"
#include "pwd2key.h"
#include "sha1.h"
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment