#include "NewtonScript.h" #include "nce_basic.h" #include "nce_idea.h" #define low16(x) ((x) & 0xFFFF) #define MUL(x,y) (x = (uint16_t) low16(x-1), t16 = (uint16_t) low16((y)-1), \ t32 = (uint32_t)x*t16+x+t16+1, x = (uint16_t) low16(t32), \ t16 = (uint16_t) (t32>>16), x = (uint16_t)(x-t16+(x= 2, this fits into 16 bits */ y = (uint16_t)(0x10001L % x); if (y == 1) return (uint16_t) low16(1-t1); t0 = 1; do { q = (uint16_t) (x / y); x = (uint16_t) (x % y); t0 += (uint16_t)(q * t1); if (x == 1) return t0; q = (uint16_t)(y / x); y = (uint16_t)(y % x); t1 += (uint16_t)(q * t0); } while (y != 1); return (uint16_t)low16(1-t1); } /* inv */ static void en_key_idea(uint16_t *userkey, uint16_t *EK) { int i,j; for (j=0; j<8; j++) EK[j] = *userkey++; for (i=0; j> 7)); EK += i & 8; i &= 7; } } /* en_key_idea */ static void de_key_idea(IDEAkey EK, IDEAkey DK) { int j; uint16_t t1, t2, t3; IDEAkey T; uint16_t *p = T + KEYLEN; t1 = inv(*EK++); t2 = (uint16_t)-*EK++; t3 = (uint16_t)-*EK++; *--p = inv(*EK++); *--p = t3; *--p = t2; *--p = t1; for (j = 1; j < ROUNDS; j++) { t1 = *EK++; *--p = *EK++; *--p = t1; t1 = inv(*EK++); t2 = (uint16_t)-*EK++; t3 = (uint16_t)-*EK++; *--p = inv(*EK++); *--p = t2; *--p = t3; *--p = t1; } t1 = *EK++; *--p = *EK++; *--p = t1; t1 = inv(*EK++); t2 = (uint16_t)-*EK++; t3 = (uint16_t)-*EK++; *--p = inv(*EK++); *--p = t3; *--p = t2; *--p = t1; /* Copy and destroy temp copy */ for (j = 0, p = T; j < KEYLEN; j++) { *DK++ = *p; *p++ = 0; } } /* de_key_idea */ static void cipher_idea(uint16_t in[4], uint16_t out[4], register IDEAkey Z) { register uint16_t x1, x2, x3, x4, s2, s3; register uint16_t t16; register uint32_t t32; int r = ROUNDS; x1 = *in++; x2 = *in++; x3 = *in++; x4 = *in; do { MUL(x1,*Z++); x2 += *Z++; x3 += *Z++; MUL(x4, *Z++); s3 = x3; x3 ^= x1; MUL(x3, *Z++); s2 = x2; x2 ^= x4; x2 += x3; MUL(x2, *Z++); x3 += x2; x1 ^= x2; x4 ^= x3; x2 ^= s3; x3 ^= s2; } while (--r); MUL(x1, *Z++); *out++ = x1; *out++ = (uint16_t)(x3 + *Z++); *out++ = (uint16_t)(x2 + *Z++); MUL(x4, *Z); *out = x4; } /* cipher_idea */ extern "C" Ref nce_idea(RefArg rcvr, RefArg plaintext, RefArg ciphertext, RefArg ideakey) { IDEAkey EK, DK; uint16_t userkey[8] = {0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007}; uint16_t plaintxt[4] = {0x0000, 0x0001, 0x0002, 0x0003}; uint16_t ciphertxt[4]; en_key_idea(userkey, EK); de_key_idea(EK, DK); cipher_idea(plaintxt, ciphertxt, EK); return MakeString((char *)ciphertxt); }