Exemple #1
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 */
Exemple #2
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;
}
Exemple #3
0
NTSTATUS
DecryptBlock(
	PNCIPHER_INSTANCE	Cipher,
	PNCIPHER_KEY		Key,
	int					BufferLength,
	PBYTE				InBuffer,
	PBYTE				OutBuffer
){
	int ret;

	if(!InBuffer || !OutBuffer) {
		KDPrintM(DBG_OTHER_ERROR, ("Buffer parameter is NULL!\n"));
		return STATUS_INVALID_PARAMETER;
	}

	switch(Cipher->CipherType) {
	case	NDAS_CIPHER_SIMPLE: {
		PCIPHER_HASH_KEY	key = (PCIPHER_HASH_KEY)Key->CipherSpecificKey;


		if(InBuffer != OutBuffer) {
			KDPrintM(DBG_OTHER_ERROR, ("Does not support encryption-copy!\n"));
			return STATUS_NOT_IMPLEMENTED;
		} else {
			Decrypt32SP(
					InBuffer,
					BufferLength,
					key->CntDcr_IR
				);
		}
		break;
	}
	case	NDAS_CIPHER_AES: {
		keyInstance *aesKey = (keyInstance *)Key->CipherSpecificKey;

		aesKey->direction = DIR_DECRYPT;
		ret = blockDecrypt(
						(cipherInstance *)Cipher->InstanceSpecific,
						aesKey,
						InBuffer,				// Input buffer
						BufferLength<<3,		// bits
						OutBuffer				// output buffer
					);
		if(ret < 0) {
			KDPrintM(DBG_OTHER_ERROR, ("blockDecrypt() failed. Ret=%d.\n", ret));
			return STATUS_UNSUCCESSFUL;
		}
		break;
	}
	default:
		return STATUS_INVALID_PARAMETER;
	}
	return STATUS_SUCCESS;
}
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;
}
/**
 * Decrypts a string(str struct).
 * 
 * @param encoded - the string that needs to be decrypted
 * @returns - the decoded string.Memory allocation takes place in this
 * 				function.
 */
str thig_decrypt(str encoded)
{
	str src;
	str my_text={0,0},dec_text={0,0};
	cipherInstance ci2 = ci;

#ifdef USE_BASE64
	src = base64_decode(encoded);
#else
	src = base16_decode(encoded);
#endif
	if (!src.len) return dec_text;

	my_text = src;
	dec_text.s = pkg_malloc(my_text.len);
	if (!dec_text.s){
		LOG(L_ERR,"ERR:"M_NAME":decrypt: error allocating %d bytes\n",my_text.len);
		goto error;		
	}
	dec_text.len = my_text.len;
	
	printstr("String bef :",my_text);

	if (blockDecrypt(&ci2,&ki,(unsigned char*)my_text.s,my_text.len*8,(unsigned char*)dec_text.s) != my_text.len*8){
		LOG(L_ERR,"DBG:"M_NAME":decrypt: Error in encryption phase\n");
		goto error;
	}
	while(dec_text.s[dec_text.len-1]==0 && dec_text.len>0)
		dec_text.len--;
	printstr("String aft :",dec_text);
	if (src.s) pkg_free(src.s);
	return dec_text;
error:
	if (src.s) pkg_free(src.s);
	if (dec_text.s) pkg_free(dec_text.s);
	dec_text.s = 0;dec_text.len=0;
	return dec_text;	
}
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 */
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 */
}
Exemple #8
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;
}
Exemple #9
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 */
Exemple #10
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 */
Exemple #11
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);
}
Exemple #12
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);
}