static void rijndaelIVKAT (FILE *fp, int keyLength) {
	int i;
	BYTE pt[4*4], ct[4*4];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;
	char format[10];
#ifdef TRACE_KAT_MCT
	printf ("Executing Intermediate value KAT (key %d): ", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */

	fprintf(fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n",
		keyLength);
	fflush(fp);
	memset(keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf(&keyMaterial[2*i], "%02X", i);
	}
	fprintf(fp, "KEY=%s\n", keyMaterial);
	
	for (i = 0; i < 16; i++) {
		pt[i] = i;
	}
	
	fprintf(fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	blockPrint(fp, pt, "PT");
	cipherInit(&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, i);
		sprintf(format, "CT%d", i);
		blockPrint(fp, ct, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, keyInst.Nr);
	blockPrint(fp, ct, "CT");
	
	fprintf(fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	blockPrint(fp, ct, "CT");
	cipherInit(&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, i);
		sprintf(format, "PT%d", i);
		blockPrint(fp, pt, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, keyInst.Nr);
	blockPrint(fp, pt, "PT");
	
#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif 
}
static void rijndaelVTKAT(FILE *fp, int keyLength) {
	int i;
	BYTE block[4*4];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	printf("Executing Variable-Text KAT (key %d): ", keyLength);
	fflush(stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf(fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n"
		"\n", keyLength);
	fflush(fp);
	memset(keyMaterial, 0, sizeof (keyMaterial));
	memset(keyMaterial, '0', keyLength/4);
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	fprintf(fp, "KEY=%s\n", keyMaterial);
	for (i = 0; i < 128; i++) {
		memset(block, 0, 16);
		block[i/8] |= 1 << (7 - i%8); /* set only the i-th bit of the i-th test block */
		fprintf (fp, "\nI=%d\n", i+1);
		blockPrint(fp, block, "PT");
		cipherInit(&cipherInst, MODE_ECB, NULL);
		blockEncrypt(&cipherInst, &keyInst, block, 128, block);
		blockPrint(fp, block, "CT");
	}
#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif /* ?TRACE_KAT_MCT */
}
Beispiel #3
0
static void rijndaelVKKAT(FILE * fp, int keyLength)
{
        int i, j, r;
        BYTE block[4 * 4];
        BYTE keyMaterial[320];
        BYTE byteVal = (BYTE) '8';
        keyInstance keyInst;
        cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
        printf("Executing Variable-Key KAT (key %d): ", keyLength);
        fflush(stdout);
#endif                          /* ?TRACE_KAT_MCT */
        fprintf(fp, "\n" "==========\n" "\n" "KEYSIZE=%d\n" "\n", keyLength);
        fflush(fp);
        memset(block, 0, 16);
        blockPrint(fp, block, "PT");
        memset(keyMaterial, 0, sizeof(keyMaterial));
        memset(keyMaterial, '0', keyLength / 4);
        for (i = 0; i < keyLength; i++) {
                keyMaterial[i / 4] = byteVal;   /* set only the i-th bit of the i-th test key */
                r = makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
                if (TRUE != r) {
                        fprintf(stderr, "makeKey error %d\n", r);
                        exit(-1);
                }
                fprintf(fp, "\nI=%d\n", i + 1);
                fprintf(fp, "KEY=%s\n", keyMaterial);
                memset(block, 0, 16);
                r = cipherInit(&cipherInst, MODE_ECB, NULL);
                if (TRUE != r) {
                        fprintf(stderr, "cipherInit error %d\n", r);
                        exit(-1);
                }
                r = blockEncrypt(&cipherInst, &keyInst, block, 128, block);
                if (128 != r) {
                        fprintf(stderr, "blockEncrypt error %d\n", r);
                        exit(-1);
                }
                blockPrint(fp, block, "CT");
                /* now check decryption: */
                makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
                blockDecrypt(&cipherInst, &keyInst, block, 128, block);
                for (j = 0; j < 16; j++) {
                        assert(block[j] == 0);
                }
                /* undo changes for the next iteration: */
                keyMaterial[i / 4] = (BYTE) '0';
                byteVal =
                    (byteVal == '8') ? '4' :
                    (byteVal == '4') ? '2' : (byteVal == '2') ? '1' :
                    /*      (byteVal == '1') */ '8';
        }
        assert(byteVal == (BYTE) '8');

#ifdef TRACE_KAT_MCT
        printf(" done.\n");
#endif                          /* ?TRACE_KAT_MCT */
}                               /* rijndaelVKKAT */
Beispiel #4
0
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;
}
Beispiel #5
0
AES_Struct *
AES_Create() {
	AES_Struct *aes;

	aes = (AES_Struct *) malloc(sizeof(AES_Struct));
	if (aes != NULL) {
		cipherInit(&aes->cipher, MODE_ECB, NULL);
		aes->cfb128_idx = -1;
		aes->key_gen = 0;
	}
	return aes;
}
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;
}
Beispiel #7
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;
}
void decryptBuffer(char* buffer,int bufferSize){
  int i;
  char *currentBlock;
  if(bufferSize % 16 != 0) {
    /*Panic*/
    return;
  }
  /*Setting the key direction to Depcrypt*/
  keyInst.direction = DIR_DECRYPT;
  makeKey(&keyInst, DIR_DECRYPT, 128,keyMaterial);
  cipherInit(&cipherInst, MODE_ECB, NULL);
  /*Decrypt the buffer*/
  for(i = 0; i< bufferSize; i+=16) {
    /*Copying out a block*/
    memcpy(currentBlock,buffer+i,16);
    /*Encrypting block*/
    blockDecrypt(&cipherInst, &keyInst, currentBlock, 16 * 8, currentBlock);
    /*Copying in the Decrypted block*/
    memcpy(buffer+i,currentBlock,16);
  }
  return;
}
Beispiel #9
0
int bc_aes_cbc_dec(uint8_t *out, int *out_len, uint8_t *in,
		int in_len, uint8_t *key, int key_len, uint8_t *iv) {
	keyInstance key_inst;
	cipherInstance cipher_inst;
	
	if (*out_len < in_len) {
		return STS_ERR;
	}
	
	if (makeKey2(&key_inst, DIR_DECRYPT, key_len, (char *)key) != TRUE) {
		return STS_ERR;
	}
	if (cipherInit(&cipher_inst, MODE_CBC, NULL) != TRUE) {
		return STS_ERR;
	}
	memcpy(cipher_inst.IV, iv, BC_LEN);
	*out_len = padDecrypt(&cipher_inst, &key_inst, in, in_len, out);
	if (*out_len <= 0) {
		return STS_ERR;
	}
	return STS_OK;
}
Beispiel #10
0
NTSTATUS
CreateCipher(
	 PNCIPHER_INSTANCE		*Cipher,
	 BYTE					CipherType,
	 BYTE					Mode,
	 int					ExtraKeyLength,
	 PBYTE					ExtraKey
){
	int					instLength;
	PNCIPHER_INSTANCE	tmpCipher;
	int					ret;

	if(!Cipher) {
		KDPrintM(DBG_OTHER_ERROR, ("Cipher parameter is NULL!\n"));
		return STATUS_INVALID_PARAMETER;
	}

	switch(CipherType)
	{
	case NDAS_CIPHER_SIMPLE: {
		PCIPHER_HASH	cipherHash;
	
		if(!ExtraKey) {
			KDPrintM(DBG_OTHER_ERROR, ("Hash key is NULL.\n"));
			return STATUS_INVALID_PARAMETER;
		}
		if(ExtraKeyLength != HASH_KEY_LENGTH) {
			KDPrintM(DBG_OTHER_ERROR, ("Hash key length invalid. ExtraKeyLength=%d\n", ExtraKeyLength));
			return STATUS_INVALID_PARAMETER;
		}

		instLength = sizeof(NCIPHER_INSTANCE) - sizeof(BYTE) + sizeof(CIPHER_HASH);
		tmpCipher = (PNCIPHER_INSTANCE)ExAllocatePoolWithTag(NonPagedPool, instLength, NCIPHER_POOLTAG_CIPHERINSTANCE);
		if(!tmpCipher) {
			KDPrintM(DBG_OTHER_ERROR, ("Could not allocate Cipher instance.\n"));
			return STATUS_INSUFFICIENT_RESOURCES;
		}
		RtlZeroMemory(tmpCipher, instLength);
		tmpCipher->CipherType = NDAS_CIPHER_SIMPLE;
		tmpCipher->InstanceSpecificLength = sizeof(CIPHER_HASH);

		//
		//	Set Hash key.
		//
		cipherHash = (PCIPHER_HASH)tmpCipher->InstanceSpecific;
		RtlCopyMemory(cipherHash->HashKey, ExtraKey, HASH_KEY_LENGTH);

		*Cipher = tmpCipher;
	}
	break;
	case NDAS_CIPHER_AES:
		instLength = sizeof(NCIPHER_INSTANCE) - sizeof(BYTE) + sizeof(cipherInstance);
		tmpCipher = (PNCIPHER_INSTANCE)ExAllocatePoolWithTag(NonPagedPool, instLength, NCIPHER_POOLTAG_CIPHERINSTANCE);
		if(!tmpCipher) {
			KDPrintM(DBG_OTHER_ERROR, ("Could not allocate Cipher instance.\n"));
			return STATUS_INSUFFICIENT_RESOURCES;
		}
		RtlZeroMemory(tmpCipher, instLength);
		tmpCipher->CipherType = NDAS_CIPHER_AES;
		tmpCipher->InstanceSpecificLength = sizeof(cipherInstance);

		ret = cipherInit((cipherInstance *)tmpCipher->InstanceSpecific, Mode, NULL);
		if(ret != TRUE) {
			ExFreePool(tmpCipher);
			KDPrintM(DBG_OTHER_ERROR, ("Could not initialize the Cipher. ERRORCODE:%d\n", ret));
			return STATUS_UNSUCCESSFUL;
		}

		*Cipher = tmpCipher;
	break;
	default:
		return STATUS_INVALID_PARAMETER;
	}

	return STATUS_SUCCESS;
}
static void makeFIPSTestVectors(const char *fipsFile) {
	int i, keyLength, r;
	keyInstance keyInst;
	cipherInstance cipherInst;
	BYTE keyMaterial[320];
	u8 pt[16], ct[16];
	char format[64];
	FILE *fp;

#ifdef TRACE_KAT_MCT
	printf("Generating FIPS test vectors...");
#endif /* ?TRACE_KAT_MCT */
	
	fp = fopen(fipsFile, "w");
	fprintf(fp,
		"\n"
		"================================\n\n"
		"FILENAME:  \"%s\"\n\n"
		"FIPS Test Vectors\n",
		fipsFile);

	/* 128-bit key: 00010103...0e0f: */
	keyLength = 128;
	memset(keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf(&keyMaterial[2*i], "%02X", i);
	}
	
	fprintf(fp, "\n================================\n\n");
	fprintf(fp, "KEYSIZE=128\n\n");
    fprintf(fp, "KEY=%s\n\n", keyMaterial);

	/* plaintext is always 00112233...eeff: */
	for (i = 0; i < 16; i++) {
		pt[i] = (i << 4) | i;
	}

    /* encryption: */	
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "Round Subkey Values (Encryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	blockPrint(fp, pt, "PT");
	for (i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, i);
		sprintf(format, "CT%d", i);
		blockPrint(fp, ct, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, keyInst.Nr);
	blockPrint(fp, ct, "CT");
	
    /* decryption: */	
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "\nRound Subkey Values (Decryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	blockPrint(fp, ct, "CT");
	for (i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, i);
		sprintf(format, "PT%d", i);
		blockPrint(fp, pt, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, keyInst.Nr);
	blockPrint(fp, pt, "PT");

	/* 192-bit key: 00010103...1617: */
	keyLength = 192;
	memset(keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf(&keyMaterial[2*i], "%02X", i);
	}
	
	fprintf(fp, "\n================================\n\n");
	fprintf(fp, "KEYSIZE=192\n\n");
    fprintf(fp, "KEY=%s\n\n", keyMaterial);

	/* plaintext is always 00112233...eeff: */
	for (i = 0; i < 16; i++) {
		pt[i] = (i << 4) | i;
	}

    /* encryption: */	
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "\nRound Subkey Values (Encryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	blockPrint(fp, pt, "PT");
	for (i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, i);
		sprintf(format, "CT%d", i);
		blockPrint(fp, ct, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, keyInst.Nr);
	blockPrint(fp, ct, "CT");
	
    /* decryption: */	
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "\nRound Subkey Values (Decryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	blockPrint(fp, ct, "CT");
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, i);
		sprintf(format, "PT%d", i);
		blockPrint(fp, pt, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, keyInst.Nr);
	blockPrint(fp, pt, "PT");

	/* 256-bit key: 00010103...1e1f: */
	keyLength = 256;
	memset(keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf(&keyMaterial[2*i], "%02X", i);
	}
	
	fprintf(fp, "\n================================\n\n");
	fprintf(fp, "KEYSIZE=256\n\n");
    fprintf(fp, "KEY=%s\n\n", keyMaterial);

	/* plaintext is always 00112233...eeff: */
	for (i = 0; i < 16; i++) {
		pt[i] = (i << 4) | i;
	}

    /* encryption: */	
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "\nRound Subkey Values (Encryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	blockPrint(fp, pt, "PT");
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, i);
		sprintf(format, "CT%d", i);
		blockPrint(fp, ct, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, keyInst.Nr);
	blockPrint(fp, ct, "CT");
	
    /* decryption: */	
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	cipherInit(&cipherInst, MODE_ECB, NULL);
	fprintf(fp, "\nRound Subkey Values (Decryption)\n\n");
    for (r = 0; r <= keyInst.Nr; r++) {
        fprintf(fp, "RK%d=", r);
        for (i = 0; i < 4; i++) {
            u32 w = keyInst.rk[4*r + i];
            fprintf(fp, "%02X%02X%02X%02X", w >> 24, (w >> 16) & 0xff, (w >> 8) & 0xff, w & 0xff);
        }
        fprintf(fp, "\n");
    }
	fprintf(fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	blockPrint(fp, ct, "CT");
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, i);
		sprintf(format, "PT%d", i);
		blockPrint(fp, pt, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, keyInst.Nr);
	blockPrint(fp, pt, "PT");

    fprintf(fp, "\n");
	fclose(fp);
