void
AES_CPU_Impl_O0::EncryptBlock(UINT8 *dst, const UINT8 *src)
{
    UINT8 m_state[m_Nb][4];
    for( UINT32 i = 0; i < 4; i++ )
        for( UINT32 j = 0; j < 4; j++ )
            m_state[j][i] = src[i*4 + j];

    // Add the First round key to the state before starting the rounds.
    AddRoundKey(m_state, 0); 

    // There will be m_Nr rounds.
    // The first m_Nr-1 rounds are identical.
    // These m_Nr-1 rounds are executed in the loop below.
    for( UINT32 round = 1; round < m_Nr; round++ )
    {
        SubBytes(m_state);
        ShiftRows(m_state);
        MixColumns(m_state);
        AddRoundKey(m_state, round);
    }

    // The last round is given below.
    // The MixColumns function is not here in the last round.
    SubBytes(m_state);
    ShiftRows(m_state);
    AddRoundKey(m_state, m_Nr);

    for( UINT32 i = 0; i < 4; i++ )
        for( UINT32 j = 0; j < 4; j++ )
            dst[i*4 + j] = m_state[j][i];
}
Exemple #2
0
///////////////////////////////////////////////////////////////////////////////
//	函数名:	AES_Init
//	描述:		初始化,在此执行扩展密钥操作。
//	输入参数:	pKey -- 原始密钥,其长度必须为 AES_KEY_LENGTH/8 字节。
//	输出参数:	无。
//	返回值:	无。
///////////////////////////////////////////////////////////////////////////////
void AES_Init(const void *pKey)
{
	// 扩展密钥
	unsigned char i;
	unsigned char *pRoundKey;
	unsigned char Rcon[4] = {0x01, 0x00, 0x00, 0x00};

	memcpy(g_roundKeyTable, pKey, 4*Nk);

	pRoundKey = &g_roundKeyTable[4*Nk];

	for (i = Nk; i < Nb*(Nr+1); pRoundKey += 4, i++)
	{
		memcpy(pRoundKey, pRoundKey - 4, 4);

		if (i % Nk == 0)
		{
			RotationWord(pRoundKey);
			SubBytes(pRoundKey, 4, 0);
			XorBytes(pRoundKey, Rcon, 4);

			Rcon[0] = GfMultBy02(Rcon[0]);
		}
		else if (Nk > 6 && i % Nk == Nb)
		{
			SubBytes(pRoundKey, 4, 0);
		}

		XorBytes(pRoundKey, pRoundKey - 4*Nk, 4);
	}
}
Exemple #3
0
//==============================================================================
void Decrypt( uint8_t *keyblok, uint8_t *buff, uint8_t *result) //Функция расшифровывания
{
  uint8_t i,j; //Счетчики
 
  KeyExpansion( keyblok, DECRYPT);  //Вычисление раундовых ключей
 
  for(i=j=0; i<Nb; i++, j+=4) s[i]= pack((uint8_t *)&buff[j]); //Заполнение промежуточного массива
  i=0;
 
  AddRoundKey(s , rkey , 0); ////Операция исключающее или с раундовым ключем
  
  for(i=1; i< Nr; i++)
  {
    ShiftRows((uint8_t*)s, DECRYPT);
    SubBytes((uint8_t*)s, DECRYPT);
    AddRoundKey(s, rkey, i);
    MixColums(s, Nb, DECRYPT);
  }
  
  ShiftRows((uint8_t*)s, DECRYPT);
  SubBytes((uint8_t*)s, DECRYPT);
  AddRoundKey(s, rkey, Nr);
  
  for(i=j=0;i<Nb;i++,j+=4) unpack(s[i], (uint8_t*)& result[j]);
 
}
void AES_enc(BYTE* input, BYTE* output,BYTE *w,BYTE Nr)
{
	DWORD i;
	DWORD round;
	BYTE gState[4][4];
	AES_Memset(&gState[0][0],0,16);
	for( i=0;i<4*NB;i++)
	{
		gState[i%4][i/4]=input[i];
	}
	AddRoundKey(0,w,gState);
	
	for ( round = 1; round <= (Nr - 1); round++)
	{
        SubBytes(gState);
        ShiftRows(gState);
        MixColumns(gState);
        AddRoundKey(round,w,gState);
	}  // main round loop
	
	SubBytes(gState);
	ShiftRows(gState);
	AddRoundKey(Nr,w,gState);
	
	// output = state
	for (i = 0; i < (4 * NB); i++)
	{
        output[i] =  gState[i % 4][ i / 4];
	}

}
Exemple #5
0
void aes_cipher(ctx_aes* aes, uint8_t* input, uint8_t* output)  // encipher 16-bit input
{
	// state = input
	int i;
	int round;
	memset(&aes->State[0][0],0,16);
	for (i = 0; i < (4 * aes->Nb); i++)//
	{
        aes->State[i % 4][ i / 4] = input[i];
	}
	AddRoundKey(aes, 0);
	for (round = 1; round <= (aes->Nr - 1); round++)  // main round loop
	{
        SubBytes(aes); 
        ShiftRows(aes);  
        MixColumns(aes); 
        AddRoundKey(aes, round);
	}  // main round loop
	
	SubBytes(aes);
	ShiftRows(aes);
	AddRoundKey(aes, aes->Nr);
	
	// output = state
	for (i = 0; i < (4 * aes->Nb); i++)
	{
        output[i] =  aes->State[i % 4][ i / 4];
	}
	
}  // Cipher()
Exemple #6
0
Fichier : aes.c Projet : LinLL/ipc
void Cipher(unsigned char* input, unsigned char* output)  // encipher 16-bit input
{
	// state = input
	int i, round;
	memset(&State[0][0],0,16);
	
	for (i = 0; i < (4 * Nb); i++)//
	{
		State[i % 4][ i / 4] = input[i];
		//State[i / 4][ i % 4] = input[i];
	}
	//Dump();
	AddRoundKey(0);

	for (round = 1; round <= (Nr - 1); round++)  // main round loop
	{
		SubBytes(); 
		ShiftRows();  
		MixColumns(); 
		AddRoundKey(round);
	}  // main round loop

	SubBytes();
	ShiftRows();
	AddRoundKey(Nr);

	// output = state
	for (i = 0; i < (4 * Nb); i++)
	{
		output[i] =  State[i % 4][ i / 4];
	}

}  // Cipher()
/**
 * @brief Encrypts 16 bytes of data.
 *
 * Based on Advanced Encryption Standard specification.
 * 
 * @param dataToEncrypt Data to encrypt, must be at least 16 bytes in size.
 * @param result Destination to store encrypted data, must be at least 16 bytes in size.
 * @param numRounds Number of rounds.
 * @param roundKey Round key.
 */
