int main () { u32 text[2]; text[0] = 0x3b726574; text[1] = 0x7475432d; u32 crypt[2] = {0}; u32 l[28] = {0}; u32 k[27] = {0}; l[2] = 0x1b1a1918; l[1] = 0x13121110; l[0] = 0x0b0a0908; k[0] = 0x03020100; START_ENCRYPT(); KeyExpansion ( l, k ); Encrypt ( text, crypt, k ); //printf("%x %x\n%x %x\n\n\n", text[0], text[1], crypt[0], crypt[1]); START_DECRYPT(); KeyExpansion ( l, k ); Decrypt ( crypt, text, k ); //printf("%x %x\n%x %x\n\n\n", text[0], text[1], crypt[0], crypt[1]); END_EXPE(); return 0; }
int main () { u32 text[2]; text[0] = 0x74614620; text[1] = 0x736e6165; u32 crypt[2] = {0}; u32 l[26] = {0}; u32 k[25] = {0}; l[1] = 0x13121110; l[0] = 0x0b0a0908; k[0] = 0x03020100; START_ENCRYPT(); KeyExpansion ( l, k ); Encrypt ( text, crypt, k ); //printf("%x %x\n%x %x\n\n\n", text[0], text[1], crypt[0], crypt[1]); START_DECRYPT(); KeyExpansion ( l, k ); Decrypt ( crypt, text, k ); //printf("%x %x\n%x %x\n\n\n", text[0], text[1], crypt[0], crypt[1]); END_EXPE(); return 0; }
int main() { int i; Nr = 128; Nk = Nr / 32; Nr = Nk + 6; unsigned char temp[16] = {0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07 ,0x08 ,0x09 ,0x0a ,0x0b ,0x0c ,0x0d ,0x0e ,0x0f}; unsigned char temp2[16]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55 ,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff}; for(i=0; i<Nk*4; i++) { Key[i]=temp[i]; in[i]=temp2[i]; } printf("Advanced Encryption Standart (AES)\n\nText before encryption:\n"); for(i=0; i<Nk*4; i++) { printf("%02x ",in[i]); } printf("\n\n"); KeyExpansion(); Cipher(); printf("\nText after encryption:\n"); for(i=0; i<Nk*4; i++) { printf("%02x ",out[i]); } printf("\n\n"); for(i=0; i<Nk*4; i++) { in[i] = out[i]; } KeyExpansion(); InvCipher(); printf("\nText after decryption:\n"); for(i=0; i<Nk*4; i++) { printf("%02x ",out[i]); } printf("\n\n"); getch(); return 0; }
void chiffrement_AES_ModeCompteur(char* data,unsigned int nbChar, unsigned char nonce[16], unsigned char Key[16]) { unsigned char bloc[16],nonce_cipher[16]; unsigned char cypherKey[4][4]; unsigned char keySchedule[4][44]; unsigned char *pt_courant; int i, nbBlocs,nbReste; for(i=0; i< 4; i++) memcpy(&cypherKey[i], &Key[i*4],4); KeyExpansion (cypherKey,keySchedule); //initialisations pt_courant = (unsigned char *)data; nbBlocs = nbChar/16; nbReste = nbChar%16; while(nbBlocs >0) { //chiffrer le compteur avec AES et la clé de chiffrement eas_encryption(nonce,keySchedule,nonce_cipher); //recuperer un bloc de 128 bits memcpy(bloc,pt_courant,16); //XOR for(i=0; i< 16; i++) bloc[i] = nonce_cipher[i] ^ bloc[i]; memcpy(pt_courant,bloc,16); pt_courant=&pt_courant[16]; //incrémentation de la nonce for(i=0; i< 16; i++) if(++nonce[i] != 0)break; nbBlocs--; } if(nbReste != 0) { //chiffrer le compteur avec AES et la clé de chiffrement eas_encryption(nonce,keySchedule,nonce_cipher); //recuperer un bloc de 128 bits memcpy(bloc,pt_courant,nbReste); //XOR for(i=0; i< 16; i++) bloc[i] = nonce_cipher[i] ^ bloc[i]; memcpy(pt_courant,bloc,nbReste); } }
/* * CBC decryption routine * size of 'input' has to be multiple of 16 * 'input' contains cleartext on exit * 'iv' must hold the same 16 byte initialization vector * that has been used to encrypt the cleartext */ int decryptCBC(unsigned char *input, int len, unsigned char *key, int klen, unsigned char *iv) { int i; unsigned char w[32 * 15] = {0}; unsigned char k[32] = {0}; unsigned char piv[16]; unsigned char tpiv[16]; if (input == 0 || key == 0 || iv == 0) { return 0; } memcpy(piv, iv, 16); memcpy(k, key, min(klen, 32)); KeyExpansion(k, w, 8); for (i = 0; i < len; i += 16) { int n; memcpy(tpiv, &input[i], 16); decryptBlock(&input[i], &input[i], w, 14); for (n = 0; n < 16; n++) { input[i+n] ^= piv[n]; } memcpy(piv, tpiv, 16); } return 1; }
//============================================================================== 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]); }
int main(int argc, char *argv[]) { // Key and 16 byte block as per FIPS 197, Appendix B (Cipher Example) byte_ard pKey[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; // The ciphertext according to the FIPS and block_e.cpp byte_ard pCipherBlock[] = { 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 }; // Allocate memory and generate the key schedule byte_ard pKeys[KEY_BYTES*12]; KeyExpansion(pKey, pKeys); printf("\nCiphertext: \n"); printBytes2((unsigned char *)pCipherBlock, BLOCK_SIZE); #ifdef print_key_schedule printf("\nKey Schdedule: \n"); printBytes2((unsigned char *)pKeys, BLOCK_SIZE*11); printf("\n"); #endif // Decrypt the single block DecryptBlock(pCipherBlock, (const u_int32_ard*)pKeys); printf("\nPlaintext: \n"); printBytes2((unsigned char *)pCipherBlock, BLOCK_SIZE); return 0; }
void aes_decrypt_dpi(svBitVecVal * pt, svBitVecVal * key, int Nk, svBitVecVal * ct) { int i; byte_t KEY[32]; byte_t RKEY[240]; byte_t PT[16], CT[16]; byte_t * bp; word_t * wp; // Number of 32-bit words comprising the Cipher Key. // For this standard, Nk = 4, 6, or 8. (Sec 6.3) bp = key; for (i = 0; i < 4*Nk; i++) KEY[i] = *bp++; bp = ct; for (i = 0; i < 16; i++) CT[i] = *bp++; KeyExpansion(KEY, RKEY, Nk); InvCipher(CT, PT, RKEY, Nk); wp = (word_t *) PT; for (i = 0; i < 4; i++) pt[i] = *wp++; }
int main() { int i; int Nr = 0; int Nk = 0; unsigned char Key[32]= {0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07 ,0x08 ,0x09 ,0x0a ,0x0b ,0x0c ,0x0d ,0x0e ,0x0f}; unsigned char in[16]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55 ,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff}; unsigned char out[16]; InitUART1(); while(Nr!=128 && Nr!=192 && Nr!=256) { SendString("Enter the length of Key(128, 192 or 256 only): "); Nr = GetKey(); } Nk = Nr / 32; Nr = Nk + 6; KeyExpansion(Key, Nk, Nr); Cipher(in, out, Nr); SendString("Text encrypted: "); for(i = 0; i < Nb*4; i++) { SendStringFromNum(out[i]); } SendEnter(); while(1); }
void TestEncrypt( void ) { //int32_t k=0; int32_t Nk=4, Nr=10; /* Plain Text: 00112233445566778899aabbccddeeff */ uint8_t pt[AES_BLOCK_SIZE] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; /* Key: 000102030405060708090a0b0c0d0e0f */ uint8_t Key[AES_BLOCK_SIZE] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; //uint8_t ZeroKey[AES_BLOCK_SIZE] = {0}; uint8_t eKey[AES_MAX_KEY_SIZE] = {0}; /* Cipher Text: 69c4e0d86a7b0430d8cdb78070b4c55a */ KeyExpansion(eKey,Key,Nk,Nr); //for ( k=0; k<Nr+1; ++k ) //{ // printf("%d\t",k); // PrintVec(eKey+(AES_BLOCK_SIZE*k)); // printf("\n"); //} RijndaelEncrypt(pt,eKey,Nr); printf("\n"); PrintVec(pt); printf("\n"); }
void aes_init(ctx_aes* aes, int keySize, uint8_t* keyBytes) { SetNbNkNr(aes, keySize);//初始化 memcpy(aes->key,keyBytes,keySize); KeyExpansion(aes); /* expand the seed key into a key schedule and store in w */ }
void InitAes(int keySize, unsigned char* keyBytes) { SetNbNkNr(keySize);//��ʼ�� memcpy(key,keyBytes,keySize); KeyExpansion(); // expand the seed key into a key schedule and store in w } // Aes constructor
void PRNGInit(PRNGContext* ctx) { unsigned int seed; __asm rdtsc __asm mov seed,eax HashSHA256((u8*)&seed, 4, ctx->prng_key); memset(ctx->prng_key + 32,0,224); KeyExpansion(ctx->prng_key); }
bool AES::SetKey(const unsigned char* szKey) { if (NULL == szKey) { return false; } KeyExpansion(szKey, w); return true; }
int AESCipher::evaluate(const unsigned char* input, const unsigned char* key, unsigned char* output) const { unsigned int key_schedule[60]; // Generate enc key. KeyExpansion(key,key_schedule, 128); // Encrypt. aes_encrypt(input, output, key_schedule, 128, this->rounds); return 1; }
// Manque une fonction de dechiffrement void Decipher(unsigned char *out, unsigned char in[], 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] = in[4*j + i]; } } // On "pele" derniere ronde // La fonction MixColumns n'est pas dans la derniere ronde AddRoundKey(V,W,RoundKey,Nr); InvShiftRows(U,V); InvSubBytes(T,U); // Il y a Nr rondes. // Les Nr-1 premieres rondes sont identiques // Ces Nr-1 rondes sont dechiffrees dans la boucle for ci-dessous for(round=Nr-1;round>0;round--) { AddRoundKey(W,T,RoundKey,round); InvMixColumns(V,W); InvShiftRows(U,V); InvSubBytes(T,U); } // AddKey de la premiere clef AddRoundKey(W,T,RoundKey,0); // Le processus de dechiffremen est fini // On copie le bloc d'etat du message dans le bloc de message clair (out) for(i=0;i<4;i++) { for(j=0;j<4;j++) { out[j*4+i]=W[4*j+i]; } } }
int ZEncryptAES::Init_Key(unsigned char *key, int size) { if(size != 128 && size != 192 && size != 256) return 0; Nk = size / 32; Nr = Nk + 6; for(int i=0;i<Nk*4;i++) Key[i]=key[i]; KeyExpansion(); return 1; }
line AesEncrypt(const void* encrypt_data, const size_t encrypt_data_size, const AesKey& encrypt_key) { unsigned char data[bytes_row_size][bytes_columns_size]; unsigned char expandkey[expand_key_size][bytes_row_size][bytes_columns_size]; unsigned char okdata[bytes_row_size*bytes_columns_size]; line ret; const unsigned char* lp_encrypt = (const unsigned char*)encrypt_data; KeyExpansion(encrypt_key._key,expandkey); for(size_t encrypted = 0; encrypted < encrypt_data_size; encrypted += (bytes_row_size*bytes_columns_size)) { for(size_t row = 0; row < bytes_row_size; ++row) { for(size_t col = 0; col < bytes_columns_size; ++col) { data[row][col] = lp_encrypt[row + col * bytes_columns_size]; } } AddRoundKey(data,expandkey[0]); for(size_t i = 1; i < expand_key_size; ++i) { SubstituteBytes(data); ShiftRows(data); if(i != (expand_key_size - 1)) MixColumns(data); AddRoundKey(data,expandkey[i]); } for(size_t row = 0; row < bytes_row_size; ++row) { for(size_t col = 0; col < bytes_columns_size; ++col) { okdata[row + col * bytes_columns_size] = data[row][col]; } } ret.append(okdata,sizeof(okdata)); lp_encrypt += bytes_row_size * bytes_columns_size; } return ret; }
line AesDecrypt(const void* decrypt_data, const size_t decrypt_data_size, const AesKey& decrypt_key) { unsigned char data[bytes_row_size][bytes_columns_size]; unsigned char expandkey[expand_key_size][bytes_row_size][bytes_columns_size]; unsigned char okdata[bytes_row_size*bytes_columns_size]; line ret; const unsigned char* lp_decrypt = (const unsigned char*)decrypt_data; KeyExpansion(decrypt_key._key,expandkey); for(size_t encrypted = 0; encrypted < decrypt_data_size; encrypted += (bytes_row_size*bytes_columns_size)) { for(size_t row = 0; row < bytes_row_size; ++row) { for(size_t col = 0; col < bytes_columns_size; ++col) { data[row][col] = lp_decrypt[row + col * bytes_columns_size]; } } AddRoundKey(data,expandkey[expand_key_size-1]); for(intptr_t i = expand_key_size - 2; i >= 0; --i) { InvShiftRows(data); InvSubstituteBytes(data); AddRoundKey(data,expandkey[i]); if(i > 0) InvMixColumns(data); } for(size_t row = 0; row < bytes_row_size; ++row) { for(size_t col = 0; col < bytes_columns_size; ++col) { okdata[row + col * bytes_columns_size] = data[row][col]; } } ret.append(okdata,sizeof(okdata)); lp_decrypt += bytes_row_size * bytes_columns_size; } return ret; }
AES::AES() { unsigned char* key ="drmf"; unsigned char sBox[] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, /*0*/ 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, /*1*/ 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, /*2*/ 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, /*3*/ 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, /*4*/ 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, /*5*/ 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, /*6*/ 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, /*7*/ 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, /*8*/ 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, /*9*/ 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, /*a*/ 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, /*b*/ 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, /*c*/ 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, /*d*/ 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, /*e*/ 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 /*f*/ }; unsigned char invsBox[256] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, /*0*/ 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, /*1*/ 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, /*2*/ 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, /*3*/ 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, /*4*/ 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, /*5*/ 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, /*6*/ 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, /*7*/ 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, /*8*/ 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, /*9*/ 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, /*a*/ 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, /*b*/ 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f, /*c*/ 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef, /*d*/ 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61, /*e*/ 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d /*f*/ }; memcpy(Sbox, sBox, 256); memcpy(InvSbox, invsBox, 256); KeyExpansion(key, w); }
void RijndaelInit(RijndaelContextPtr contextPtr) { if (NULL != contextPtr) { //默认使用128位密钥 if (contextPtr->keySize == 0) { contextPtr->keySize = KeySize_128; } contextPtr->nk = contextPtr->keySize / 4; if (contextPtr->plainSize == 0) { contextPtr->plainSize = contextPtr->keySize; } contextPtr->nb = contextPtr->plainSize / 4; contextPtr->nr = (contextPtr->nb > contextPtr->nk) ? contextPtr->nb + 4 : contextPtr->nk + 4; KeyExpansion(contextPtr); } }
/* * ECB decryption routine * size of 'input' has to be multiple of 16 * 'input' contains cleartext on exit */ int decrypt(unsigned char *input, int len, unsigned char *key, int klen) { int i; unsigned char w[32 * 15] = {0}; unsigned char k[32] = {0}; if (input == 0 || key == 0) { return 0; } memcpy(k, key, min(klen, 32)); KeyExpansion(k, w, 8); for (i = 0; i < len; i += 16) { decryptBlock(&input[i], &input[i], w, 14); } return 1; }
int main (void) { PINSEL10 = 0; /* Disable ETM interface */ FIO2DIR = LEDMSK; /* LEDs, port 2, bit 0~7 output only */ lcd_init(); lcd_clear(); lcd_print ("MCB2300 HID Demo"); set_cursor (0, 1); lcd_print (" www.keil.com "); Nr = 128; Nk = Nr / 32; Nr = Nk + 6; KeyExpansion(Key, Nk, Nr); USB_Init(); /* USB Initialization */ USB_Connect(TRUE); /* USB Connect */ while (1); /* Loop forever */ }
int main(void){ unsigned char key[Nk*4] = { 1, 2, 3, 4, 5, 6, 7, 8 }; unsigned char exkey[Nb * (Nr + 1) * 4]; unsigned char State[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 7, 7, 7, 7, 7, 7 }; char hexs[16 * 2 + 1]; KeyExpansion(key, exkey); Encrypt(State, exkey); toHex(State, 16, hexs); printf("%s\n", hexs); Decrypt(State, exkey); toHex(State, 16, hexs); printf("%s\n", hexs); /* 输出: 33D19245695D96C60CCB73DB7E0FB1E9 01020304050607080907070707070707 */ }
int aes::AES_do_decrypt_from_file(char *infile, char *outfile, unsigned long *CifKey) { BYTE* in = new BYTE[4*Nb]; printf("Decoding...\n"); GenPowerTab(); GenSubBytesTab(); FILE* stream_in; FILE* stream_out; if ( !(stream_in = fopen(infile, "rb"))) { printf("File in: %s cannot be read", infile); return -1; } if ( !(stream_out = fopen(outfile, "wb")) ) { printf("File out: %s cannot be read", outfile); return -1; } fpos_t flen; // fseek(stream_in, 0, SEEK_END); fgetpos(stream_in, &flen); unsigned long rlen = file_len(flen); // fseek(stream_in, 0, SEEK_SET); WORD ExpKey[Nb*(Nr+1)]; //WORD CifKey[Nk] = { 0x00010203, 0x04050607, // 0x08090a0b, 0x0c0d0e0f}; KeyExpansion(CifKey, ExpKey); while(rlen > 0 && !feof(stream_in)) { unsigned long len = (unsigned long)fread(in, 1, 4*Nb, stream_in); if (rlen < 4*Nb) for (int i = rlen; i < 4*Nb; i++) in[i] = 0; rlen -= len; //if (len != 4*Nb) #ifdef LOGit printf("\nNew block\n"); for(int i=0; i<4; i++) { printf("%02x %02x %02x %02x\n", in[i], in[4+i], in[8+i], in[12+i]); } #endif AddRoundKey((WORD*)in, &ExpKey[4*Nr]); InvCipher((WORD*)in, ExpKey); if (rlen == 1) { BYTE* out = new BYTE[1]; fread(out, sizeof(BYTE), 1, stream_in); len = out[0]; rlen = 0; } int nWritten = fwrite(in, sizeof(BYTE), len, stream_out); } fclose(stream_out); }
int main() { int i; // Recieve the length of key here. while(Nr!=128 && Nr!=192 && Nr!=256) { printf("Enter the length of Key(128, 192 or 256 only): "); scanf("%d",&Nr); } // Calculate Nk and Nr from the recieved value. Nk = Nr / 32; Nr = Nk + 6; // Part 1 is for demonstrative purpose. The key and plaintext are given in the program itself. // Part 1: ******************************************************** // The array temp stores the key. // The array temp2 stores the plaintext. unsigned char temp[32] = {0x00 ,0x01 ,0x02 ,0x03 ,0x04 ,0x05 ,0x06 ,0x07 ,0x08 ,0x09 ,0x0a ,0x0b ,0x0c ,0x0d ,0x0e ,0x0f}; unsigned char temp2[32]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55 ,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff}; // Copy the Key and PlainText for(i=0;i<Nk*4;i++) { Key[i]=temp[i]; in[i]=temp2[i]; } // ********************************************************* // Uncomment Part 2 if you need to read key and plaintext from the keyboard. // Part 2: ******************************************************** /* //Clear the input buffer flushall(); //Recieve the key from the user printf("Enter the Key in hexadecimal: "); for(i=0;i<Nk*4;i++) { scanf("%x",&Key[i]); } printf("Enter the PlainText in hexadecimal: "); for(i=0;i<Nb*4;i++) { scanf("%x",&in[i]); } */ // ******************************************************** // The KeyExpansion routine must be called before encryption. KeyExpansion(); // The next function call encrypts the PlainText with the Key using AES algorithm. Cipher(); // Output the encrypted text. printf("\nText after encryption:\n"); for(i=0;i<Nb*4;i++) { printf("%02x ",out[i]); } printf("\n\n"); }
int main( int argc, char *argv[] ) { unsigned int itr; int operacao; int verbose; int juntar; char * chave_file; char * entrada_file; char * saida_file; octeto Nb,Nk,Nr; octeto bloco[4*8]; octeto chave[4*8*15]; int worldsize, rank; MPI_Status status; MPI_File chave_handle; MPI_File entrada_handle; MPI_File saida_handle; MPI_Offset entrada_bytes; unsigned int numero_blocos; unsigned int blocos_processo; MPI_Offset bloco_byte_inicio; MPI_Offset bloco_byte_fim; MPI_Offset iterador; Tabela * tabela; octeto * tabelaEmpacotada; unsigned int proc; unsigned int tamanho_tabela; Tabela * tabela2; unsigned int no_proc; unsigned int no_resto; unsigned int i; BTreeNode * node; Indice * indice; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&worldsize); MPI_Comm_rank(MPI_COMM_WORLD,&rank); operacao = INDEFINIDA; verbose = 0; juntar = 0; chave_file = NULL; entrada_file = NULL; saida_file = NULL; for(itr = 1;itr < (unsigned int)argc;itr++) { /* Instrucoes de uso */ if( strcmp(argv[itr],"-a") == 0 || strcmp(argv[itr],"--ajuda") == 0 || strcmp(argv[itr],"-h") == 0 || strcmp(argv[itr],"--help") == 0 ) { if(rank == 0) { printf(" Uso: mpiexec -n [PROCESSOS] ./sm-rijndael [ARGUMENTO VALOR].\n"); printf(" Encripta/Decripta um arquivo usando o algoritmo Rijndael(AES) extendido,\n"); printf(" realizando um pre-processamento de blocos repetidos.\n"); printf(" Argumentos opcionais:\n"); printf(" -v,--verbose: Exibe mensagens de conclusao da operacao.\n"); printf(" -j,--juntar: Concatena as tabelas de cada processo em um mestre.\n"); printf(" Argumentos obrigatorios:\n"); printf(" -op,--operacao: Informa se o objetivo da execucao eh encriptar ou decriptar.\n"); printf(" * Os valores possiveis sao: \'encriptar\' e \'decriptar\'.\n"); printf(" -e,-i,--entrada,--input: Caminho e nome do arquivo a ser criptografado.\n"); printf(" -s,-o,--saida,--output: Caminho e nome do arquivo resultante do processo de criptografia da entrada.\n"); printf(" -c,-k,--chave,--key: Caminho e nome do arquivo contendo a chave.\n"); printf(" O arquivo contendo a chave eh em formato binario de acordo com a seguinte especificacao:\n"); printf(" - O primeiro byte deve conter o tamanho do bloco (em palavras de 4 bytes).\n"); printf(" * O bloco pode possuir tamanho: 4, 5, 6, 7 ou 8.\n"); printf(" - O segundo byte deve conter o tamanho da chave (em palavras de 4 bytes).\n"); printf(" * Esta aplicacao aceita chaves com tamanho: 4, 5, 6, 7 ou 8.\n"); printf(" - Os proximos 4*[tamanho da chave] bytes do arquivo sao os bytes componentes da chave, que\n"); printf(" devem estar (obrigatoriamente) escritos no formato hexadecimal da linguagem C (0xff).\n"); printf(" * Eh recomendavel o uso de um editor hexadecimal na construcao do arquivo chave.\n"); } goto finalizando; } /* Juntar: Concatena as tabelas de cada processo em um mestre */ else if( strcmp(argv[itr],"-j") == 0 || strcmp(argv[itr],"--juntar") == 0) { juntar = 1; } /* Verbose: exibir mensagens de finalizacao */ else if( strcmp(argv[itr],"-v") == 0 || strcmp(argv[itr],"--verbose") == 0) { verbose = 1; } /* Operacao a ser realizada */ else if( strcmp(argv[itr],"-op") == 0 || strcmp(argv[itr],"--operacao") == 0 ) { if( itr+1 < argc ) { if( strcmp(argv[itr+1],"encriptar") == 0 ) { operacao = ENCRIPTAR; } else if( strcmp(argv[itr+1],"decriptar") == 0 ) { operacao = DECRIPTAR; } itr++; } else { goto sempar; } } /* Arquivo com a chave */ else if( strcmp(argv[itr],"-c") == 0 || strcmp(argv[itr],"--chave") == 0 || strcmp(argv[itr],"-k") == 0 || strcmp(argv[itr],"--key") == 0 ) { if(itr+1 < argc) { chave_file = argv[itr+1]; itr++; } else { goto sempar; } } /* Arquivo de entrada */ else if( strcmp(argv[itr],"-e") == 0 || strcmp(argv[itr],"--entrada") == 0 || strcmp(argv[itr],"-i") == 0 || strcmp(argv[itr],"--input") == 0 ) { if(itr+1 < argc) { entrada_file = argv[itr+1]; itr++; } else { goto sempar; } } /* Arquivo de saida */ else if( strcmp(argv[itr],"-s") == 0 || strcmp(argv[itr],"--saida") == 0 || strcmp(argv[itr],"-o") == 0 || strcmp(argv[itr],"--output") == 0 ) { if(itr+1 < argc) { saida_file = argv[itr+1]; itr++; } else { goto sempar; } } /* Erro desconhecido */ else { if(rank == 0) { printf("Erro nos argumentos passados.\n"); } goto help; } } /* Fim da leitura dos argumentos */ if( operacao == INDEFINIDA || chave_file == NULL || entrada_file == NULL || saida_file == NULL ) { if(rank == 0) { if( operacao == INDEFINIDA ) printf("A operacao a ser realizada eh invalida ou nao foi especificada.\n"); if( chave_file == NULL ) printf("Esta faltando especificar o arquivo com a chave.\n"); if( entrada_file == NULL ) printf("Esta faltando especificar o arquivo de entrada.\n"); if( saida_file == NULL ) printf("Esta faltando especificar o arquivo de saida.\n"); } goto help; } /* Fim do tratamento dos argumentos */ if( MPI_File_open( MPI_COMM_WORLD, chave_file, MPI_MODE_RDONLY, MPI_INFO_NULL, &chave_handle ) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na abertura do arquivo com a chave (%s).\n",chave_file); } goto help; } if( MPI_File_read(chave_handle,&Nb,1, MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na leitura do tamanho de um bloco no arquivo com a chave (%s).\n",chave_file); } goto help; } if( Nb< 4 || Nb > 8 ) { if( rank == 0 ) { printf("Tamanho de bloco invalido no arquivo com a chave (%s).\n",chave_file); } goto help; } if( MPI_File_read(chave_handle,&Nk,1, MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na leitura do tamanho da chave no arquivo com a chave (%s).\n",chave_file); } goto help; } if( Nk< 4 || Nk > 8 ) { if( rank == 0 ) { printf("Tamanho de chave invalido no arquivo com a chave (%s).\n",chave_file); } goto help; } if( MPI_File_read(chave_handle,chave,4*Nk,MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na leitura da chave no arquivo com a chave (%s).\n",chave_file); } goto help; } MPI_File_close( &chave_handle ); Nr = numero_rodadas(Nb,Nk); KeyExpansion(chave,Nb,Nk); if( MPI_File_open( MPI_COMM_WORLD, entrada_file, MPI_MODE_RDONLY, MPI_INFO_NULL, &entrada_handle ) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na abertura do arquivo de entrada (%s).\n",entrada_file); } goto help; } MPI_File_get_size(entrada_handle,&entrada_bytes); if( MPI_File_open( MPI_COMM_WORLD, saida_file, MPI_MODE_RDWR | MPI_MODE_CREATE | MPI_MODE_EXCL, MPI_INFO_NULL, &saida_handle ) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro na criacao do arquivo de saida (%s).\n",saida_file); printf("Uma possivel causa eh que o arquivo ja exista.\n"); } goto help; } numero_blocos = ( entrada_bytes / (Nb*4) ); blocos_processo = numero_blocos / worldsize; if( operacao == ENCRIPTAR || operacao == DECRIPTAR ) { bloco_byte_inicio = 4*Nb*blocos_processo*rank; bloco_byte_fim = 4*Nb*blocos_processo*(rank+1); tabela = novaTabela(Nb*4); for( iterador = bloco_byte_inicio ; iterador < bloco_byte_fim ; iterador += (4*Nb) ) { if( MPI_File_read_at(entrada_handle,iterador,bloco,(4*Nb),MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro ao ler do arquivo de entrada (%s).\n",entrada_file); } goto help; } novaOcorrenciaTabela(tabela,bloco,iterador); } iterador = 4*Nb*blocos_processo*worldsize + 4*Nb*rank; if( iterador < numero_blocos*4*Nb ) { if( MPI_File_read_at(entrada_handle,iterador,bloco,(4*Nb),MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro ao ler do arquivo de entrada (%s).\n",entrada_file); } goto help; } novaOcorrenciaTabela(tabela,bloco,iterador); } else if( operacao == ENCRIPTAR && iterador == numero_blocos*4*Nb ) { if( MPI_File_read_at(entrada_handle,iterador,bloco,(4*Nb),MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro ao ler do arquivo de entrada (%s).\n",entrada_file); } goto help; } bloco[ 4*Nb - 1 ] = (octeto)(entrada_bytes - numero_blocos*4*Nb); novaOcorrenciaTabela(tabela,bloco,iterador); } if( juntar == 1 ) { tabelaEmpacotada = (octeto*)malloc( entrada_bytes ); if( rank == 0 ) /* Mestre que vai concatenar todas as arvores*/ { for(proc=1;proc<worldsize;proc++) { MPI_Recv( tabelaEmpacotada, entrada_bytes, MPI_BYTE, MPI_ANY_SOURCE, TAG_TABELA_EMPACOTADA, MPI_COMM_WORLD, &status ); desempacotarInserindo(tabelaEmpacotada,tabela); } tamanho_tabela = numeroBlocosTabela(tabela); no_proc = (tamanho_tabela / worldsize); no_resto = (tamanho_tabela % worldsize); tabela2 = novaTabela(Nb*4); for(proc=1;proc<worldsize;proc++) { for(i=0;i<no_proc;i++) { soInsiraTabela(tabela2, popLastTabelaNode(tabela) ); } if( no_resto > 1 ) { soInsiraTabela(tabela2, popLastTabelaNode(tabela) ); no_resto--; } empacotarTabela(tabela2,tabelaEmpacotada); MPI_Send(tabelaEmpacotada,numeroBytesTabela(tabela2), MPI_BYTE, proc, TAG_TABELA_EMPACOTADA_2, MPI_COMM_WORLD ); destruirArvore(tabela2->root); tabela2->root = NULL; } destruirTabela(tabela2); } else { empacotarTabela(tabela,tabelaEmpacotada); MPI_Send(tabelaEmpacotada,numeroBytesTabela(tabela), MPI_BYTE, 0, TAG_TABELA_EMPACOTADA, MPI_COMM_WORLD ); destruirArvore(tabela->root); tabela->root = NULL; MPI_Recv( tabelaEmpacotada, entrada_bytes, MPI_BYTE, 0, TAG_TABELA_EMPACOTADA_2, MPI_COMM_WORLD, &status ); desempacotarInserindo(tabelaEmpacotada,tabela); } free(tabelaEmpacotada); } if( operacao == ENCRIPTAR ) MPI_File_set_size(saida_handle,(MPI_Offset)( (numero_blocos+1)*(Nb*4) ) ); else if( operacao == DECRIPTAR ) MPI_File_set_size(saida_handle,entrada_bytes); tamanho_tabela = numeroBlocosTabela(tabela); for( i=0 ; i<tamanho_tabela ; i++ ) { node = popLastTabelaNode(tabela); // memcpy (bloco,node->bloco,4*Nb); if( operacao == ENCRIPTAR ) AES_encriptar_bloco(node->bloco,Nb,chave,Nr); else if( operacao == DECRIPTAR ) AES_decriptar_bloco(node->bloco,Nb,chave,Nr); indice = node->ocorrencias; while( indice != NULL ) { if( MPI_File_write_at(saida_handle,indice->indice,node->bloco,(4*Nb),MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro ao escrever no arquivo de saida (%s).\n",saida_file); } goto help; } indice = indice->next; } destruirArvore(node); } destruirTabela(tabela); if( operacao == DECRIPTAR ) { MPI_Barrier( MPI_COMM_WORLD ); /*Barreira q impede q alguem leia antes do valor decriptografado ser escrito */ if( MPI_File_read_at(saida_handle,entrada_bytes-1,bloco,1,MPI_BYTE,&status) != MPI_SUCCESS ) { if( rank == 0 ) { printf("Erro ao realizar leitura no arquivo de saida (%s).\n",saida_file); } goto help; } MPI_Barrier( MPI_COMM_WORLD ); /* Barreira q impede q alqum processo trunque o arquivo antes de outro processo ler*/ MPI_File_set_size(saida_handle,entrada_bytes - 4*Nb + bloco[0]); } if( rank == 0 && verbose==1) { if( operacao == ENCRIPTAR ) printf("A encriptacao do arquivo foi realizada com sucesso.\n"); else if( operacao == DECRIPTAR ) printf("A decriptacao do arquivo foi realizada com sucesso.\n"); } } goto finalizando; sempar: if( rank == 0 ) { printf("Sem par correspondente para a opcao %s.\n",argv[itr]); } help: if( rank == 0 ) { printf("Use a opcao --help para melhor entendimento do uso da aplicacao.\n"); } finalizando: MPI_Finalize( ); return 0; }
void Aes_setKey(int keysize,BYTE* keyBytes,BYTE *w,BYTE *key,BYTE* Nr,BYTE *Nk) { SetNbNkNr(keysize,Nr,Nk); AES_Memcpy(key,keyBytes,keysize); KeyExpansion(w,key,*Nr,*Nk); }
AES::AES(unsigned char* key) { KeyExpansion(key, w); }
static PyObject* aesDecrypt ( PyObject* self, PyObject* args) { static int run = 0; Py_ssize_t count; uint8_t *fileRead = (uint8_t*) malloc(BUFSIZE); memset(fileRead,0,BUFSIZE); uint8_t *decryptOut = (uint8_t*) malloc(BUFSIZE); uint8x16_t *in = (uint8x16_t*) malloc(16); uint8x16_t *out = (uint8x16_t*) malloc(16); uint8x16_t *key_v = (uint8x16_t*) malloc(16); uint8x16_t *iv_v = (uint8x16_t*) malloc(16); uint8_t RoundKey[176]; static uint8x16_t RoundKey_v[11]; uint8_t *key = (uint8_t*) malloc(KEYLEN); PyArg_ParseTuple(args, "s#|s#", &fileRead, &count, &key, &count); if(key == NULL) { return Py_BuildValue("s#", "Key Read Error", count); } *iv_v = vld1q_u8(iv); Key = key; KeyExpansion(RoundKey); int i; for(i=0; i<11; i++) { RoundKey_v[i] = vld1q_u8(RoundKey+(i*16)); } if(fileRead != 0){ if (run == 0) { uint8_t initial = 0x00; iv[0] = initial; int i =1; for (i = 1; i<15; i++) { iv[i] = iv[i-1]+1; } *in = vld1q_u8(fileRead); AES128_CFB_decrypt(out, *in, run, RoundKey_v, *iv_v); vst1q_u8(decryptOut, *out); run++; } else { *in = vld1q_u8(fileRead); AES128_CFB_decrypt(out, *in, run, RoundKey_v, *iv_v); vst1q_u8(decryptOut, *out); run++; } } return Py_BuildValue("s#", decryptOut, count); }