#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif /* ?TRACE_KAT_MCT */
}
static void rijndaelCBC_MCT(FILE *fp, int keyLength, BYTE direction) {
	int i, j, r, t;
	BYTE inBlock[256/8], outBlock[256/8], binKey[256/8], cv[256/8];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	int width = 0;
	clock_t elapsed = -clock();
	printf("Executing CBC MCT (%s, key %d): ",
		direction == DIR_ENCRYPT ? "ENCRYPT" : "DECRYPT", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf (fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n", keyLength);
	fflush(fp);
	memset(cv, 0, 16);
	memset(inBlock, 0, 16);
	memset(binKey, 0, keyLength/8);
	for (i = 0; i < 400; i++) {
#ifdef TRACE_KAT_MCT                 
        while (width-- > 0) {
        	putchar('\b');
        }
        width = printf("%d", i);
        fflush(stdout);    
#endif /* ?TRACE_KAT_MCT */
		fprintf (fp, "\nI=%d\n", i);
		/* prepare key: */
		for (j = 0; j < keyLength/8; j++) {
			sprintf (&keyMaterial[2*j], "%02X", binKey[j]);
		}
		keyMaterial[keyLength/4] = 0;
		fprintf(fp, "KEY=%s\n", keyMaterial);
		r = makeKey(&keyInst, direction, keyLength, keyMaterial);
		if (TRUE != r) {
			fprintf(stderr,"makeKey error %d\n",r);
			exit(-1);
		}
		r = cipherInit(&cipherInst, MODE_ECB, NULL);
		if (TRUE != r) {
			fprintf(stderr,"cipherInit error %d\n",r);
			exit(-1);
		}
		/* do encryption/decryption: */
		blockPrint(fp, cv, "IV");
		blockPrint(fp, inBlock, direction == DIR_ENCRYPT ? "PT" : "CT");
		if (direction == DIR_ENCRYPT) {
			for (j = 0; j < 10000; j++) {
				for (t = 0; t < 16; t++) {
					inBlock[t] ^= cv[t];
				}
				r = blockEncrypt(&cipherInst, &keyInst, inBlock, 128, outBlock);
				if (128 != r) {
					fprintf(stderr,"blockEncrypt error %d\n",r);
					exit(-1);
				}
				memcpy(inBlock, cv, 16);
				memcpy(cv, outBlock, 16);
			}
		} else {
			for (j = 0; j < 10000; j++) {
				blockDecrypt(&cipherInst, &keyInst, inBlock, 128, outBlock);
				for (t = 0; t < 16; t++) {
					outBlock[t] ^= cv[t];
				}
				memcpy(cv, inBlock, 16);
				memcpy(inBlock, outBlock, 16);
			}
		}
		blockPrint(fp, outBlock, direction == DIR_ENCRYPT ? "CT" : "PT");
		/* prepare new key: */
		switch (keyLength) {
		case 128:
			for (j = 0; j < 128/8; j++) {
				binKey[j] ^= outBlock[j];
			}
			break;
		case 192:
			for (j = 0; j < 64/8; j++) {
				if (direction == DIR_ENCRYPT) {
					binKey[j] ^= inBlock[j + 64/8];
				} else {
					binKey[j] ^= cv[j + 64/8];
				}
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 64/8] ^= outBlock[j];
			}
			break;
		case 256:
			for (j = 0; j < 128/8; j++) {
				if (direction == DIR_ENCRYPT) {
					binKey[j] ^= inBlock[j];
				} else {
					binKey[j] ^= cv[j];
				}
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 128/8] ^= outBlock[j];
			}
			break;
		}
	}
#ifdef TRACE_KAT_MCT
	elapsed += clock();
    while (width-- > 0) {
    	putchar('\b');
    }
	printf("%d done (%.1f s).\n", i, (float)elapsed/CLOCKS_PER_SEC);
#endif /* ?TRACE_KAT_MCT */
} /* rijndaelCBC_MCT */
Beispiel #13
0
int main(void) {
  int bitsPerShortKey, result;
  BLOCK T, plainText, cipherText, recoveredPlainText, recoveredCipherText;
  char asciiKey[HEX_DIGITS_PER_KEY+1];
  char asciiT[HEX_DIGITS_PER_BLOCK+1];
  keyInstance key;
  cipherInstance cipher;
  char* masterAsciiPattern = 
    "0123456789abcdeffedcba9876543210"
    "00112233445566778899aabbccddeeff"
    "ffeeddccbbaa99887766554433221100";

  assert(strlen(masterAsciiPattern) 
         >= HEX_DIGITS_PER_BLOCK+HEX_DIGITS_PER_KEY);
  /* ...otherwise we need to put more hex digits in it! */

  printf(
         "/*\n"
         "\n"
         "For each key size, this test program picks a key K and a\n"
         "block-sized test pattern T (not all 0s: we use an asymmetric\n"
         "pattern to highlight any word swaps). It then encrypts T under K\n"
         "and decrypts the result, showing all the intermediate values\n"
         "along the way; it then DEcrypts T under K and encrypts the\n"
         "result, again showing all intermediate values.\n"
         "\n"
         "The intermediate values shown are: the 256-bit long key (LONG_KEY)\n"
         "corresponding to the supplied key; all the subkeys of the key\n"
         "schedule, both in bitslice (SK[]) and in standard (SK^[])\n"
         "format, and the outputs of all the rounds (R[], or Rinv[] for\n"
         "the inverse rounds while decrypting). The relevant round number\n"
         "for each result appears within the square brackets.\n"
         "\n"
         "Note that this reference implementation, since it does not\n"
         "implement the fast bitslice variant, only uses the standard keys\n"
         "(SK^[]) in its rounds. However the algorithm's description\n"
         "defines those in terms of the bitslice keys (SK[]), which need\n"
         "to be precomputed first, so these are shown as well.\n"
         "\n"
         "The subkeys are all precomputed within makeKey(), since they\n"
         "remain the same for all the blocks processed under the same key;\n"
         "for this reason, they all appear at the beginning instead of\n"
         "being interleaved with the round values.\n"
         "\n"
         "In keeping with the convention adopted in other NIST example\n"
         "files, there is a blank line between the output of different\n"
         "blocks. There are no blank lines between internal results\n"
         "pertaining to the same block.\n"
         "\n"
         "Note also that printing of intermediate values can be turned on\n"
         "or off for *any* test run (not that you'd want to do it in those\n"
         "that run millions of encryptions, though...) simply by linking\n"
         "the desired main program with serpent-reference-show-internals.o\n"
         "instead of the regular serpent-reference.o. As you might have\n"
         "guessed, you obtain the former by compiling serpent-reference.c\n"
         "with -DSHOW_INTERNALS. Conversely, this same test can be run\n"
         "with just the top-level results (and no intermediate printouts)\n"
         "by simply linking it with serpent-reference.o. See the Makefile\n"
         "for more details.\n"
         "\n"
         "*/\n"
         "\n"
         );

  printHeader("ecb_iv", "Electronic Codebook (ECB) Mode",
              "Intermediate Values Known Answer Tests");

  strncpy(asciiT, masterAsciiPattern, HEX_DIGITS_PER_BLOCK);
  asciiT[HEX_DIGITS_PER_BLOCK] = 0;
  result = stringToWords(asciiT, T, WORDS_PER_BLOCK);
  if (result != TRUE) goto error;

  for(bitsPerShortKey=BITS_PER_SHORTEST_KEY; bitsPerShortKey<=BITS_PER_KEY;
      bitsPerShortKey+=BITS_PER_KEY_STEP) {

    /* make the key and set things up */
    printf("KEYSIZE=%d\n\n", bitsPerShortKey);
    strncpy(asciiKey, &masterAsciiPattern[HEX_DIGITS_PER_BLOCK],
            bitsPerShortKey/BITS_PER_HEX_DIGIT);
    asciiKey[bitsPerShortKey/BITS_PER_HEX_DIGIT] = 0;
    printf("KEY=%s\n\n", asciiKey);
    result = makeKey(&key, DIR_ENCRYPT, bitsPerShortKey, asciiKey);
    if (result != TRUE) goto error;
    printf("\n");
    result = cipherInit(&cipher, MODE_ECB, 0);
    if (result != TRUE) goto error;

    /* encrypt T */
    key.direction = DIR_ENCRYPT;
    render("PT=", T, WORDS_PER_BLOCK);
    result = blockEncrypt(&cipher, &key, (BYTE*) T, BITS_PER_BLOCK,
                          (BYTE*) cipherText);
    if (result < 0) {
      goto error;
    } else if (result != BITS_PER_BLOCK) {
      result = BAD_NUMBER_OF_BITS_PROCESSED;
      goto error;
    }
    render("CT=", cipherText, WORDS_PER_BLOCK);
    printf("\n");

    /* decrypt and see if it comes out the same */
    key.direction = DIR_DECRYPT;
    render("CT=", cipherText, WORDS_PER_BLOCK);
    result = blockDecrypt(&cipher, &key, (BYTE*) cipherText, BITS_PER_BLOCK,
                          (BYTE*) recoveredPlainText);
    if (result < 0) {
      goto error;
    } else if (result != BITS_PER_BLOCK) {
      result = BAD_NUMBER_OF_BITS_PROCESSED;
      goto error;
    }
    render("PT=", recoveredPlainText, WORDS_PER_BLOCK);
    if (memcmp((BYTE*)T, (BYTE*)recoveredPlainText, BYTES_PER_BLOCK)) {
      result = DECRYPTION_MISMATCH;
      goto error;
    }
    printf("\n");

    /* decrypt T */
    key.direction = DIR_DECRYPT;
    render("CT=", T, WORDS_PER_BLOCK);
    result = blockDecrypt(&cipher, &key, (BYTE*) T, BITS_PER_BLOCK,
                          (BYTE*) plainText);
    if (result < 0) {
      goto error;
    } else if (result != BITS_PER_BLOCK) {
      result = BAD_NUMBER_OF_BITS_PROCESSED;
      goto error;
    }
    render("PT=", plainText, WORDS_PER_BLOCK);
    printf("\n");

    /* encrypt and see if it comes out the same */
    key.direction = DIR_ENCRYPT;
    render("PT=", plainText, WORDS_PER_BLOCK);
    result = blockEncrypt(&cipher, &key, (BYTE*) plainText, BITS_PER_BLOCK,
                          (BYTE*) recoveredCipherText);
    if (result < 0) {
      goto error;
    } else if (result != BITS_PER_BLOCK) {
      result = BAD_NUMBER_OF_BITS_PROCESSED;
      goto error;
    }
    render("CT=", recoveredCipherText, WORDS_PER_BLOCK);
    if (memcmp((BYTE*)recoveredCipherText, (BYTE*)T, BYTES_PER_BLOCK)) {
      result = ENCRYPTION_MISMATCH;
      goto error;
    }
    printf("\n");

    printf("==========\n\n");
  }
  exit(0);

error:
  printf("Error %d (sorry, see serpent-api.h to see what this means)\n",
         result);
  exit(result);
}
static void rijndaelTKAT(FILE *fp, int keyLength, FILE *in) {
	int i, j;
	unsigned int s;
	BYTE block[4*4], block2[4*4];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	printf("Executing Tables KAT (key %d): ", keyLength);
	fflush(stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf(fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n"
		"\n", keyLength);
	fflush(fp);

	memset(keyMaterial, 0, sizeof (keyMaterial));
	
	for (i = 0; i < 64; i++) {
		fprintf(fp, "\nI=%d\n", i+1);
		for(j = 0; j < keyLength/4; j++) {
			fscanf(in, "%c", &keyMaterial[j]);
		}
		makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
		
		fprintf(fp, "KEY=%s\n", keyMaterial);
		
		for (j = 0; j < 16; j++) {
			fscanf(in, "%02x", &s);
			block[j] = s;
		}
		fscanf(in, "%c", (char *)&s);
		fscanf(in, "%c", (char *)&s);
		blockPrint(fp, block, "PT");
		cipherInit(&cipherInst, MODE_ECB, NULL);
		blockEncrypt(&cipherInst, &keyInst, block, 128, block2);
		blockPrint(fp, block2, "CT");
	}
	for (i = 64; i < 128; i++) {
		fprintf(fp, "\nI=%d\n", i+1);
		for(j = 0; j < keyLength/4; j++) {
			fscanf(in, "%c", &keyMaterial[j]);
		}
		makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
		
		fprintf(fp, "KEY=%s\n", keyMaterial);
		
		for (j = 0; j < 16; j++) {
			fscanf(in, "%02x", &s);
			block[j] = s;
		}
		fscanf(in, "%c", (char *)&s);
		fscanf(in, "%c", (char *)&s);
		cipherInit(&cipherInst, MODE_ECB, NULL);
		blockDecrypt(&cipherInst, &keyInst, block, 128, block2);
		blockPrint(fp, block2, "PT");
		blockPrint(fp, block, "CT");
	}

#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif /* ?TRACE_KAT_MCT */
}
Beispiel #15
0
int main(void) {
  int i, j, bitsPerShortKey, result;
  BLOCK plainText, cipherText, PT_9998;
  KEY binaryKey;
  char asciiKey[HEX_DIGITS_PER_KEY+1];
  keyInstance key;
  cipherInstance cipher;


  /* The hack that remembers PT_9998 only works if... */
  assert(BITS_PER_KEY <= 2*BITS_PER_BLOCK);
  /* ...otherwise we'd have to remember more than just PT_9998. */

  printHeader("ecb_d_m", "Electronic Codebook (ECB) Mode - DECRYPTION",
              "Monte Carlo Test");

  for(bitsPerShortKey=BITS_PER_SHORTEST_KEY; bitsPerShortKey<=BITS_PER_KEY;
      bitsPerShortKey+=BITS_PER_KEY_STEP) {
    result = stringToWords("00000000000000000000000000000000", cipherText,
                           WORDS_PER_BLOCK);
    if (result != TRUE) goto error;

    printf("KEYSIZE=%d\n\n", bitsPerShortKey);

    /* Construct (backwards) an ascii key of all 0s, of length
       bitsPerShortKey bits. */
    i=bitsPerShortKey/BITS_PER_HEX_DIGIT;
    asciiKey[i] = 0; /* terminating null */ 
    for (i--; i >=0; i--) {
      asciiKey[i] = '0';
    }

    result = cipherInit(&cipher, MODE_ECB, 0);
    if (result != TRUE) goto error;

    for(i=0; i<OUTER_LOOP_MAX; i++) {
      result = makeKey(&key, DIR_DECRYPT, bitsPerShortKey, asciiKey);
      if (result != TRUE) goto error;

      /* NIST SPEC: Record i, KEY_i, CT_0 */
      printf("I=%d\n", i);
      render("KEY=", key.userKey, bitsPerShortKey/BITS_PER_WORD);
      render("CT=", cipherText, WORDS_PER_BLOCK);
      
      for (j=0; j<INNER_LOOP_MAX; j++) {
        /* NIST SPEC: IB_j=CT_j */
        /* Implicit (no IB var used) */

        /* encrypt */
        result = blockDecrypt(&cipher, &key, (BYTE*) cipherText, 
                              BITS_PER_BLOCK, (BYTE*) plainText);
        if (result < 0) {
          goto error;
        } else if (result != BITS_PER_BLOCK) {
          result = BAD_NUMBER_OF_BITS_PROCESSED;
          goto error;
        }

        /* NIST SPEC: CT_j+1 = PT_j */
        memcpy(cipherText, plainText, BYTES_PER_BLOCK);

        if (j == INNER_LOOP_MAX-2) {
          memcpy(PT_9998, plainText, BYTES_PER_BLOCK);
        }
      }
      
      /* NIST SPEC: Record PT_j */
      render("PT=", cipherText, WORDS_PER_BLOCK);
      printf("\n");

      /* NIST SPEC: KEY_i+1 = KEY_i xor last n bits of PT, where n=key size */
      /* First, juxtapose PT_9999 and PT_9998 into binaryKey; */
      memcpy(binaryKey, PT_9998, BYTES_PER_BLOCK);
      memcpy(&binaryKey[WORDS_PER_BLOCK], plainText, BYTES_PER_BLOCK);
      memmove(binaryKey, 
             &binaryKey[(BITS_PER_KEY-bitsPerShortKey)/BITS_PER_WORD], 
             bitsPerShortKey/BITS_PER_BYTE);
      /* Then, xor this stuff with the previously used key. */
      for (j=0; j<bitsPerShortKey/BITS_PER_WORD; j++) {
        binaryKey[j] ^= key.userKey[j];
      }
      
      /* NB: the NIST API does not provide callers with a way to specify a
         new key in binary format, so we have to go through the rigmarole
         of computing the new key in binary and converting it to ascii so
         that we can feed it to makeKey which will internally reconvert it
         back to binary--yechh. Note that just poking a new binary key in
         key.userKey won't work, as we need to invoke the routine that
         makes the subkeys. */
      wordsToString(binaryKey,
                    bitsPerShortKey/BITS_PER_WORD, asciiKey);
      result = makeKey(&key, DIR_DECRYPT, bitsPerShortKey, asciiKey);
      if (result != TRUE) goto error;

      /* NIST SPEC: CT_0 = PT_9999 */
      memcpy(cipherText, plainText, BYTES_PER_BLOCK);
    }
      
    printf("==========\n\n");
  }
  exit(0);

error:
  printf("Error %d (sorry, see aes.h to see what this means)\n", result);
  exit(result);
}
Beispiel #16
0
int __stdcall decrypt_elec_card_pwd(int cut_id,const char seedkey[32],const char mpwd[64],char pwd[8])
{
	char temp[17],temp1[17],buf[17];
	char encrypt_seed[65];
	unsigned char radom_seed[4];
	keyInstance key_inst;
	cipherInstance cipher_inst;
	int i,len;
	static const int max_pwd_len = 8;

	memset(&key_inst,0,sizeof key_inst);
	memset(&cipher_inst,0,sizeof cipher_inst);


	// 读取随机种子
	memcpy(temp,mpwd,8);
	memset(temp1,0,sizeof temp1);
	for(i = 0;i < 8;i+=2)
	{
		memcpy(temp1,temp+i,2);
		radom_seed[i/2] = (unsigned char)strtoul(temp1,NULL,16);
	}

	// 计算种子密钥
	memset(encrypt_seed,0,sizeof encrypt_seed);
	for(i = 0;i < 32;++i)
		encrypt_seed[i] = seedkey[i] ^ radom_seed[i%4];
	CalcMD5((unsigned char*)encrypt_seed,32,(unsigned char*)temp);
	memset(encrypt_seed,0,sizeof encrypt_seed);
	for(i = 0; i < 16 ;++i)
		sprintf(encrypt_seed+i*2,"%02X",(unsigned char)temp[i]);


	// 解密
	if(makeKey(&key_inst,DIR_DECRYPT,128,(char*)encrypt_seed)==FALSE)
	{
		return -1;
	}
	if(cipherInit(&cipher_inst,MODE_CBC,NULL)==FALSE)
	{
		return -1;
	}

	memset(temp1,0,sizeof temp1);
	memset(temp,0,sizeof temp);
	for(i = 0;i < 32; i+=2)
	{
		memcpy(temp1,mpwd+12+i,2);
		temp[i/2] = (unsigned char)strtoul(temp1,NULL,16);
	}
	memset(temp1,0,sizeof temp1);
	len = blockDecrypt(&cipher_inst,&key_inst,(BYTE*)temp,16*8,(BYTE*)temp1);

	for(i=0;i < max_pwd_len;++i)
		buf[i] = temp1[i] ^ radom_seed[i%4];
	

	// 计算密码
	sprintf(temp,"%08X",cut_id);
	for(i = 0;i < max_pwd_len;++i)
		temp1[i] = temp1[i] ^ temp[i];
	// CRC 校验
	uint16 crc = GenerateCRC16((unsigned char*)temp1,max_pwd_len);
	memset(temp,0,sizeof temp);
	sprintf(temp,"%04X",crc);
	if(strncmp(temp,mpwd+8,4))
	{
		return -2;
	}
	memcpy(pwd,buf,max_pwd_len);
	//memcpy(pwd,temp1,max_pwd_len);
	
	return 0;
}
Beispiel #17
0
int __stdcall encrypt_elec_card_pwd(int cut_id,const char seedkey[32],const char pwd[8],char mpwd[64])
{
	static const int max_pwd_len = 8;
	keyInstance key_inst;
	cipherInstance cipher_inst;
	unsigned char buf[16] = "";
	char temp[16] = "";
	char temp2[16] = "";
	char pwd_str[max_pwd_len*2+1] = "";
	unsigned char decrypt_buf[16] = "";
	char encrypt_seedkey[64] = "";
	unsigned char decrypt_str[64] = "";
	time_t radom_seed = time(NULL);
	int len,i,j,pwd_len;
	memset(&key_inst,0,sizeof key_inst);
	memset(&cipher_inst,0,sizeof cipher_inst);
	
	for(i = 0;i < max_pwd_len;++i)
	{
		switch(pwd[i])
		{
		case ' ':
		case '\t':
		case '\r':
		case '\n':
		case '\'':
		case '"':
		case '%':
		case '_':
			return -2;
		default:
			break;
		}
	}
	pwd_len = strlen(pwd);
	if(pwd_len > max_pwd_len)
		return -3;
	// 取4位随机种子
	srand((unsigned int)radom_seed);
	for(i = 0;i < 4;++i)
		buf[i] = (unsigned char)(rand() % 0xFF);

	// 密码不足8位右补空格
	memcpy(pwd_str,pwd,pwd_len);
	for(i=pwd_len;i < max_pwd_len;++i)
		pwd_str[pwd_len] = ' ';
	for(i=0;i < max_pwd_len;++i)
		pwd_str[i] ^= buf[i%4];

	// 加密的密钥
	for(i = 0;i < max_pwd_len;++i)
		pwd_str[max_pwd_len+i] = pwd_str[i] | (!temp[i]);
	memcpy(pwd_str+max_pwd_len,pwd_str,max_pwd_len);

	
	// 计算种子密钥
	memset(encrypt_seedkey,0,sizeof encrypt_seedkey);
	for(i = 0; i < 32 ;++i)
		encrypt_seedkey[i] = seedkey[i] ^ buf[i%4];
	CalcMD5((unsigned char*)encrypt_seedkey,32,(unsigned char*)temp);
	memset(encrypt_seedkey,0,sizeof encrypt_seedkey);
	for(i = 0,j = 0;i < 16; ++i)
		j += sprintf(encrypt_seedkey+j,"%02X",(unsigned char)temp[i]);


	// 计算CRC
	sprintf(temp,"%08X",cut_id);
	memset(temp2,0,sizeof temp2);
	for(i = 0;i < max_pwd_len;++i)
		temp2[i] = pwd_str[i] ^ temp[i];
	uint16 crc = GenerateCRC16((unsigned char *)temp2,max_pwd_len);
	sprintf(temp,"%04X",crc);
	memcpy(buf+4,temp,4);
	
	

	// 进行加密
	if(makeKey(&key_inst,DIR_ENCRYPT,128,encrypt_seedkey)==FALSE)
	{
		return -1;
	}
	if(cipherInit(&cipher_inst,MODE_CBC,NULL)==FALSE)
	{
		return -1;
	}
	len = blockEncrypt(&cipher_inst,&key_inst,(unsigned char*)pwd_str,16*8,decrypt_str);
	if(len == 16*8)
	{
		// 8 个字符种子
		for(i = 0;i < 4; ++i)
			sprintf(mpwd+i*2,"%02X",(unsigned char)buf[i]);
		// 4 个字符CRC
		memcpy(mpwd+8,temp,4);
		// 8 个字符密码
		for(i = 0;i < 16;++i)
			sprintf(mpwd+12+i*2,"%02X",decrypt_str[i]);
		//mpwd[28] = '\0';
		return 0;
	}
	return -1;
}
serverState keyExchange(){
	
	encType = PLAIN;
	
	fprintf(stderr , " **** Key Exhange phase **** \n\n");
	
	char cChiper[1];
	
	fprintf(stderr , "\n< Client cipher spec , client key exchange >\n");
	receive_and_decrypt(cChiper);
	fprintf(stderr , " %c \n" , cChiper[0]);
	
	if(isInCipherSpec(ServerCipherSpecFile , cChiper) == -1)	//if i have the cipher
	{
		fprintf(stderr , "\n< No cipher %c >\n" , cChiper[0]);
		return ERROR;
	}
	
	fprintf(stderr , "\n< Client cipher accepted , key generation >\n");	
	switch(cChiper[0]){
		
		case 'A': cipherSpec.symmetric_cipher = Cipher_Bunny24; 
					 cipherSpec.public_cipher = RSA64;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		case 'B': cipherSpec.symmetric_cipher = Cipher_Bunny24; 
					 cipherSpec.public_cipher = RSA512;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		case 'C': cipherSpec.symmetric_cipher = Cipher_ALL5; 
					 cipherSpec.public_cipher = RSA64;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		case 'D': cipherSpec.symmetric_cipher = Cipher_ALL5; 
					 cipherSpec.public_cipher = RSA512;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		case 'E': cipherSpec.symmetric_cipher = Cipher_MAJ5; 
					 cipherSpec.public_cipher = RSA64;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		case 'F': cipherSpec.symmetric_cipher = Cipher_MAJ5; 
					 cipherSpec.public_cipher = RSA512;
					 cipherSpec.hash_function = hash_spongeBunny;
					 break;
					 
		default : break;
	}
	
	bit buffer24[24] , buffer64[64];
	byte key24[3] , key64[8];
	
	memset(key24 , 0 , sizeof(byte) * 3);
	memset(key64 , 0 , sizeof(byte) * 8);
	
	int i;
	BIGNUM *tm;
	tm = BN_new();
	
	encType = cipherSpec.public_cipher;

	if(cipherSpec.symmetric_cipher == Cipher_Bunny24)
	{
		FPRNG(buffer24 , 24);
		for(i = 0; i < 24; i++)
			key24[i/8] |= (buffer24[i] << (i % 8));		//to byte
			
		tm = BN_bin2bn((const unsigned char *) key24, 3 , NULL);	
		printf("PLAIN : %s\n", BN_bn2hex(tm));	
		encrypt_and_send(key24 , 3);
		cipherInit(&cipherStruct , buffer24 , 24 , init_vector , 24, Cipher_Bunny24);
	}
	else
	{
		FPRNG(buffer64 , 64);
		for(i = 0; i < 64; i++)
			key64[i/8] |= (buffer64[i] << (i % 8));		//to byte		
			
		tm = BN_bin2bn((const unsigned char *) key64, 8 , NULL);	
		printf("PLAIN  : %s\n", BN_bn2hex(tm));	
		encrypt_and_send(key64 , 8);	
		cipherInit(&cipherStruct , buffer64 , 64 , init_vector , 24, cipherSpec.symmetric_cipher);
	}
	
	BN_free(tm);

	fprintf(stderr , "\n **** Key Exhange completed **** \n\n");
	
	return COMMUNICATION;
	
}
Beispiel #19
0
static void rijndaelIVKAT (FILE *fp, int keyLength, int blockLength)
{
	int i, ROUNDS;
	BYTE block[4*MAXBC], block2[4*MAXBC];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;
	char format[10];
#ifdef TRACE_KAT_MCT
	printf ("Executing Intermediate value KAT (key %d): ", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */

	switch (keyLength >= blockLength ? keyLength : blockLength) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return; /* this cannot happen */
	}
	
	fprintf (fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n",
		keyLength);
	fflush (fp);
	memset (keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf (&keyMaterial[2*i], "%02X", i);
	}
	keyInst.blockLen = blockLength;
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	fprintf (fp, "KEY=%s\n", keyMaterial);
	fprintf (fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	for (i = 0; i < blockLength/8; i++) {
		block[i] = i;
	}
	blockPrint (fp, block, blockLength, "PT");
	cipherInst.blockLen = blockLength;
	cipherInit (&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < ROUNDS; i++) {
		cipherUpdateRounds (&cipherInst, &keyInst, block, blockLength/8, block2, i);
		sprintf(format,"CT%d",i);
		blockPrint (fp, block2, blockLength, format);
	}
	cipherUpdateRounds (&cipherInst, &keyInst, block, blockLength, block2, ROUNDS);
	blockPrint (fp, block2, blockLength, "CT");
	
	keyInst.blockLen = blockLength;
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	fprintf (fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	blockPrint (fp, block2, blockLength, "CT");
	cipherInst.blockLen = blockLength;
	cipherInit (&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < ROUNDS; i++) {
		cipherUpdateRounds (&cipherInst, &keyInst, block2, blockLength,block, ROUNDS-i);
		sprintf(format,"PT%d",i);
		blockPrint (fp, block, blockLength, format);
	}
	cipherUpdateRounds (&cipherInst, &keyInst, block2, blockLength, block, 0);
	blockPrint (fp, block, blockLength, "PT");
	
#ifdef TRACE_KAT_MCT
	printf (" done.\n");
#endif 
}
Beispiel #20
0
static void rijndaelECB_MCT (FILE *fp, const char *initKey, int keyLength,
	const char *initBlock, int blockLength, BYTE direction)
{
	int i, j;
	BYTE inBlock[4*MAXBC], outBlock[4*MAXBC], binKey[4*MAXKC];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	int width = 0;
	clock_t elapsed = -clock();
	printf ("Executing ECB MCT (%s, key %d): ",
		direction == DIR_ENCRYPT ? "ENCRYPT" : "DECRYPT", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf (fp,
		"\n"
		"=========================\n"
		"\n"
		"KEYSIZE=%d\n", keyLength);
	fflush (fp);
	HexToBin (outBlock, initBlock, blockLength);
	HexToBin (binKey, initKey, keyLength);
	for (i = 0; i < 400; i++) {
#ifdef TRACE_KAT_MCT                 
        while (width-- > 0) putchar ('\b'); width = printf ("%d", i); fflush (stdout);    
#endif /* ?TRACE_KAT_MCT */
		fprintf (fp, "\nI=%d\n", i);
		/* prepare key: */
		for (j = 0; j < keyLength/8; j++) {
			sprintf (&keyMaterial[2*j], "%02X", binKey[j]);
		}
		keyMaterial[keyLength/4] = 0;
		fprintf (fp, "KEY=%s\n", keyMaterial);
		keyInst.blockLen = blockLength;
		makeKey(&keyInst, direction, keyLength, keyMaterial);
		/* do encryption/decryption: */
		blockPrint (fp, outBlock, blockLength, direction == DIR_ENCRYPT ? "PT" : "CT");
		cipherInst.blockLen = blockLength;
		cipherInit (&cipherInst, MODE_ECB, NULL);
		if (direction == DIR_ENCRYPT) {
			for (j = 0; j < 10000; j++) {
				memcpy (inBlock, outBlock, blockLength/8);
				blockEncrypt(&cipherInst, &keyInst, inBlock, blockLength, outBlock);
			}
		} else {
			for (j = 0; j < 10000; j++) {
				memcpy (inBlock, outBlock, blockLength/8);
				blockDecrypt(&cipherInst, &keyInst, inBlock, blockLength, outBlock);
			}
		}
		blockPrint (fp, outBlock, blockLength, direction == DIR_ENCRYPT ? "CT" : "PT");
		/* prepare new key: */
		switch (keyLength) {
		case 128:
			for (j = 0; j < 128/8; j++) {
				binKey[j] ^= outBlock[j];
			}
			break;
		case 192:
			for (j = 0; j < 64/8; j++) {
				binKey[j] ^= inBlock[j + 64/8];
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 64/8] ^= outBlock[j];
			}
			break;
		case 256:
			for (j = 0; j < 128/8; j++) {
				binKey[j] ^= inBlock[j];
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 128/8] ^= outBlock[j];
			}
			break;
		}
	}
#ifdef TRACE_KAT_MCT
	elapsed += clock();
	printf (" done (%.1f s).\n", (float)elapsed/CLOCKS_PER_SEC);
#endif /* ?TRACE_KAT_MCT */
} /* rijndaelECB_MCT */
Beispiel #21
0
static void rijndaelCBC_MCT (FILE *fp, const char *initKey, int keyLength,
	const char *initIV, const char *initBlock, int blockLength, BYTE direction)
{
	int i, j, r, t;
	BYTE inBlock[256/8], outBlock[256/8], binKey[256/8], cv[256/8];
	BYTE keyMaterial[320];
	BYTE iv[64+1];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	int width = 0;
	clock_t elapsed = -clock();
	printf ("Executing CBC MCT (%s, key %d): ",
		direction == DIR_ENCRYPT ? "ENCRYPT" : "DECRYPT", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf (fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n", keyLength);
	fflush (fp);
	HexToBin (inBlock, initBlock, blockLength); /* this is either PT0 or CT0 */
	HexToBin (cv, initIV, blockLength);
	HexToBin (binKey, initKey, keyLength);
	for (i = 0; i < 400; i++) {
#ifdef TRACE_KAT_MCT                 
        while (width-- > 0) putchar ('\b'); width = printf ("%d", i); fflush (stdout);    
#endif /* ?TRACE_KAT_MCT */
		fprintf (fp, "\nI=%d\n", i);
		/* prepare key: */
		for (j = 0; j < keyLength/8; j++) {
			sprintf (&keyMaterial[2*j], "%02X", binKey[j]);
		}
		keyMaterial[keyLength/4] = 0;
		fprintf (fp, "KEY=%s\n", keyMaterial);
		keyInst.blockLen = blockLength;
		r = makeKey(&keyInst, direction, keyLength, keyMaterial);
		if (TRUE != r) {
			fprintf(stderr,"makeKey error %d\n",r);
			exit(-1);
		}
		/* do encryption/decryption: */
		blockPrint (fp, cv, blockLength, "IV");
		blockPrint (fp, inBlock, blockLength, direction == DIR_ENCRYPT ? "PT" : "CT");
		if (direction == DIR_ENCRYPT) {
			for (j = 0; j < 10000; j++) {
				for(t = 0; t < blockLength/8; t++) {
					sprintf(iv+2*t,"%02x",cv[t]);					
				}
				cipherInst.blockLen = blockLength;
				r = cipherInit (&cipherInst, MODE_CBC, iv);
				if (TRUE != r) {
					fprintf(stderr,"cipherInit error %d\n",r);
					exit(-1);
				}
				r = blockEncrypt(&cipherInst, &keyInst, inBlock, blockLength, outBlock);
				if (blockLength != r) {
					fprintf(stderr,"blockEncrypt error %d\n",r);
					exit(-1);
				}
				memcpy (inBlock, cv, blockLength/8);
				memcpy (cv, outBlock, blockLength/8);
			}
		} else {
			for (j = 0; j < 10000; j++) {
				for(t = 0; t < blockLength/8; t++) {
					sprintf(iv+2*t,"%02x",cv[t]);					
				}
				cipherInst.blockLen = blockLength;
				cipherInit (&cipherInst, MODE_CBC, iv);
				blockDecrypt(&cipherInst, &keyInst, inBlock, blockLength, outBlock);
				memcpy (cv, inBlock, blockLength/8);
				memcpy (inBlock, outBlock, blockLength/8);
			}
		}
		blockPrint (fp, outBlock, blockLength, direction == DIR_ENCRYPT ? "CT" : "PT");
		/* prepare new key: */
		switch (keyLength) {
		case 128:
			for (j = 0; j < 128/8; j++) {
				binKey[j] ^= outBlock[j];
			}
			break;
		case 192:
			for (j = 0; j < 64/8; j++) {
				if (direction == DIR_ENCRYPT)
					binKey[j] ^= inBlock[j + 64/8];
				else
					binKey[j] ^= cv[j + 64/8];
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 64/8] ^= outBlock[j];
			}
			break;
		case 256:
			for (j = 0; j < 128/8; j++) {
				if (direction == DIR_ENCRYPT)
					binKey[j] ^= inBlock[j];
				else
					binKey[j] ^= cv[j];
			}
			for (j = 0; j < 128/8; j++) {
				binKey[j + 128/8] ^= outBlock[j];
			}
			break;
		}
	}
#ifdef TRACE_KAT_MCT
	elapsed += clock();
	printf (" done (%.1f s).\n", (float)elapsed/CLOCKS_PER_SEC);
#endif /* ?TRACE_KAT_MCT */
} /* rijndaelCBC_MCT */