void ThreadMessageItemEncrypt::Cipher(unsigned char * dataToEncrypt,unsigned char * result, unsigned char numRounds, unsigned char * roundKey)
{
	// Copy data into state for manipulation
	for(size_t r = 0;r<EncryptKey::WORD_SIZE;r++)
	{
		for(size_t c = 0;c<EncryptKey::WORD_SIZE;c++)
		{
			state[r][c] = dataToEncrypt[r+(c*EncryptKey::WORD_SIZE)];
		}
	}

	// Perform encryption operations
	XorRoundKey(0,roundKey);

	for(size_t r = 1; r<numRounds; r++)
	{
		SubBytes();
		ShiftRowsLeft();
		MixColumns();
		XorRoundKey(r,roundKey);
	}

	SubBytes();
	ShiftRowsLeft();
	XorRoundKey(numRounds,roundKey);
	
	// Copy state into data now that we have finished
	for(int r = 0;r<EncryptKey::WORD_SIZE;r++)
	{
		for(int c = 0;c<EncryptKey::WORD_SIZE;c++)
		{
			result[r+(c*EncryptKey::WORD_SIZE)] = state[r][c];
		}
	}
}
Exemple #8
0
void Cipher()
{
	int i, j, round=0;

	for(i=0; i<4; i++)
	{
		for(j=0; j<4; j++)
		{
			state[j][i] = in[i*4 + j];
		}
	}

	AddRoundKey(0); 

	for(round=1; round<Nr; round++)
	{
		SubBytes();
		ShiftRows();
		MixColumns();
		AddRoundKey(round);
	}
	
	SubBytes();
	ShiftRows();
	AddRoundKey(Nr);

	for(i=0; i<4; i++)
	{
		for(j=0; j<4; j++)
		{
			out[i*4+j]=state[j][i];
		}
	}
}
Exemple #9
0
// Cipher is the main function that encrypts the PlainText.
void Cipher(unsigned char out[16],
	    unsigned char in[16], unsigned char RoundKey[240], int Nr)
{
  unsigned char state[4][4];
  int i,j,round=0;
  //Copy the input PlainText to state array.
  for(i=0;i<4;i++)
    {
      for(j=0;j<4;j++)
        {
	  state[j][i] = in[i*4 + j];
        }
    }
  // Add the First round key to the state before starting the rounds.
  AddRoundKey(state, RoundKey, 0);
#ifdef DEBUG_PRINTOUT
  std::cerr << "  ka="; printState(state); std::cerr << std::endl;
#endif
  // There will be Nr rounds.
  // The first Nr-1 rounds are identical.
  // These Nr-1 rounds are executed in the loop below.
  for(round=1;round<Nr;round++)
    {
      SubBytes(state);
#ifdef DEBUG_PRINTOUT
      std::cerr << "  sb="; printState(state); std::cerr << std::endl;
#endif
      ShiftRows(state);
      MixColumns(state);
#ifdef DEBUG_PRINTOUT
      std::cerr << "  mc="; printState(state); std::cerr << std::endl;
#endif
      AddRoundKey(state, RoundKey, round);
#ifdef DEBUG_PRINTOUT
      std::cerr << "  ka="; printState(state); std::cerr << std::endl;
#endif
    }
  // The last round is given below.
  // The MixColumns function is not here in the last round.
  SubBytes(state);
  ShiftRows(state);
#ifdef DEBUG_PRINTOUT
  std::cerr << "  sr="; printState(state); std::cerr << std::endl;
#endif
  AddRoundKey(state, RoundKey, Nr);
#ifdef DEBUG_PRINTOUT
  std::cerr << "  ka="; printState(state); std::cerr << std::endl;
#endif
  // The encryption process is over.
  // Copy the state array to output array.
  for(i=0;i<4;i++)
    {
      for(j=0;j<4;j++)
        {
	  out[i*4+j]=state[j][i];
        }
    }
}
// Cipher is the main function that encrypts the PlainText.
void Cipher()
{
	int i,j,round=0;

	//Copy the input PlainText to state array.
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			state[j][i] = in[i*4 + j];
		}
	}

	// Add the First round key to the state before starting the rounds.
	AddRoundKey(0); 
	
	// There will be Nr rounds.
	// The first Nr-1 rounds are identical.
	// These Nr-1 rounds are executed in the loop below.
	for(round=1;round<Nr;round++)
	{
		SubBytes();
		ShiftRows();
		MixColumns();
		AddRoundKey(round);
		// for(i=0;i<4;i++)
		// {
		// 	for(j=0;j<4;j++)
		// 	{
		// 	//	out[i*4+j]=state[j][i];
		// 		printf("%02x",state[j][i]);
		// 	}

		// }
		printf("\n");

	}
	
	// The last round is given below.
	// The MixColumns function is not here in the last round.
	SubBytes();
	ShiftRows();
	AddRoundKey(Nr);

	// The encryption process is over.
	// Copy the state array to output array.
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			out[i*4+j]=state[j][i];
		}
	}
}
/* apply Q-permutation to x */
void Q(hashState *ctx, u8 x[ROWS][COLS1024]) {
  u8 i;
  Variant v = ctx->columns==8?Q512:Q1024;
#ifndef TURN_OFF_PRINTING
  printf(":: BEGIN Q\n");
  printf("Input:\n");
  PrintState(ctx, x);
#endif
  for (i = 0; i < ctx->rounds; i++) {
    AddRoundConstant(x, ctx->columns, i, v);
#ifndef TURN_OFF_PRINTING
    printf("t=%d (AddRoundConstant):\n", i);
    PrintState(ctx, x);
#endif
    SubBytes(x, ctx->columns);
#ifndef TURN_OFF_PRINTING
    printf("t=%d (SubBytes):\n", i);
    PrintState(ctx, x);
#endif
    ShiftBytes(x, ctx->columns, v);
#ifndef TURN_OFF_PRINTING
    printf("t=%d (ShiftBytes):\n", i);
    PrintState(ctx, x);
#endif
    MixBytes(x, ctx->columns);
#ifndef TURN_OFF_PRINTING
    printf("t=%d (MixBytes):\n", i);
    PrintState(ctx, x);
#endif
  }
#ifndef TURN_OFF_PRINTING
  printf(":: END Q\n\n");
#endif
}
unsigned char* AES::Cipher(unsigned char* input)
{
	unsigned char state[4][4];
	int i,r,c;

	for(r=0; r<4; r++)
	{
		for(c=0; c<4 ;c++)
		{
			state[r][c] = input[c*4+r];
		}
	}

	AddRoundKey(state,w[0]);

	for(i=1; i<=10; i++)
	{
		SubBytes(state);
		ShiftRows(state);
		if(i!=10)MixColumns(state);
		AddRoundKey(state,w[i]);
	}

	for(r=0; r<4; r++)
	{
		for(c=0; c<4 ;c++)
		{
			input[c*4+r] = state[r][c];
		}
	}

	return input;
}
Exemple #13
0
int main(){
  unsigned int temp[]={0x19a09ae9,0x3df4c6f8,0xe3e28d48,0xbe2b2a08};
  SubBytes(temp);
  int i=0;
  for(i=0;i<4;i++)
    printf("%08x\n",temp[i]);
  return 0;
}
Exemple #14
0
void SubWord(uint32_t in)
{
    uint8_t the_bytes[4];

    bytes(in, the_bytes);
    SubBytes(the_bytes);

    in = word(the_bytes[0], the_bytes[1], the_bytes[2], the_bytes[3]);
}
static void Cipher(uint8x16_t RoundKey_v[])
{
	uint8_t round = 0;

	AddRoundKey(RoundKey_v[0]); 

	for(round = 1; round < rounds; ++round)
	{
		SubBytes();
		ShiftRows();
		MixColumns();
		AddRoundKey(RoundKey_v[round]);
	}

	SubBytes();
	ShiftRows();
	AddRoundKey(RoundKey_v[rounds]);
}
Exemple #16
0
void RijndaelEncrypt( uint8_t state[AES_BLOCK_SIZE], uint8_t eKey[AES_MAX_KEY_SIZE],int32_t Nr )
{
    int32_t round = 0;

    AddRoundKey(state,eKey,round);

    for ( round = 1; round < Nr; ++round )
    {
        SubBytes(state);
        ShiftRows(state);
        MixColumns(state);
        AddRoundKey(state,eKey,round);
    }

    SubBytes(state);
    ShiftRows(state);
    AddRoundKey(state,eKey,Nr);
}
Exemple #17
0
// this is the function that takes a block of plaintext and the key schedule
// and encrypts it. the next level of abstraction would be to implement block
// modes using this function on each block
void EncryptBlock(uint8_t* block, uint8_t* key_schedule)
{
    // the state is always 128 bits for AES. we are going to represent that as
    // an array of 16 bytes. conceptually it can be useful to think of it as a
    // 4x4 matrix
    //
    // step 1 of the cipher is to initialize the state as the input block of
    // plaintext. we are just going to operate directly on the input block

    // step 2 is to do an initial round key addition. the first round key is
    // added by a simple bitwise xor operation
    AddRoundKey(block, key_schedule[0, (4*4) - 1]);

    // step 3 is Nr-1 rounds where Nr is the total number of rounds we will be
    // performing. Nr is 10, 12, and 14 for keysizes of 128, 192, and 256
    // respectively.
    for (uint8_t round = 0; round < (10 - 1); round++) {

        // the round function consists of four operations
        //
        // SubBytes subsitutes bytes in the state based on the standardized
        // substitution boxes or S-Boxes
        SubBytes(block);

        // ShiftRows cyclically shifts each of the last three rows of state
        // over by a different offset
        ShiftRows(block);

        // MixColumns does some math on the state, column by column
        MixColumns(block);

        // finally, we add the next round key to the state
        AddRoundKey(block, key_schedule[round * (4*4), (round + 1) * 4 - 1]);
    }

    // step 4 is the final round. the only difference is that we do not
    // perform the MixColumns operation on this one
    SubBytes(block);
    ShiftRows(block);
    AddRoundKey(block, key_schedule[10 * (4*4), (10 + 1) * (4*4) - 1]);

    // all of that fiddling with the state leaves us with the encrypted
    // block
}
Exemple #18
0
//       Subbytes
void GenSubBytesTab()
{
    SubBytesTab[0] = 0x63; //  
    InvSubBytesTab[0x63] = 0;
    for (int i = 1; i < 256; i++)
    {
        BYTE y = SubBytes((BYTE) i);
        SubBytesTab[i] = y;
        InvSubBytesTab[y] = i;
    }
}
Exemple #19
0
Fichier : aes.c Projet : DDTLK/AUTH
// encrypt is the main function that encrypts the PlainText.
void encrypt(uint8_t *out, uint8_t *in, uint8_t *expanded_key)
{
    int i,j,round=0;
    uint8_t state[4][4];
    int Nr = 128/32+6;// replace 128 by 192, 256 for larger keys

    //Copy the input PlainText to state array.
    for(i=0; i<4; i++)  {
        for(j=0; j<4; j++)  {
            state[j][i] = in[i*4 + j];
        }
    }

    // Add the First round key to the state before starting the rounds.
    AddRoundKey(0,state,expanded_key);

    // There will be Nr rounds.
    // The first Nr-1 rounds are identical.
    // These Nr-1 rounds are executed in the loop below.
    for(round=1; round<Nr; round++)  {
        SubBytes(state);
        ShiftRows(state);
        MixColumns(state);
        AddRoundKey(round,state,expanded_key);
    }

    // The last round is given below.
    // The MixColumns function is not here in the last round.
    SubBytes(state);
    ShiftRows(state);
    AddRoundKey(Nr,state,expanded_key);

    // The encryption process is over.
    // Copy the state array to output array.
    for(i=0; i<4; i++)  {
        for(j=0; j<4; j++)  {
            out[i*4+j]=state[j][i];
        }
    }
}
Exemple #20
0
/*
 * This method performs encrypt operation given plaintext.
 * It read tables from tf and plaintext from fp.
 * Encrypts plainetxt using key
 */
