Исходные тексты на языке C алгоритмов шифрования DES, ГОСТ, IDEA, Blowfish, страница 2
Описание файла
PDF-файл из архива "Исходные тексты на языке C алгоритмов шифрования DES, ГОСТ, IDEA, Blowfish", который расположен в категории "". Всё это находится в предмете "математические основы криптологии" из 6 семестр, которые можно найти в файловом архиве МАИ. Не смотря на прямую связь этого архива с МАИ, его также можно найти и в других разделах. Архив можно найти в разделе "остальное", в предмете "математические основы криптологии" в общих файлах.
Просмотр PDF-файла онлайн
Текст 2 страницы из PDF
Caller is responsible forshort blocks. */void des_enc(des_ctx *dc, unsigned char *data, int blocks){unsigned long work[2];int i;unsigned char *cp;}cp = data;for(i=0;i<blocks;i++){scrunch(cp,work);desfunc(work,dc->ek);unscrun(work,cp);cp+=8;}void des_dec(des_ctx *dc, unsigned char *data, int blocks){unsigned long work[2];int i;unsigned char *cp;}cp = data;for(i=0;i<blocks;i++){scrunch(cp,work);desfunc(work,dc->dk);unscrun(work,cp);cp+=8;}void main(void){des_ctx dc;int i;unsigned long data[10];char *cp,key[8] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef};char x[8] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xe7};cp = x;des_key(&dc,key);des_enc(&dc,cp,1);printf("Enc(0..7,0..7) = ");for(i=0;i<8;i++) printf("%02x ", ((unsigned int) cp[i])&0x00ff);printf("\n");des_dec(&dc,cp,1);printf("Dec(above,0..7) = ");for(i=0;i<8;i++) printf("%02x ",((unsigned int)cp[i])&0x00ff);printf("\n");cp = (char *) data;for(i=0;i<10;i++)data[i]=i;des_enc(&dc,cp,5); /* Enc 5 blocks.
*/for(i=0;i<10;i+=2) printf("Block %01d = %08lx %08lx.\n",i/2,data[i],data[i+1]);des_dec(&dc,cp,1);des_dec(&dc,cp+8,4);for(i=0;i<10;i+=2) printf("Block %01d = %08lx %08lx.\n",i/2,data[i],data[i+1]);}LOKI91#include <stdio.h>#define LOKIBLK*/#define ROUNDS*/8/* No of bytes in a LOKI data-block16/* No of LOKI roundstypedef unsigned longLOKI blocks */Long;extern Longextern charcopyright/* 64-bit key used by LOKI routines/* String with version no. &lokikey[2];*loki_lib_ver;*//* type specification for aligned*/#ifdef __STDC__/* declare prototypes for libraryfunctions */extern void enloki(char *b);extern void deloki(char *b);extern void setlokikey(char key[LOKIBLK]);#else/* else just declare library functions extern*/extern void enloki(), deloki(), setlokikey();#endif __STDC__char P[32] = {31, 23,29, 21,27, 19,25, 17,};15, 7, 30, 22, 14, 6,13, 5, 28, 20, 12, 4,11, 3, 26, 18, 10, 2,9, 1, 24, 16, 8, 0typedefstruct {short gen;short exp;} sfn_desc;sfn_desc sfn[] = {{ /* 101110111{ /* 110000111{ /* 110001101{ /* 110100011{ /* 110110001{ /* 111000011{ /* 111010111{ /* 111100111{ 00, 00}*/*/*/*/*/*/*/*/};/* irreducible polynomial used in this field *//* exponent used to generate this s function */375,391,397,419,433,451,471,487,31},31},31},31},31},31},31},31},{{{{{{{{/*/*/*/*/*/*/*/*101111011110001011110011111110101001110111101111001111111011101111110011*/*/*/*/*/*/*/*/379,395,415,425,445,463,477,499,31},31},31},31},31},31},31},31},typedef struct {Long loki_subkeys[ROUNDS];} loki_ctx;static Longstatic shortf();s();/* declare LOKI function f *//* declare LOKI S-box fn s */#define ROL12(b) b = ((b << 12) | (b >> 20));#define ROL13(b) b = ((b << 13) | (b >> 19));#ifdef LITTLE_ENDIAN#define bswap(cb) {register charc;c = cb[0]; cb[0] =c = cb[1]; cb[1] =c = cb[4]; cb[4] =c = cb[5]; cb[5] =}#endifcb[3];cb[2];cb[7];cb[6];cb[3]cb[2]cb[7]cb[6]====c;c;c;c;\\\\\\voidsetlokikey(loki_ctx *c, char *key){registeri;register Long KL, KR;#ifdef LITTLE_ENDIANbswap(key);#endifKL = ((Long *)key)[0];KR = ((Long *)key)[1];/* swap bytes round if little-endian */for (i=0; i<ROUNDS; i+=4) {c->loki_subkeys[i] = KL;ROL12 (KL);c->loki_subkeys[i+1] = KL;ROL13 (KL);c->loki_subkeys[i+2] = KR;ROL12 (KR);c->loki_subkeys[i+3] = KR;ROL13 (KR);}#ifdef LITTLE_ENDIANbswap(key);#endif/* Generate the 16 subkeys *//* swap bytes back if little-endian */}voidenloki (loki_ctx *c, char *b){registeri;register Long L, R;#ifdef LITTLE_ENDIANbswap(b);#endif/* left & right data halves*//* swap bytes round if little-endian */L = ((Long *)b)[0];R = ((Long *)b)[1];*/for (i=0; i<ROUNDS; i+=2) {}/* Encrypt with the 16 subkeysL ^= f (R, c->loki_subkeys[i]);R ^= f (L, c->loki_subkeys[i+1]);((Long *)b)[0] = R;((Long *)b)[1] = L;#ifdef LITTLE_ENDIANbswap(b);#endif}/* Y = swap(LR) *//* swap bytes round if little-endian */voiddeloki(loki_ctx *c, char *b){registeri;register Long L, R;#ifdef LITTLE_ENDIANbswap(b);#endif/* left & right data halves/* swap bytes round if little-endian */L = ((Long *)b)[0];R = ((Long *)b)[1];/* LR = X XOR K */for (i=ROUNDS; i>0; i-=2) {order */L ^= f(R, c->loki_subkeys[i-1]);R ^= f(L, c->loki_subkeys[i-2]);}}((Long *)b)[0] = R;((Long *)b)[1] = L;#define MASK12*/static Longf(r, k)register LongLong{Long0x0fffr;k;*//* subkeys in reverse/* Y = LR XOR K *//* 12 bit mask for expansion E/* Data value R(i-1) *//* KeyK(i)*/a, b, c;/* 32 bit S-box output, & P output */a = r ^ k;*/}/* A = R(i-1) XOR K(i) *//* want to use slow speed/small size version */b = ((Long)s((a& MASK12))) | /* B = S(E(R(i-1))^K(i))((Long)s(((a >> 8) & MASK12)) << 8) |((Long)s(((a >> 16) & MASK12)) << 16) |((Long)s((((a >> 24) | (a << 8)) & MASK12)) << 24);perm32(&c, &b, P);/* C = P(S( E(R(i-1)) XOR K(i))) */return(c);/* f returns the result C */static short s(i)register Long i;/* return S-box value for input i */{register short r, c, v, t;short exp8();/* exponentiation routine for GF(2^8) */r = ((i>>8) & 0xc) | (i & 0x3);bottom 2 */c = (i>>2) & 0xff;value-middle 8 bits */t = (c + ((r * 17) ^ 0xff)) & 0xff;v = exp8(t, sfn[r].exp, sfn[r].gen);mod gen */return(v);}#defineMSB0x80000000L/* row value-top 2 &/* column/* base value for Sfn *//* Sfn[r] = t ^ exp/* MSB of 32-bit word */perm32(out, in , perm)Long*out;/* Output 32-bit block to be permutedLong*in;/* Input 32-bit block after permutationcharperm[32];/* Permutation array{Longmask = MSB;/* mask used to set bit inoutput*/register inti, o, b;/* input bit no, output bit no, valueregister char *p = perm;/* ptr to permutation array */*out = 0;for (o=0; o<32; o++) {position o */i =(int)*p++;output o */b = (*in >> i) & 01;if (b)*out |= mask;output i */mask >>= 1;bit*/}}#define SIZE 256/* clear output block *//* For each output bit/* get input bit permuted to/* value of input bit i *//* If the input bit i is set *//* OR in mask to/* Shift mask to next/* 256 elements in GF(2^8) */short mult8(a, b, gen)shorta, b;/* operands for multiply */shortgen;/* irreducible polynomial generating Galois Field */{*/*/*/*/shortproduct = 0;/* result of multiplication */while(b != 0) {non-zero */if (b & 01)product ^= a;of b set */a <<= 1;if (a >= SIZE)a ^= gen;b >>= 1;}return(product);}/* while multiplier is/*add multiplicand if LSB/*shift multiplicand one place *//*/*and modulo reduce if needed */shift multiplier one place */short exp8(base, exponent, gen)shortbase;/* base of exponentiation*/shortexponent;/* exponent*/shortgen;/* irreducible polynomial generating Galois Field */{short accum = base;/* superincreasing sequence of base */short result = 1;/* result of exponentiation*/if (base == 0)return(0);/* if zero base specified then/* the result is "0" if base = 0*/*/while (exponent != 0) {/* repeat while exponent non-zero */if (( exponent & 0x0001) == 0x0001)/* multiply ifexp 1 */result = mult8(result, accum, gen);exponent >>= 1;/* shift exponent to nextdigit */accum = mult8(accum, accum, gen);/* & square */}return(result);}void loki_key(loki_ctx *c, unsigned char *key){setlokikey(c,key);}void loki_enc(loki_ctx *c, unsigned char *data, int blocks){unsigned char *cp;int i;}cp = data;for(i=0;i<blocks;i++){enloki(c,cp);cp+=8;}void loki_dec(loki_ctx *c, unsigned char *data, int blocks){unsigned char *cp;int i;}cp = data;for(i=0;i<blocks;i++){deloki(c,cp);cp+=8;}void main(void){loki_ctxunsignedunsignedunsignedint i;lc;long data[10];char *cp;char key[] = {0,1,2,3,4,5,6,7};for(i=0;i<10;i++) data[i]=i;loki_key(&lc,key);cp = (char *)data;loki_enc(&lc,cp,5);for(i=0;i<10;i+=2) printf("Block %01d = %08lx %08lx\n",i/2,data[i],data[i+1]);loki_dec(&lc,cp,1);loki_dec(&lc,cp+8,4);for(i=0;i<10;i+=2) printf("Block %01d = %08lx %08lx\n",i/2,data[i],data[i+1]);}IDEAtypedeftypedeftypedeftypedeftypedeftypedefunsigned char boolean;/* values are TRUE or FALSE */unsigned char byte; /* values are 0-255 */byte *byteptr;/* pointer to byte */char *string;/* pointer to ASCII character string */unsigned short word16;/* values are 0-65535 */unsigned long word32;/* values are 0-4294967295 */#ifndef TRUE#define FALSE 0#define TRUE (!FALSE)#endif /* if TRUE not already defined */#ifndef min/*#define min(a,b)#define max(a,b)#endif /* if minif min macro not already defined */( (a)<(b) ? (a) : (b) )( (a)>(b) ? (a) : (b) )macro not already defined */#define IDEAKEYSIZE 16#define IDEABLOCKSIZE 8#define IDEAROUNDS 8#define IDEAKEYLEN (6*IDEAROUNDS+4)typedef struct{word16 ek[IDEAKEYLEN],dk[IDEAKEYLEN];}idea_ctx;/* End includes for IDEA.C */#ifdef IDEA32/* Use >16-bit temporaries */#define low16(x) ((x) & 0xFFFF)typedef unsigned int uint16;/* at LEAST 16 bits, maybe more */#else#define low16(x) (x) /* this is only ever applied to uint16's */typedef word16 uint16;#endif#ifdef SMALL_CACHEstatic uint16mul(register uint16 a, register uint16 b){register word32 p;p = (word32)a * b;if (p) {b = low16(p);a = p>>16;return (b - a) + (b < a);} else if (a) {return 1-b;} else {return 1-a;}} /* mul */#endif /* SMALL_CACHE */static uint16mulInv(uint16 x){uint16 t0, t1;uint16 q, y;if (x <= 1)return x;/* 0 and 1 are self-inverse */t1 = 0x10001L / x;/* Since x >= 2, this fits into 16 bits */y = 0x10001L % x;if (y == 1)return low16(1-t1);t0 = 1;do {q = x / y;x = x % y;t0 += q * t1;if (x == 1)return t0;q = y / x;y = y % x;t1 += q * t0;} while (y != 1);return low16(1-t1);} /* mukInv */static voidideaExpandKey(byte const *userkey, word16 *EK){int i,j;for (j=0; j<8; j++) {EK[j] = (userkey[0]<<8) + userkey[1];userkey += 2;}for (i=0; j < IDEAKEYLEN; j++) {i++;EK[i+7] = EK[i & 7] << 9 | EK[i+1 & 7] >> 7;EK += i & 8;i &= 7;}} /* ideaExpandKey */static voidideaInvertKey(word16 const *EK, word16 DK[IDEAKEYLEN]){int i;uint16 t1, t2, t3;word16 temp[IDEAKEYLEN];word16 *p = temp + IDEAKEYLEN;t1 =t2 =t3 =*--p*--p*--p*--pmulInv(*EK++);-*EK++;-*EK++;= mulInv(*EK++);= t3;= t2;= t1;for (i = 0;t1 =*--p*--pt1 =t2 =t3 =*--p*--p*--p*--pi < IDEAROUNDS-1; i++) {*EK++;= *EK++;= t1;mulInv(*EK++);-*EK++;-*EK++;= mulInv(*EK++);= t2;= t3;= t1;}t1 = *EK++;*--p = *EK++;*--p = t1;t1 = mulInv(*EK++);t2 = -*EK++;t3 = -*EK++;*--p = mulInv(*EK++);*--p = t3;*--p = t2;*--p = t1;/* Copy and destroy temp copy */memcpy(DK, temp, sizeof(temp));for(i=0;i<IDEAKEYLEN;i++)temp[i]=0;} /* ideaInvertKey */#ifdef SMALL_CACHE#define MUL(x,y) (x = mul(low16(x),y))#else /* !SMALL_CACHE */#ifdef AVOID_JUMPS#define MUL(x,y) (x = low16(x-1), t16 = low16((y)-1), \t32 = (word32)x*t16 + x + t16 + 1, x = low16(t32), \t16 = t32>>16, x = (x-t16) + (x<t16) )#else /* !AVOID_JUMPS (default) */#define MUL(x,y) \((t16 = (y)) ? \(x=low16(x)) ? \t32 = (word32)x*t16, \x = low16(t32), \t16 = t32>>16, \x = (x-t16)+(x<t16) \: \: \#endif#endif(x = 1-t16) \(x = 1-x))static voidideaCipher(byte *inbuf, byte *outbuf, word16 *key){register uint16 x1, x2, x3, x4, s2, s3;word16 *in, *out;#ifndef SMALL_CACHEregister uint16 t16; /* Temporaries needed by MUL macro */register word32 t32;#endifint r = IDEAROUNDS;in = (word16 *)inbuf;x1 = *in++; x2 = *in++;x3 = *in++; x4 = *in;#ifndef HIGHFIRSTx1 = (x1 >>8) | (x1<<8);x2 = (x2 >>8) | (x2<<8);x3 = (x3 >>8) | (x3<<8);x4 = (x4 >>8) | (x4<<8);#endifdo {MUL(x1,*key++);x2 += *key++;x3 += *key++;MUL(x4, *key++);s3 = x3;x3 ^= x1;MUL(x3, *key++);s2 = x2;x2 ^= x4;x2 += x3;MUL(x2, *key++);x3 += x2;x1 ^= x2;x4 ^= x3;x2 ^= s3;} while (--r);MUL(x1, *key++);x3 += *key++;x2 += *key++;MUL(x4, *key);x3 ^= s2;out = (word16 *)outbuf;#ifdef HIGHFIRST*out++ = x1;*out++ = x3;*out++ = x2;*out = x4;#else /* !HIGHFIRST */*out++ = (x1 >>8) | (x1<<8);*out++ = (x3 >>8) | (x3<<8);*out++ = (x2 >>8) | (x2<<8);*out = (x4 >>8) | (x4<<8);#endif} /* ideaCipher */void idea_key(idea_ctx *c, unsigned char *key){ideaExpandKey(key,c->ek);ideaInvertKey(c->ek,c->dk);}void idea_enc(idea_ctx *c, unsigned char *data, int blocks){int i;unsigned char *d = data;}for(i=0;i<blocks;i++){ideaCipher(d,d,c->ek);d+=8;}void idea_dec(idea_ctx *c, unsigned char *data, int blocks){int i;unsigned char *d = data;}for(i=0;i<blocks;i++){ideaCipher(d,d,c->dk);d+=8;}#include <stdio.h>#ifndef#ifndef#define#endif#define#endifBLOCKSKBYTESKBYTES 1024BLOCKS (64*KBYTES)intmain(void){/* Test driver for IDEA cipher */int i, j, k;idea_ctx c;byte userkey[16];word16 EK[IDEAKEYLEN], DK[IDEAKEYLEN];byte XX[8], YY[8], ZZ[8];word32 long_block[10]; /* 5 blocks */long l;char *lbp;/* Make a sample user key for testing...