Example #1
0
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 */
}
void OSIEncryption::ReinitTFTable()
{
	unsigned char tmpBuff[256];
	blockEncrypt( &m_Cipher, &m_Key, m_TFTable, 256*8, tmpBuff );
	memcpy( m_TFTable, tmpBuff, 256 );
	m_TFPos = 0;
}
Example #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 */
Example #4
0
NTSTATUS
EncryptBlock(
	PNCIPHER_INSTANCE	Cipher,
	PNCIPHER_KEY		Key,
	LONG				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) {
			Encrypt32SPAndCopy(
					OutBuffer,
					InBuffer,
					BufferLength,
					key->CntEcr_IR
				);
		} else {
			Encrypt32SP(
					InBuffer,
					BufferLength,
					key->CntEcr_IR
				);
		}
		break;
	}
	case	NDAS_CIPHER_AES: {
		keyInstance *aesKey = (keyInstance *)Key->CipherSpecificKey;

		aesKey->direction = DIR_ENCRYPT;
		ret = blockEncrypt(
						(cipherInstance *)Cipher->InstanceSpecific,
						aesKey,
						InBuffer,				// Input buffer
						BufferLength<<3,		// bits
						OutBuffer				// output buffer
					);
		if(ret < 0) {
			KDPrintM(DBG_OTHER_ERROR, ("blockEncrypt() failed. Ret=%d.\n", ret));
			return STATUS_UNSUCCESSFUL;
		}
		break;
	}
	default:
		return STATUS_INVALID_PARAMETER;
	}
	return STATUS_SUCCESS;
}
Example #5
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;
}
Example #6
0
/**
 * Encrypts a string (str struct).
 *
 * @param src - the string that needs to be encrypted.Must NOT contain \0
 * @returns - the encrypted string, allocated in this function.
 */
str thig_encrypt(str src)
{
	int padding;
	str my_text={0,0},enc_text={0,0};
	cipherInstance ci2 = ci;
	str encoded={0,0};
	
	padding = (src.len%byteCnt)==0?0:byteCnt-(src.len%byteCnt);
	LOG(L_ERR,"DBG:"M_NAME":encrypt:String has length %d so needs padding %d\n",src.len,padding);

	my_text.len = src.len+padding;
	my_text.s = pkg_malloc(my_text.len);
	if (!my_text.s){
		LOG(L_ERR,"ERR:"M_NAME":encrypt: error allocating %d bytes\n",my_text.len);
		goto error;
	}	
	memcpy(my_text.s,src.s,src.len);
	memset(my_text.s+src.len,0,my_text.len-src.len);
	
	enc_text.s = pkg_malloc(my_text.len);
	if (!enc_text.s){
		LOG(L_ERR,"ERR:"M_NAME":encrypt: error allocating %d bytes\n",my_text.len);
		goto error;		
	}
	enc_text.len = my_text.len;

	printstr("String bef :",my_text);
	if (blockEncrypt(&ci2,&ki,(unsigned char*)my_text.s,my_text.len*8,(unsigned char*)enc_text.s) != my_text.len*8){
		LOG(L_ERR,"DBG:"M_NAME":encrypt: Error in encryption phase\n");
		goto error;
	}
	printstr("String aft :",enc_text);

#ifdef USE_BASE64
	encoded = base64_encode(enc_text);
#else
	encoded = base16_encode(enc_text);
#endif
	
	if (my_text.s) pkg_free(my_text.s);
	if (enc_text.s) pkg_free(enc_text.s);
	return encoded;	
error:
	if (my_text.s) pkg_free(my_text.s);
	if (enc_text.s) pkg_free(enc_text.s);
	enc_text.s = 0;enc_text.len=0;
	return enc_text;		
}
Example #7
0
void
AES_Decrypt(AES_Struct *aes, const unsigned char *data, unsigned int len,
	    unsigned char *result) {
	unsigned int i, ch;

	for (i = 0; i < len; i++) {
		if (aes->cfb128_idx < 0 || aes->cfb128_idx > 15) {
			blockEncrypt(&aes->cipher, &aes->encrypt_key,
				     aes->cfb_blk, 128, aes->cfb_crypt);
			aes->cfb128_idx = 0;
		}

		ch = data[i];
		result[i] = ch ^ aes->cfb_crypt[aes->cfb128_idx]; 
		/* do output feedback: put crypted byte into next block to be crypted */
		aes->cfb_blk[aes->cfb128_idx] = ch;
		aes->cfb128_idx++;
	}
}
Example #8
0
/*
** Generate and return a 32-bit uniform random string (saved in the lower
** half of the OWPnum64.
*/
OWPnum64
OWPunif_rand64(OWPrand_context64 *next)
{
	int j;
	u_int8_t res = next->counter[15] & (u_int8_t)3;

	if (!res) {
		if (blockEncrypt(&next->cipher, &next->key, next->counter, 128,
				 next->out) < 0) {
			fprintf(stderr, "DEBUG: encryption failed\n");
			exit(1);
		}
	}

	/* Increment next.counter as an 128-bit single quantity in network
	   byte order for AES counter mode. */
	for (j = 15; j >= 0; j--)
		if (++next->counter[j])
			break;
	return OWPraw2num64((next->out) + 4*res);
}
void encryptBuffer(char* buffer,int bufferSize){
  int i;
  char *currentBlock;
  if(bufferSize % 16 != 0) {
    /*Panic*/
    return;
  }
  /*Setting the key direction to Enpcrypt*/
  keyInst.direction = DIR_ENCRYPT;
  makeKey(&keyInst, DIR_ENCRYPT, 128,keyMaterial);
  cipherInit(&cipherInst, MODE_ECB, NULL);
  /*Encrypt the buffer*/
  for(i = 0; i< bufferSize; i+=16) {
    /*Copying out a block*/
    memcpy(currentBlock,buffer+i,16);
    /*Encrypting block*/
    blockEncrypt(&cipherInst, &keyInst, currentBlock, 16 * 8, currentBlock);
    /*Copying in the encrypted block*/
    memcpy(buffer+i,currentBlock,16);
  }
  return;
}
Example #10
0
void
AES_Encrypt(AES_Struct *aes, const unsigned char *data, unsigned int len,
	    unsigned char *result) {
	unsigned int i, ch;

	for (i = 0; i < len; i++) {
		if ((aes->cfb128_idx < 0) || (aes->cfb128_idx > 15)) {
			blockEncrypt(&aes->cipher, &aes->encrypt_key,
				     aes->cfb_blk, 128, aes->cfb_crypt);

			aes->cfb128_idx = 0;
		}

		/* XOR the data with a byte from our encrypted buffer. */ 
		ch = data[i] ^ aes->cfb_crypt[aes->cfb128_idx];

		/* do output feedback: put crypted byte into next block to be crypted */
		aes->cfb_blk[aes->cfb128_idx] = ch;
		aes->cfb128_idx++;

		result[i] = (unsigned char) ch;
	}
}
Example #11
0
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 */
Example #12
0
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 */
}
Example #13
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;
}
Example #14
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 */
Example #15
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 */
Example #16
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);
}