void ProcessEncrypt(char *key, FILE *tf, FILE *fp) {
	table_check = 0;
	ProcessTableCheck(tf);
	char buf[16];
	int ret = fread(buf, 1, 16, fp);
	if (ret < 16) {
		fprintf(stderr,
				"Input size for encryption can not be less than 16 bytes\n");
		exit(1);
	}
	int i, Nr = 10, Nb = 4, round;
	unsigned char **state = (unsigned char **) malloc(
			sizeof(unsigned char *) * 4);
	for (i = 0; i < 4; i++)
		state[i] = (unsigned char *) malloc(sizeof(unsigned char) * 4);
	copyInStateArray(state, buf);
	unsigned char **word = doProcessKeyExpand(key);
	printOut(state, "input", 0);
	AddRoundKey(state, word, 0);
	printWord(word, "k_sch", 0, 0);
	for (round = 1; round < Nr; round++) {
		printOut(state, "start", round);
		SubBytes(state);
		printOut(state, "s_box", round);
		ShiftRows(state);
		printOut(state, "s_row", round);
		MixColumns(state, P);
		printOut(state, "m_col", round);
		AddRoundKey(state, word, round * Nb);
		printWord(word, "k_sch", round * Nb, round);
	}
	printOut(state, "start", round);
	SubBytes(state);
	printOut(state, "s_box", round);
	ShiftRows(state);
	printOut(state, "s_row", round);
	AddRoundKey(state, word, Nr * Nb);
	printWord(word, "k_sch", Nr * Nb, round);
	printOut(state, "output", round);
}
Exemple #21
0
void
AES_Cipher(void *_ctx, u1 *data)
{
	char	r;
	AES_CTX	*ctx = (AES_CTX *)_ctx;
	u4	*w = ctx->W;

	AddRoundKey((u4 *)data, w);
	w += 4;
	for(r = 1;r < ctx->Nr;r++) {
		SubBytes(data);
		ShiftRows(data);
		MixColumns(data);
		AddRoundKey((u4 *)data, w);

		w += 4;
	}

	SubBytes(data);
	ShiftRows(data);
	AddRoundKey((u4 *)data, w);
}
Exemple #22
0
static void
buildAESCircuit(GarbledCircuit *gc, block *inputLabels)
{
	GarblingContext ctxt;

	int q = 50000; //Just an upper bound
	int r = 50000;
    int *addKeyInputs = calloc(2 * m, sizeof(int));
    int *addKeyOutputs = calloc(m, sizeof(int));
    int *subBytesOutputs = calloc(m, sizeof(int));
    int *shiftRowsOutputs = calloc(m, sizeof(int));
    int *mixColumnOutputs = calloc(m, sizeof(int));
    block *outputMap = allocate_blocks(2 * m);

	createEmptyGarbledCircuit(gc, n, m, q, r, inputLabels);
	startBuilding(gc, &ctxt);

	countToN(addKeyInputs, 256);

	for (int round = 0; round < roundLimit; round++) {

		AddRoundKey(gc, &ctxt, addKeyInputs, addKeyOutputs);

		for (int i = 0; i < 16; i++) {
			SubBytes(gc, &ctxt, addKeyOutputs + 8 * i, subBytesOutputs + 8 * i);
		}

		ShiftRows(gc, &ctxt, subBytesOutputs, shiftRowsOutputs);

		for (int i = 0; i < 4; i++) {
			if (round != roundLimit - 1)
				MixColumns(gc, &ctxt, shiftRowsOutputs + i * 32,
                           mixColumnOutputs + 32 * i);
		}
		for (int i = 0; i < 128; i++) {
			addKeyInputs[i] = mixColumnOutputs[i];
			addKeyInputs[i + 128] = (round + 2) * 128 + i;
		}
	}

	finishBuilding(gc, &ctxt, outputMap, mixColumnOutputs);
	/* writeCircuitToFile(gc, AES_CIRCUIT_FILE_NAME); */

    free(addKeyInputs);
    free(addKeyOutputs);
    free(subBytesOutputs);
    free(shiftRowsOutputs);
    free(mixColumnOutputs);
    free(outputMap);
}
Exemple #23
0
int main(int argc, char** argv){

  print(state);

  KeySchedule();
  AddRoundKey();

  for(iteracja = 1; iteracja < ROUND_cnt; ++iteracja){
    SubBytes();
    ShiftRows();
    MixColumns();
   print(state);
   AddRoundKey();   
  }
  SubBytes();
  ShiftRows()
  AddRoundKey();

  print(state); /*encrypted*/

  AddRoundKey();
  InvShiftRows();
  InvSubBytes();
  for(iteracja = ROUND_cnt-1; iteracja > 0; --iteracja){
    AddRoundKey();
    InvMixColumns();
    InvShiftRows();
    InvSubBytes();
  }
  AddRoundKey();

  print(state);

  return 0;

}
Exemple #24
0
void ExpansionCle(char cle[], char unsigned cleEtendue[TAILLEMATRICE*(NBROUND+1)][TAILLEMATRICE]){

    int caractere, round, ligne;

    unsigned char wMoinsUn[TAILLEMATRICE][TAILLEMATRICE]={0};
    unsigned char wMoinsQuatre[TAILLEMATRICE];

    memset(cleEtendue, 0, TAILLEMATRICE*NBROUND);

    for (caractere=0; caractere<strlen(cle); caractere++){

        cleEtendue[(caractere/TAILLEMATRICE)%TAILLEMATRICE][caractere%TAILLEMATRICE]=cle[caractere];

    }

    for(round=1; round<=NBROUND*TAILLEMATRICE; round++){

        for(ligne=0; ligne<TAILLEMATRICE; ligne++){

            wMoinsQuatre[ligne]=cleEtendue[(round+TAILLEMATRICE-1)-4][ligne];
            wMoinsUn[1][ligne]=cleEtendue[(round+TAILLEMATRICE-1)-1][ligne];

        }


        if((round-1)%TAILLEMATRICE==0){

                RotWord(wMoinsUn);
                SubBytes(wMoinsUn);
         }

        for(ligne=0; ligne<TAILLEMATRICE; ligne++){


            cleEtendue[TAILLEMATRICE+round-1][ligne]=wMoinsQuatre[ligne]^wMoinsUn[1][ligne];

            if((round-1)%TAILLEMATRICE==0){ (cleEtendue[TAILLEMATRICE+round-1][ligne])^=(Rcon[((round-1)/4)][ligne]);}

        }
    }
}
Exemple #25
0
void test_SubBytes(void)
{
	int i;
	unsigned char expected[] = {
		0x63, 0x7c, 0x77, 0x7b,
        0xca, 0x82, 0xc9, 0x7d,
        0xb7, 0xfd, 0x93, 0x26,
        0x04, 0xc7, 0x23, 0xc3};

	unsigned char actual[] = {
		0x00, 0x01, 0x02, 0x03,
		0x10, 0x11, 0x12, 0x13,
		0x20, 0x21, 0x22, 0x23,
		0x30, 0x31, 0x32, 0x33};
	SubBytes(actual);

	for (i = 0; i < 4*4; i++)
	{
	  CU_ASSERT_INT_EQ(expected[i], actual[i]);
	}
}
Exemple #26
0
///////////////////////////////////////////////////////////////////////////////
//	函数名:	BlockDecrypt
//	描述:		对单块数据解密。
//	输入参数:	pState -- 状态数据。
//	输出参数:	pState -- 解密后的状态数据。
//	返回值:	无。
///////////////////////////////////////////////////////////////////////////////
static void BlockDecrypt(unsigned char *pState)
{
	unsigned char i;
	
	AddRoundKey(pState, &g_roundKeyTable[4*Nb*Nr]);
	
	for (i = Nr; i > 0; i--)	// i = [Nr, 1]
	{
		ShiftRows(pState, 1);
		SubBytes(pState, 4*Nb, 1);
		AddRoundKey(pState, &g_roundKeyTable[4*Nb*(i-1)]);

		if (i != 1)
		{
			MixColumns(pState, 1);
		}
	}
	
// 为了节省代码,合并到循化执行
//  ShiftRows(pState, 1);
//  SubBytes(pState, 4*Nb, 1);
//  AddRoundKey(pState, g_roundKeyTable);
}
/*
 * One AES round
 */
