int TwoFishCrypt( int direction, /* 1=encrypt or 0=decrypt */ int keySize, const char *passwd, const struct CryptData *data_in, struct CryptData *data_out ) { keyInstance ki; /* key information, including tables */ cipherInstance ci; /* keeps mode (ECB, CBC) and IV */ int i; int pwLen, result; int blkCount = (data_in->len+1)/(BLOCK_SIZE/8) + 1; int byteCnt = (BLOCK_SIZE/8) * blkCount; BYTE * input = (BYTE *) calloc(byteCnt,1); BYTE * output = (BYTE *) calloc(byteCnt,1); memcpy(input, data_in->data, byteCnt); if ( !makeKey(&ki,DIR_ENCRYPT,keySize,NULL) ) { free(input); free(output); return 0; } if ( !cipherInit(&ci,MODE_ECB,NULL) ) { free(input); free(output); return 0; } /* Set key bits from password. */ pwLen = strlen(passwd); for (i=0;i<keySize/32;i++) /* select key bits */ { ki.key32[i] = (i < pwLen) ? passwd[i] : 0; ki.key32[i] ^= passwd[0]; } reKey(&ki); /* encrypt the bytes */ result = direction ? blockEncrypt(&ci, &ki, input, byteCnt*8, output) : blockDecrypt(&ci, &ki, input, byteCnt*8, output); if(result == byteCnt*8) { data_out->data = (BYTE *) malloc(byteCnt); memcpy(data_out->data, output, byteCnt); data_out->len = byteCnt; free(input); free(output); return 1; } free(input); free(output); return 0; }
void OSIEncryption::Initialize( DWORD Seed ) { memset( &m_Key, 0, sizeof(m_Key) ); memset( &m_Cipher, 0, sizeof(m_Cipher) ); memset( m_TFTable, 0, 256 ); makeKey( &m_Key, DIR_DECRYPT, 0x80, NULL ); m_Key.key32[0] = m_Key.key32[1] = m_Key.key32[2] = m_Key.key32[3] = Seed; reKey( &m_Key ); cipherInit( &m_Cipher, MODE_ECB, NULL ); for(int i=0;i<256;i++) m_TFTable[i] = i; ReinitTFTable(); MD5( m_TFTable, 256, m_XORTable ); m_XORPos = 0; }
/** * Initializes the structures that hold the keys and the cipher * * @param ki - the structure where the key information is to be stored * @param ci - the structure where the cipher information is to be stored * @returns 1 */ int thig_key_and_cipher_init(keyInstance *ki , cipherInstance *ci){ int i; BYTE iv[BLOCK_SIZE/8]; if (makeKey(ki,DIR_ENCRYPT,keySize,NULL) != TRUE) return 1; /* 'dummy' setup for a 128-bit key */ if (cipherInit(ci,mode,NULL) != TRUE) return 1; /* 'dummy' setup for cipher */ /* choose a key */ for (i=0;i<keySize/32;i++) (*ki).key32[i]=0x10003 * rand(); reKey(ki); /* run the key schedule */ /* set the initialization vector */ for (i=0;i<sizeof(iv);i++) iv[i]=(BYTE) rand(); memcpy((*ci).iv32,iv,sizeof((*ci).iv32)); /* copy the IV to ci */ return 1; }