void AES_round( word P, word K, word C)
{
  int i,j;
  unsigned char state[4][4];

  // Convert the 16 byte sequence to a 4x4 matrix
  for(i=0; i<4; i++)
    for(j=0; j<4; j++)
      state[i][j] = P[ 4 * j + i ];

  // Apply keyless AES round
  SubBytes  ( state );
  ShiftRows ( state );
  MixColumns( state );

  // Convert the 4x4 matrix to 16-byte sequence
  for(i=0; i<4; i++)
    for(j=0; j<4; j++)
      C[ 4 * j + i ] = state[i][j];

  // Xor the key
  for(i=0; i<16; i++)
    C[i] ^= K[i];
}
Exemple #28
0
///////////////////////////////////////////////////////////////////////////////
//	函数名:	BlockEncrypt
//	描述:		对单块数据加密。
//	输入参数:	pState -- 状态数据。
//	输出参数:	pState -- 加密后的状态数据。
//	返回值:	无。
///////////////////////////////////////////////////////////////////////////////
static void BlockEncrypt(unsigned char *pState)
{
	unsigned char i;
	
	AddRoundKey(pState, g_roundKeyTable);
	
	for (i = 1; i <= Nr; i++)	// i = [1, Nr]
	{
		SubBytes(pState, 4*Nb, 0);
		ShiftRows(pState, 0);

		if (i != Nr)
		{
			MixColumns(pState, 0);
		}

		AddRoundKey(pState, &g_roundKeyTable[4*Nb*i]);
	}
	
// 为了节省代码,合并到循化执行
// 	SubBytes(pState, 4*Nb);
//	ShiftRows(pState, 0);
// 	AddRoundKey(pState, &g_roundKeyTable[4*Nb*Nr]);
}
Exemple #29
0
// La fonction cipher sert a chiffrer le bloc de message
void Cipher(unsigned char *C, unsigned char M[], unsigned char Key[], int Nr)
{
	int i,j,round=0;
	unsigned char T[16],U[16], V[16],W[16];
	unsigned char RoundKey[240];

	//On fabrique les clefs de ronde
	KeyExpansion( RoundKey, Key, 10);


	//On copide le messge dans le bloc d'etat 
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			W[4*j+i] = M[4*j + i];
		}
	}


//    for (i=0; i<4;i++) {
//        for (j=16; j<24; j++) {
//            if (!(j%4))
//                printf("  ");    
//            printf("%02x ", RoundKey[j*4 + i]);
//        }
//        printf("\n");
//    }

    //printf("\n");

	// AddKey de la premiere clef
	AddRoundKey(T,W,RoundKey,0); 

	// Il y a Nr rondes.
	// Les Nr-1 premieres rondes sont identiques
	// Ces Nr-1 rondes sont effectuées dans la boucle for ci-dessous
	for(round=1;round<Nr;round++)
	{
	  SubBytes(U,T);
	  ShiftRows(V,U);
	  MixColumns(W,V);
	  AddRoundKey(T,W,RoundKey,round);
	}	
	// Derniere ronde
	// La fonction MixColumns n'est pas dans la derniere ronde
	SubBytes(U,T);
	ShiftRows(V,U);
	AddRoundKey(W,V,RoundKey,Nr);


	// Le processus de chiffremen est fini
	// On copie le bloc d'etat du message dans le bloc de message chiffre
	for(i=0;i<4;i++)
	{
		for(j=0;j<4;j++)
		{
			C[j*4+i]=W[4*j+i];
		}
	}
}
Exemple #30
0
void  chiffrerBloc(unsigned char mat[TAILLEMATRICE][TAILLEMATRICE], unsigned char cleEtendue[TAILLEMATRICE*(NBROUND+1)][TAILLEMATRICE]){

int ligne, colonne, round;
        // Traitement du bloc

        for(round=0; round<NBROUND; round++){

        /*//DEBUG BLOC EN CLAIR ------------------------------------------

            printf("\nBLOC EN CLAIR \n");

            for (ligne=0; ligne<TAILLEMATRICE; ligne++){

                for (colonne=0; colonne<TAILLEMATRICE; colonne++){

                   printf("0x%.2X\t"  ,mat[colonne][ligne]);
                }

                 printf("\n");
            }

             printf("\n---------------------------------\n");
            // FIN DEBUG BLOC EN CLAIR---------------------------------------*/

            AddRoundKey(cleEtendue,round,mat);

            /*//DEBUG ADDROUNDKEY----------------------------------------------

            printf("\nADDROUNDKEY [%d] \n",round);

            for (ligne=0; ligne<TAILLEMATRICE; ligne++){

                for (colonne=0; colonne<TAILLEMATRICE; colonne++){

                   printf("0x%.2X\t"  ,mat[colonne][ligne]);
                }

                 printf("\n");
            }

            printf("\n---------------------------------\n");
            // FIN DEBUG BLOC EN CLAIR---------------------------------------*/

            SubBytes(mat);

            /*//DEBUG SUBBYTES------------------------------------------

            printf("DEBUG SUBBYTES[%d] \n",round);

            for (ligne=0; ligne<TAILLEMATRICE; ligne++){

                for (colonne=0; colonne<TAILLEMATRICE; colonne++){

                   printf("0x%.2X\t"  ,mat[colonne][ligne]);
                }

                 printf("\n");
            }

             printf("\n---------------------------------\n");
            // FIN DEBUG SUBBYTES---------------------------------------*/

            ShiftRow(mat);

            /*//DEBUG SHIFTROW------------------------------------------

            printf("DEBUG SHIFTROW[%d] \n",round);

            for (ligne=0; ligne<TAILLEMATRICE; ligne++){

                for (colonne=0; colonne<TAILLEMATRICE; colonne++){

                   printf("0x%.2X\t"  ,mat[colonne][ligne]);
                }

                 printf("\n");
            }

             printf("\n---------------------------------\n");
         // FIN DEBUG SHIFTROW---------------------------------------*/

            if(round!=(NBROUND-1))
            {
                MixColumns(mat);

               /* //DEBUG MIXCOLUMNS------------------------------------------

                printf("DEBUG MIXCOLUMNS [%d] \n",round);

                for (ligne=0; ligne<TAILLEMATRICE; ligne++){

                    for (colonne=0; colonne<TAILLEMATRICE; colonne++){

                       printf("0x%.2X\t"  ,mat[colonne][ligne]);
                    }

                     printf("\n");
                }

                 printf("\n---------------------------------\n");
                // FIN DEBUG MIXCOLUMNS---------------------------------------*/
            }
        }

        AddRoundKey(cleEtendue,round,mat);



       //DEBUG  MESSAGE CRYPTE EN HEXA------------------------------------------

        printf("BLOC CHIFFRE EN HEXA   \n",round);

        for (ligne=0; ligne<TAILLEMATRICE; ligne++){

            for (colonne=0; colonne<TAILLEMATRICE; colonne++){

              printf("0x%.2X\t"  ,mat[colonne][ligne]);
            }

             printf("\n");
        }

        // FIN DEBUG MESSAGE CRYPTE EN HEXA---------------------------------------

}