C语言AES对称加密算法源码
AES加密算法c语言实现代码
/*密钥置换1*/ int DES_PC1_Transform(ElemType key[64], ElemType tempbts[56]){ int cnt; for(cnt = 0; cnt < 56; cnt++){
AES加密算法c语言实现代码
/*将二进制位串转为长度为8的字符串*/ int Bit64ToChar8(ElemType bit[64],ElemType ch[8]){ int cnt; memset(ch,0,8); for(cnt = 0; cnt < 8; cnt++){
BitToByte(bit+(cnt<<3),ch+cnt); } return 0; }
/*扩充置换表E*/ int E_Table[48] = {31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8,9,10,11,12, 11,12,13,14,15,16, 15,16,17,18,19,20, 19,20,21,22,23,24, 23,24,25,26,27,28, 27,28,29,30,31, 0};
/*对左移次数的规定*/ int MOVE_TIMES[16] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};
int ByteToBit(ElemType ch,ElemType bit[8]); int BitToByte(ElemType bit[8],ElemType *ch); int Char8ToBit64(ElemType ch[8],ElemType bit[64]); int Bit64ToChar8(ElemType bit[64],ElemType ch[8]); int DES_MakeSubKeys(ElemType key[64],ElemType subKeys[16][48]); int DES_PC1_Transform(ElemType key[64], ElemType tempbts[56]); int DES_PC2_Transform(ElemType key[56], ElemType tempbts[48]); int DES_ROL(ElemType data[56], int time); int DES_IP_Transform(ElemType data[64]); int DES_IP_1_Transform(ElemType data[64]); int DES_E_Transform(ElemType data[48]); int DES_P_Transform(ElemType data[32]); int DES_SBOX(ElemType data[48]); int DES_XOR(ElemType R[48], ElemType L[48],int count); int DES_Swap(ElemType left[32],ElemType right[32]); int DES_EncryptBlock(ElemType plainBlock[8], ElemType subKeys[16][48], ElemType cipherBlock[8]); int DES_DecryptBlock(ElemType cipherBlock[8], ElemType subKeys[16][48], ElemType plainBlock[8]); int DES_Encrypt(char *plainFile, char *keyStr,char *cipherFile); int DES_Decrypt(char *cipherFile, char *keyStr,char *plainFile);
AES加密C语言实现代码
#define BPOLY 0x1b //!< Lower 8 bits of (x^8+x^4+x^3+x+1), ie. (x^4+x^3+x+1).#define BLOCKSIZE 16 //!< Block size in number of bytes.#define KEY_COUNT 3#if KEY_COUNT == 1#define KEYBITS 128 //!< Use AES128.#elif KEY_COUNT == 2#define KEYBITS 192 //!< Use AES196.#elif KEY_COUNT == 3#define KEYBITS 256 //!< Use AES256.#else#error Use 1, 2 or 3 keys!#endif#if KEYBITS == 128#define ROUNDS 10 //!< Number of rounds.#define KEYLENGTH 16 //!< Key length in number of bytes.#elif KEYBITS == 192#define ROUNDS 12 //!< Number of rounds.#define KEYLENGTH 24 //!< // Key length in number of bytes.#elif KEYBITS == 256#define ROUNDS 14 //!< Number of rounds.#define KEYLENGTH 32 //!< Key length in number of bytes.#else#error Key must be 128, 192 or 256 bits!#endif#define EXPANDED_KEY_SIZE (BLOCKSIZE * (ROUNDS+1)) //!< 176, 208 or 240 bytes.unsigned char AES_Key_Table[32] ={0xd0, 0x94, 0x3f, 0x8c, 0x29, 0x76, 0x15, 0xd8,0x20, 0x40, 0xe3, 0x27, 0x45, 0xd8, 0x48, 0xad,0xea, 0x8b, 0x2a, 0x73, 0x16, 0xe9, 0xb0, 0x49,0x45, 0xb3, 0x39, 0x28, 0x0a, 0xc3, 0x28, 0x3c,};unsigned char block1[256]; //!< Workspace 1.unsigned char block2[256]; //!< Worksapce 2.unsigned char tempbuf[256];unsigned char *powTbl; //!< Final location of exponentiation lookup table.unsigned char *logTbl; //!< Final location of logarithm lookup table. unsigned char *sBox; //!< Final location of s-box.unsigned char *sBoxInv; //!< Final location of inverse s-box. unsigned char *expandedKey; //!< Final location of expanded key.void CalcPowLog(unsigned char *powTbl, unsigned char *logTbl) {unsigned char i = 0;unsigned char t = 1;do {// Use 0x03 as root for exponentiation and logarithms.powTbl[i] = t;logTbl[t] = i;i++;// Muliply t by 3 in GF(2^8).t ^= (t << 1) ^ (t & 0x80 ? BPOLY : 0);}while( t != 1 ); // Cyclic properties ensure that i < 255.powTbl[255] = powTbl[0]; // 255 = '-0', 254 = -1, etc.}void CalcSBox( unsigned char * sBox ){unsigned char i, rot;unsigned char temp;unsigned char result;// Fill all entries of sBox[].i = 0;do {//Inverse in GF(2^8).if( i > 0 ){temp = powTbl[ 255 - logTbl[i] ];}else{temp = 0;}// Affine transformation in GF(2).result = temp ^ 0x63; // Start with adding a vector in GF(2).for( rot = 0; rot < 4; rot++ ){// Rotate left.temp = (temp<<1) | (temp>>7);// Add rotated byte in GF(2).result ^= temp;}// Put result in table.sBox[i] = result;} while( ++i != 0 );}void CalcSBoxInv( unsigned char * sBox, unsigned char * sBoxInv ) {unsigned char i = 0;unsigned char j = 0;// Iterate through all elements in sBoxInv using i.do {// Search through sBox using j.do {// Check if current j is the inverse of current i.if( sBox[ j ] == i ){// If so, set sBoxInc and indicate search finished.sBoxInv[ i ] = j;j = 255;}} while( ++j != 0 );} while( ++i != 0 );}void CycleLeft( unsigned char * row ){// Cycle 4 bytes in an array left once.unsigned char temp = row[0];row[0] = row[1];row[1] = row[2];row[2] = row[3];row[3] = temp;}void InvMixColumn( unsigned char * column ){unsigned char r0, r1, r2, r3;r0 = column[1] ^ column[2] ^ column[3];r1 = column[0] ^ column[2] ^ column[3];r2 = column[0] ^ column[1] ^ column[3];r3 = column[0] ^ column[1] ^ column[2];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);r0 ^= column[0] ^ column[1];r1 ^= column[1] ^ column[2];r2 ^= column[2] ^ column[3];r3 ^= column[0] ^ column[3];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);r0 ^= column[0] ^ column[2];r1 ^= column[1] ^ column[3];r2 ^= column[0] ^ column[2];r3 ^= column[1] ^ column[3];column[0] = (column[0] << 1) ^ (column[0] & 0x80 ? BPOLY : 0);column[1] = (column[1] << 1) ^ (column[1] & 0x80 ? BPOLY : 0);column[2] = (column[2] << 1) ^ (column[2] & 0x80 ? BPOLY : 0);column[3] = (column[3] << 1) ^ (column[3] & 0x80 ? BPOLY : 0);column[0] ^= column[1] ^ column[2] ^ column[3];r0 ^= column[0];r1 ^= column[0];r2 ^= column[0];r3 ^= column[0];column[0] = r0;column[1] = r1;column[2] = r2;column[3] = r3;}void SubBytes( unsigned char * bytes, unsigned char count ){do {*bytes = sBox[ *bytes ]; // Substitute every byte in state.bytes++;} while( --count );}void InvSubBytesAndXOR( unsigned char * bytes, unsigned char * key, unsigned char count ){do {// *bytes = sBoxInv[ *bytes ] ^ *key; // Inverse substitute every byte in state and add key.*bytes = block2[ *bytes ] ^ *key; // Use block2 directly. Increases speed.bytes++;key++;} while( --count );}void InvShiftRows( unsigned char * state ){unsigned char temp;// Note: State is arranged column by column.// Cycle second row right one time.temp = state[ 1 + 3*4 ];state[ 1 + 3*4 ] = state[ 1 + 2*4 ];state[ 1 + 2*4 ] = state[ 1 + 1*4 ];state[ 1 + 1*4 ] = state[ 1 + 0*4 ];state[ 1 + 0*4 ] = temp;// Cycle third row right two times.temp = state[ 2 + 0*4 ];state[ 2 + 0*4 ] = state[ 2 + 2*4 ];state[ 2 + 2*4 ] = temp;temp = state[ 2 + 1*4 ];state[ 2 + 1*4 ] = state[ 2 + 3*4 ];state[ 2 + 3*4 ] = temp;// Cycle fourth row right three times, ie. left once.temp = state[ 3 + 0*4 ];state[ 3 + 0*4 ] = state[ 3 + 1*4 ];state[ 3 + 1*4 ] = state[ 3 + 2*4 ];state[ 3 + 2*4 ] = state[ 3 + 3*4 ];state[ 3 + 3*4 ] = temp;}void InvMixColumns( unsigned char * state ){InvMixColumn( state + 0*4 );InvMixColumn( state + 1*4 );InvMixColumn( state + 2*4 );InvMixColumn( state + 3*4 );}void XORBytes( unsigned char * bytes1, unsigned char * bytes2, unsigned char count ) {do {*bytes1 ^= *bytes2; // Add in GF(2), ie. XOR.bytes1++;bytes2++;} while( --count );}void CopyBytes( unsigned char * to, unsigned char * from, unsigned char count ) {do {*to = *from;to++;from++;} while( --count );}void KeyExpansion( unsigned char * expandedKey ){unsigned char temp[4];unsigned char i;unsigned char Rcon[4] = { 0x01, 0x00, 0x00, 0x00 }; // Round constant.unsigned char * key = AES_Key_Table;// Copy key to start of expanded key.i = KEYLENGTH;do {*expandedKey = *key;expandedKey++;key++;} while( --i );// Prepare last 4 bytes of key in temp.expandedKey -= 4;temp[0] = *(expandedKey++);temp[1] = *(expandedKey++);temp[2] = *(expandedKey++);temp[3] = *(expandedKey++);// Expand key.i = KEYLENGTH;while( i < BLOCKSIZE*(ROUNDS+1) ){// Are we at the start of a multiple of the key size?if( (i % KEYLENGTH) == 0 ){CycleLeft( temp ); // Cycle left once.SubBytes( temp, 4 ); // Substitute each byte.XORBytes( temp, Rcon, 4 ); // Add constant in GF(2).*Rcon = (*Rcon << 1) ^ (*Rcon & 0x80 ? BPOLY : 0);}// Keysize larger than 24 bytes, ie. larger that 192 bits?#if KEYLENGTH > 24// Are we right past a block size?else if( (i % KEYLENGTH) == BLOCKSIZE ) {SubBytes( temp, 4 ); // Substitute each byte.}#endif// Add bytes in GF(2) one KEYLENGTH away.XORBytes( temp, expandedKey - KEYLENGTH, 4 );// Copy result to current 4 bytes.*(expandedKey++) = temp[ 0 ];*(expandedKey++) = temp[ 1 ];*(expandedKey++) = temp[ 2 ];*(expandedKey++) = temp[ 3 ];i += 4; // Next 4 bytes.}}void InvCipher( unsigned char * block, unsigned char * expandedKey ) {unsigned char round = ROUNDS-1;expandedKey += BLOCKSIZE * ROUNDS;XORBytes( block, expandedKey, 16 );expandedKey -= BLOCKSIZE;do {InvShiftRows( block );InvSubBytesAndXOR( block, expandedKey, 16 );expandedKey -= BLOCKSIZE;InvMixColumns( block );} while( --round );InvShiftRows( block );InvSubBytesAndXOR( block, expandedKey, 16 );}void aesDecInit(void){powTbl = block1;logTbl = block2;CalcPowLog( powTbl, logTbl );sBox = tempbuf;CalcSBox( sBox );expandedKey = block1;KeyExpansion( expandedKey );sBoxInv = block2; // Must be block2.CalcSBoxInv( sBox, sBoxInv );}void aesDecrypt( unsigned char * buffer, unsigned char * chainBlock ) {unsigned char temp[ BLOCKSIZE ];CopyBytes( temp, buffer, BLOCKSIZE );InvCipher( buffer, expandedKey );XORBytes( buffer, chainBlock, BLOCKSIZE );CopyBytes( chainBlock, temp, BLOCKSIZE );}unsigned char Multiply( unsigned char num, unsigned char factor ){unsigned char mask = 1;unsigned char result = 0;while( mask != 0 ){// Check bit of factor given by mask.if( mask & factor ){// Add current multiple of num in GF(2).result ^= num;}// Shift mask to indicate next bit.mask <<= 1;// Double num.num = (num << 1) ^ (num & 0x80 ? BPOLY : 0);}return result;}unsigned char DotProduct( unsigned char * vector1, unsigned char * vector2 ) {unsigned char result = 0;result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1++, *vector2++ );result ^= Multiply( *vector1 , *vector2 );return result;}void MixColumn( unsigned char * column ){unsigned char row[8] = {0x02, 0x03, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01};// Prepare first row of matrix twice, to eliminate need for cycling.unsigned char result[4];// Take dot products of each matrix row and the column vector.result[0] = DotProduct( row+0, column );result[1] = DotProduct( row+3, column );result[2] = DotProduct( row+2, column );result[3] = DotProduct( row+1, column );// Copy temporary result to original column.column[0] = result[0];column[1] = result[1];column[2] = result[2];column[3] = result[3];}void MixColumns( unsigned char * state ){MixColumn( state + 0*4 );MixColumn( state + 1*4 );MixColumn( state + 2*4 );MixColumn( state + 3*4 );}void ShiftRows( unsigned char * state ){unsigned char temp;// Note: State is arranged column by column.// Cycle second row left one time.temp = state[ 1 + 0*4 ];state[ 1 + 0*4 ] = state[ 1 + 1*4 ];state[ 1 + 1*4 ] = state[ 1 + 2*4 ];state[ 1 + 2*4 ] = state[ 1 + 3*4 ];state[ 1 + 3*4 ] = temp;// Cycle third row left two times.temp = state[ 2 + 0*4 ];state[ 2 + 0*4 ] = state[ 2 + 2*4 ];state[ 2 + 2*4 ] = temp;temp = state[ 2 + 1*4 ];state[ 2 + 1*4 ] = state[ 2 + 3*4 ];state[ 2 + 3*4 ] = temp;// Cycle fourth row left three times, ie. right once.temp = state[ 3 + 3*4 ];state[ 3 + 3*4 ] = state[ 3 + 2*4 ];state[ 3 + 2*4 ] = state[ 3 + 1*4 ];state[ 3 + 1*4 ] = state[ 3 + 0*4 ];state[ 3 + 0*4 ] = temp;}void Cipher( unsigned char * block, unsigned char * expandedKey ) {unsigned char round = ROUNDS-1;XORBytes( block, expandedKey, 16 );expandedKey += BLOCKSIZE;do {SubBytes( block, 16 );ShiftRows( block );MixColumns( block );XORBytes( block, expandedKey, 16 );expandedKey += BLOCKSIZE;} while( --round );SubBytes( block, 16 );ShiftRows( block );XORBytes( block, expandedKey, 16 );}void aesEncInit(void){powTbl = block1;logTbl = tempbuf;CalcPowLog( powTbl, logTbl );sBox = block2;CalcSBox( sBox );expandedKey = block1;KeyExpansion( expandedKey );}void aesEncrypt( unsigned char * buffer, unsigned char * chainBlock ) {XORBytes( buffer, chainBlock, BLOCKSIZE );Cipher( buffer, expandedKey );CopyBytes( chainBlock, buffer, BLOCKSIZE );}#include <string.h>void AES_Test(void){unsigned char dat[16]="0123456789ABCDEF";unsigned char chainCipherBlock[16];unsigned char i;for(i=0;i<32;i++) AES_Key_Table[i]=i;//做运算之前先要设置好密钥,这里只是设置密钥的DEMO。
C语言利用OpenSSL实现AES加解密源代码
#include <stdlib.h>#include <stdio.h>#include <iostream>#include <string>#include <cassert>#include <Windows.h>#include <tchar.h>#include <conio.h>#include <openssl\aes.h>#include <openssl\rand.h>#include <openssl\evp.h>#pragma comment(lib,"libeay32.lib")#pragma comment(lib,"ssleay32.lib")#define BIG_TEST_SIZE 10240using namespace std;std::string EncodeAES( /*const std::string&*/char * strPassword, const std::string& strData){AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8 *//*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;for (unsigned int i = 0; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);unsigned char out[AES_BLOCK_SIZE];AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}return strRet;}std::string EncodeAES_little( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0)assert(false);return "";}unsigned char out[AES_BLOCK_SIZE];AES_encrypt((const unsigned char*)strData.c_str(), out, &aes_key);return std::string((const char*)out);}std::string EncodeAES_Big( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8 *//*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;unsigned int i = 0;std::string str16;unsigned char out[AES_BLOCK_SIZE];for (; i < strData.length() / AES_BLOCK_SIZE; i++){str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}str16 = strData.substr(i*AES_BLOCK_SIZE, strData.length() - i*AES_BLOCK_SIZE);AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);cout << "*************:" << str16 << endl;cout << "strRet.length() = " << strRet.length() << endl;return strRet;}std::string DecodeAES( /*const std::string&*/char * strPassword, const std::string& strData){AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0)assert(false);return "";}std::string strRet;for (unsigned int i = 0; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);unsigned char out[AES_BLOCK_SIZE];AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}return strRet;}std::string DecodeAES_little( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}unsigned char out[AES_BLOCK_SIZE];AES_decrypt((const unsigned char*)strData.c_str(), out, &aes_key);return std::string((const char*)out);}std::string DecodeAES_Big( /*const std::string&*/char * strPassword, const std::string& strData) {cout << "strData.length() = " << strData.length() << endl;AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;unsigned int i = 0;unsigned char out[AES_BLOCK_SIZE];for (; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}std::string str16 = strData.substr(i*AES_BLOCK_SIZE, strData.length() - i*AES_BLOCK_SIZE);AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);return strRet;}int main(int argc, _TCHAR* argv[]){system("cls");std::string buf;cout << "请输入待加密字符串:" << endl;getline(cin, buf);char userkey[AES_BLOCK_SIZE];//std::string userkey;RAND_pseudo_bytes((unsigned char*)userkey, sizeof userkey);std::string encrypt_data;std::string decrypt_data;cout << "输入的字符串长度与16比较大小:" << endl;if (buf.length() % 16 == 0){cout << "等于16 " << endl;encrypt_data = EncodeAES(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}else{if (buf.length()<16){cout << "小于16 " << endl;encrypt_data = EncodeAES_little(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES_little(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}else{cout << "大于16 " << endl;encrypt_data = EncodeAES_Big(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES_Big(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}}getchar();return 0;}。
基于C++的 AES加密和解密代码
///////////头文件-------begin-----------------------------------------#ifndef AES_H_#define AES_H_#include <string>using std::string;////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////class AES{public:AES();//AES(const char *cchKey);~AES();public://加密文件数据int EncryptFile(const char *cszpSourceFileName,const char *cszpPwdFileName,const char *cszpKey);//解密文件数据int DecryptFile(const char *cszpPwdFileName,const char *cszpResultFileName,const char *cszpKey);//加密字符串string EncryptText(const char *pszInText,const char *cszpKey);//解密字符串string DecryptText(const char *pszInText,const char *cszpKey);//备份数据int BackUp(const char *cszpData, const char *cszpKey, const char *cszpFileName);//恢复备份的数据string Recover(const char *cszpKey, const char *cszpFileName);private:int ByteToBit(char ch,char bit[8]);int BitToByte(char bit[8],char *ch);int Char8ToBit64(char ch[8],char bit[64]);int Bit64ToChar8(char bit[64],char ch[8]);int DES_MakeSubKeys(char key[64],char subKeys[16][48]);int DES_PC1_Transform(char key[64], char tempbts[56]);int DES_PC2_Transform(char key[56], char tempbts[48]);int DES_ROL(char data[56], int time);int DES_IP_Transform(char data[64]);int DES_IP_1_Transform(char data[64]);int DES_E_Transform(char data[48]);int DES_P_Transform(char data[32]);int DES_SBOX(char data[48]);int DES_XOR(char R[48], char L[48],int count);int DES_Swap(char left[32],char right[32]);int DES_EncryptBlock(char plainBlock[8], char subKeys[16][48], char cipherBlock[8]);int DES_DecryptBlock(char cipherBlock[8], char subKeys[16][48], char plainBlock[8]); };#endif /* AES_H_ *////////////头文件-------end-----------------------------------------//以下是实现文件#include "stdafx.h"#include <string>#include <stdio.h>#include <memory.h>#include <time.h>#include <stdlib.h>#include "AES.h"using namespace std;#define PLAIN_FILE_OPEN_ERROR -1#define KEY_FILE_OPEN_ERROR -2#define CIPHER_FILE_OPEN_ERROR -3#define OK 1#define PARAM_ERROR -1///////////////////////////////////////////////////////////////////////////*初始置换表IP*/int IP_Table[64] = { 57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7,56,48,40,32,24,16,8,0,58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,62,54,46,38,30,22,14,6};/*逆初始置换表IP^-1*/int IP_1_Table[64] = {39,7,47,15,55,23,63,31,38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25,32,0,40,8,48,16,56,24};/*扩充置换表E*/int E_Table[48] = {31, 0, 1, 2, 3, 4,3, 4, 5, 6, 7, 8,7, 8,9,10,11,12,11,12,13,14,15,16,15,16,17,18,19,20,19,20,21,22,23,24,23,24,25,26,27,28,27,28,29,30,31, 0};/*置换函数P*/int P_Table[32] = {15,6,19,20,28,11,27,16,0,14,22,25,4,17,30,9,1,7,23,13,31,26,2,8,18,12,29,5,21,10,3,24};/*S盒*/int S[8][4][16] =/*S1*/{{{14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7}, {0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8}, {4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0}, {15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13}}, /*S2*/{{15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10}, {3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5}, {0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15}, {13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9}}, /*S3*/{{10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8}, {13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1}, {13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7}, {1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12}}, /*S4*/{{7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15}, {13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9}, {10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4}, {3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14}}, /*S5*/{{2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9}, {14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6}, {4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14}, {11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3}}, /*S6*/{{12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11}, {10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8}, {9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6}, {4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13}}, /*S7*/{{4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1}, {13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6}, {1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2}, {6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12}}, /*S8*/{{13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7}, {1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2},{7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8},{2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11}}};/*置换选择1*/int PC_1[56] = {56,48,40,32,24,16,8,0,57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,60,52,44,36,28,20,12,4,27,19,11,3};/*置换选择2*/int PC_2[48] = {13,16,10,23,0,4,2,27,14,5,20,9,22,18,11,3,25,7,15,6,26,19,12,1,40,51,30,36,46,54,29,39,50,44,32,46,43,48,38,55,33,52,45,41,49,35,28,31};/*对左移次数的规定*/int MOVE_TIMES[16] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};//////////////////////////////////////////////////////////////////////////AES::AES(){}// AES::AES(const char *cchKey)// {//// }AES::~AES(){}/*字节转换成二进制*/int AES::ByteToBit(char ch, char bit[8]){if (bit == NULL){return PARAM_ERROR;}int cnt = 0;for(cnt = 0;cnt < 8; cnt++){*(bit+cnt) = (ch>>cnt)&1;}return 0;}/*二进制转换成字节*/int AES::BitToByte(char bit[8],char *ch){ if ((ch == NULL) || (bit == NULL)){return PARAM_ERROR;}int cnt = 0;for(cnt = 0;cnt < 8; cnt++){*ch |= *(bit + cnt)<<cnt;}return 0;}/*将长度为8的字符串转为二进制位串*/ int AES::Char8ToBit64(char ch[8],char bit[64]){ if ((ch == NULL) || (bit == NULL)){return PARAM_ERROR;}int cnt = 0;for(cnt = 0; cnt < 8; cnt++){ByteToBit(*(ch+cnt),bit+(cnt<<3));}return 0;}/*将二进制位串转为长度为8的字符串*/ int AES::Bit64ToChar8(char bit[64],char ch[8]){ if ((ch == NULL) || (bit == NULL)){return PARAM_ERROR;}int cnt = 0;memset(ch,0,8);for(cnt = 0; cnt < 8; cnt++){BitToByte(bit+(cnt<<3),ch+cnt);}return 0;}/*生成子密钥*/int AES::DES_MakeSubKeys(char key[64],char subKeys[16][48]){if ((key == NULL) || (subKeys == NULL)){return PARAM_ERROR;}char temp[56] = {0};int cnt = 0;if(DES_PC1_Transform(key,temp) < 0)/*PC1置换*/{return -2;}for(cnt = 0; cnt < 16; cnt++){/*16轮跌代,产生16个子密钥*/DES_ROL(temp,MOVE_TIMES[cnt]);/*循环左移*/DES_PC2_Transform(temp,subKeys[cnt]);/*PC2置换,产生子密钥*/ }return 0;}/*密钥置换1*/int AES::DES_PC1_Transform(char key[64], char tempbts[56]){if ((key == NULL) || (tempbts == NULL)){return PARAM_ERROR;}int cnt = 0;for(cnt = 0; cnt < 56; cnt++){tempbts[cnt] = key[PC_1[cnt]];}return 0;}/*密钥置换2*/int AES::DES_PC2_Transform(char key[56], char tempbts[48]){if ((key == NULL) || (tempbts == NULL)){return PARAM_ERROR;}int cnt = 0;for(cnt = 0; cnt < 48; cnt++){tempbts[cnt] = key[PC_2[cnt]];}return 0;}/*循环左移*/int AES::DES_ROL(char data[56], int time){ if ((data == NULL) || (time < 0)){return PARAM_ERROR;}char temp[56] = {0};/*保存将要循环移动到右边的位*/memcpy(temp,data,time);memcpy(temp+time,data+28,time);/*前28位移动*/memcpy(data,data+time,28-time);memcpy(data+28-time,temp,time);/*后28位移动*/memcpy(data+28,data+28+time,28-time);memcpy(data+56-time,temp+time,time);return 0;}/*IP置换*/int AES::DES_IP_Transform(char data[64]){ if (data == NULL){return PARAM_ERROR;}int cnt = 0;char temp[64] = {0};for(cnt = 0; cnt < 64; cnt++){temp[cnt] = data[IP_Table[cnt]];}memcpy(data,temp,64);return 0;}/*IP逆置换*/int AES::DES_IP_1_Transform(char data[64]){ if (data == NULL){return PARAM_ERROR;}int cnt = 0;char temp[64] = {0};for(cnt = 0; cnt < 64; cnt++){temp[cnt] = data[IP_1_Table[cnt]];}memcpy(data,temp,64);return 0;}/*扩展置换*/int AES::DES_E_Transform(char data[48]){ if (data == NULL){return PARAM_ERROR;}int cnt = 0;char temp[48] = {0};for(cnt = 0; cnt < 48; cnt++){temp[cnt] = data[E_Table[cnt]];}memcpy(data,temp,48);return 0;}/*P置换*/int AES::DES_P_Transform(char data[32]){ if (data == NULL){return PARAM_ERROR;}int cnt = 0;char temp[32] = {0};for(cnt = 0; cnt < 32; cnt++){temp[cnt] = data[P_Table[cnt]];}memcpy(data,temp,32);return 0;}/*异或*/int AES::DES_XOR(char R[48], char L[48] ,int count){ if ((R == NULL) || (L == NULL)){return PARAM_ERROR;}int cnt = 0;for(cnt = 0; cnt < count; cnt++){R[cnt] ^= L[cnt];}return 0;}/*S盒置换*/int AES::DES_SBOX(char data[48]){if(data == NULL){return PARAM_ERROR;}int cnt = 0;int line = 0;int row = 0;int output = 0;int cur1 = 0,cur2 = 0;for(cnt = 0; cnt < 8; cnt++){cur1 = cnt*6;cur2 = cnt<<2;/*计算在S盒中的行与列*/line = (data[cur1]<<1) + data[cur1+5];row = (data[cur1+1]<<3) + (data[cur1+2]<<2)+ (data[cur1+3]<<1) + data[cur1+4];output = S[cnt][line][row];/*化为2进制*/data[cur2] = (output&0X08)>>3;data[cur2+1] = (output&0X04)>>2;data[cur2+2] = (output&0X02)>>1;data[cur2+3] = output&0x01;}return 0;}/*交换*/int AES::DES_Swap(char left[32], char right[32]){if((left == NULL) || (right == NULL)){return PARAM_ERROR;}char temp[32] = {0};memcpy(temp,left,32);memcpy(left,right,32);memcpy(right,temp,32);return 0;}/*加密单个分组*/int AES::DES_EncryptBlock(char plainBlock[8], char subKeys[16][48], char cipherBlock[8]){if((plainBlock == NULL) || (subKeys == NULL) || (cipherBlock == NULL)){return PARAM_ERROR;}char plainBits[64] = {0};char copyRight[48] = {0};int cnt = 0;Char8ToBit64(plainBlock,plainBits);/*初始置换(IP置换)*/DES_IP_Transform(plainBits);/*16轮迭代*/for(cnt = 0; cnt < 16; cnt++){memcpy(copyRight,plainBits+32,32);/*将右半部分进行扩展置换,从32位扩展到48位*/DES_E_Transform(copyRight);/*将右半部分与子密钥进行异或操作*/DES_XOR(copyRight,subKeys[cnt],48);/*异或结果进入S盒,输出32位结果*/DES_SBOX(copyRight);/*P置换*/DES_P_Transform(copyRight);/*将明文左半部分与右半部分进行异或*/DES_XOR(plainBits,copyRight,32);if(cnt != 15){/*最终完成左右部的交换*/DES_Swap(plainBits,plainBits+32);}}/*逆初始置换(IP^1置换)*/DES_IP_1_Transform(plainBits);Bit64ToChar8(plainBits,cipherBlock);return 0;}/*解密单个分组*/int AES::DES_DecryptBlock(char cipherBlock[8], char subKeys[16][48],char plainBlock[8]){ if((plainBlock == NULL) || (subKeys == NULL) || (cipherBlock == NULL)){return PARAM_ERROR;}char cipherBits[64] = {0};char copyRight[48] = {0};int cnt = 0;Char8ToBit64(cipherBlock,cipherBits);/*初始置换(IP置换)*/DES_IP_Transform(cipherBits);/*16轮迭代*/for(cnt = 15; cnt >= 0; cnt--){memcpy(copyRight,cipherBits+32,32);/*将右半部分进行扩展置换,从32位扩展到48位*/DES_E_Transform(copyRight);/*将右半部分与子密钥进行异或操作*/DES_XOR(copyRight,subKeys[cnt],48);/*异或结果进入S盒,输出32位结果*/DES_SBOX(copyRight);/*P置换*/DES_P_Transform(copyRight);/*将明文左半部分与右半部分进行异或*/DES_XOR(cipherBits,copyRight,32);if(cnt != 0){/*最终完成左右部的交换*/DES_Swap(cipherBits,cipherBits+32);}}/*逆初始置换(IP^1置换)*/DES_IP_1_Transform(cipherBits);Bit64ToChar8(cipherBits,plainBlock);return 0;}/*功能:加密文件参数:[cszpSourceFileName]:原数据文件名[cszpPwdFileName]:密码文件名[cszpKey]:密码*/int AES::EncryptFile(const char *cszpSourceFileName,const char *cszpPwdFileName,const char *cszpKey){if ((cszpSourceFileName == NULL) ||(cszpPwdFileName == NULL) ||(cszpKey == NULL)){return PARAM_ERROR;}FILE *plain = NULL,*cipher = NULL;int count = 0;char plainBlock[8] = {0};char cipherBlock[8] = {0};char keyBlock[8] = {0};char bKey[64] = {0};char subKeys[16][48] = {0};if((plain = fopen(cszpSourceFileName,("rb"))) == NULL){ return PLAIN_FILE_OPEN_ERROR;}if((cipher = fopen(cszpPwdFileName,"wb")) == NULL){ return CIPHER_FILE_OPEN_ERROR;}/*设置密钥*/memcpy(keyBlock,cszpKey,8);/*将密钥转换为二进制流*/Char8ToBit64(keyBlock,bKey);/*生成子密钥*/DES_MakeSubKeys(bKey,subKeys);while(!feof(plain)){/*每次读8个字节,并返回成功读取的字节数*/if((count = fread(plainBlock,sizeof(char),8,plain)) == 8){DES_EncryptBlock(plainBlock,subKeys,cipherBlock);fwrite(cipherBlock,sizeof(char),8,cipher);}}if(count){/*填充*/memset(plainBlock + count,'\0',7 - count);/*最后一个字符保存包括最后一个字符在内的所填充的字符数量*/plainBlock[7] = 8 - count;DES_EncryptBlock(plainBlock,subKeys,cipherBlock);fwrite(cipherBlock,sizeof(char),8,cipher);}fclose(plain);plain = NULL;fclose(cipher);cipher = NULL;return OK;}/*功能:解密文件参数:[cszpPwdFileName]:密码文件名[cszpResultFileName]:解密后数据文件名[cszpKey]:密码*/int AES::DecryptFile(const char *cszpPwdFileName,const char *cszpResultFileName,const char *cszpKey){if ((cszpResultFileName == NULL) ||(cszpPwdFileName == NULL) ||(cszpKey == NULL)){return PARAM_ERROR;}FILE *plain = NULL, *cipher = NULL;int count,times = 0;long fileLen = 0;char plainBlock[8] = {0};char cipherBlock[8] = {0};char keyBlock[8] = {0};char bKey[64] = {0};char subKeys[16][48] = {0};if((cipher = fopen(cszpPwdFileName,"rb")) == NULL){ return CIPHER_FILE_OPEN_ERROR;}if((plain = fopen(cszpResultFileName,"wb")) == NULL){ return PLAIN_FILE_OPEN_ERROR;}/*设置密钥*/memcpy(keyBlock,cszpKey,8);/*将密钥转换为二进制流*/Char8ToBit64(keyBlock,bKey);/*生成子密钥*/DES_MakeSubKeys(bKey,subKeys);/*取文件长度*/fseek(cipher,0,SEEK_END);/*将文件指针置尾*/ fileLen = ftell(cipher); /*取文件指针当前位置*/ rewind(cipher); /*将文件指针重指向文件头*/while(1){/*密文的字节数一定是8的整数倍*/fread(cipherBlock,sizeof(char),8,cipher);DES_DecryptBlock(cipherBlock,subKeys,plainBlock);times += 8;if(times < fileLen){fwrite(plainBlock,sizeof(char),8,plain);}else{break;}}/*判断末尾是否被填充*/if(plainBlock[7] < 8){for(count = 8 - plainBlock[7]; count < 7; count++){if(plainBlock[count] != '\0'){break;}}}if(count == 7){/*有填充*/fwrite(plainBlock,sizeof(char),8 - plainBlock[7],plain);}else{/*无填充*/fwrite(plainBlock,sizeof(char),8,plain);}fclose(plain);plain = NULL;fclose(cipher);cipher = NULL;return OK;}/*功能:加密字符串参数:[pszInText]:要加密的字符串[cszpKey]:密码*/string AES::EncryptText(const char *pszInText,const char *cszpKey){if ((pszInText == NULL) ||(cszpKey == NULL)){return "";}int count = 0;char plainBlock[9] = {0};char cipherBlock[9] = {0};char keyBlock[9] = {0};char bKey[64] = {0};char subKeys[16][48] = {0};int nSize = strlen(pszInText);char *pchData = (char *)malloc(nSize + 1);if (pchData == NULL){return "";}memset(pchData, 0, nSize + 1);memcpy(pchData, pszInText, nSize);/*设置密钥*/memcpy(keyBlock,cszpKey,8);/*将密钥转换为二进制流*/Char8ToBit64(keyBlock,bKey);/*生成子密钥*/DES_MakeSubKeys(bKey,subKeys);string strData;char *pch = pchData;do{memset(plainBlock, 0, 9);memcpy(plainBlock, pch, 8);int nLen = strlen(plainBlock);if (nLen < 8){count = nLen;break;}else{DES_EncryptBlock(plainBlock,subKeys,cipherBlock);strData += cipherBlock;pch += 8;}} while (true);if(count){/*填充*/memset(plainBlock + count,'\0',7 - count);/*最后一个字符保存包括最后一个字符在内的所填充的字符数量*/ plainBlock[7] = 8 - count;DES_EncryptBlock(plainBlock,subKeys,cipherBlock);strData += cipherBlock;}return strData;}/*功能:解密字符串参数:[pszInText]:要解密的字符串,即加密后的字符串[cszpKey]:密码*/string AES::DecryptText(const char *pszInText,const char *cszpKey) {if ((pszInText == NULL) ||(cszpKey == NULL)){return "";}int count = 0;int times = 0;char plainBlock[9] = {0};char cipherBlock[9] = {0};char keyBlock[9] = {0};char bKey[64] = {0};char subKeys[16][48] = {0};int nSize = strlen(pszInText);char *pchData = (char *)malloc(nSize + 1);if (pchData == NULL){return "";}memset(pchData, 0, nSize + 1);memcpy(pchData, pszInText, nSize);/*设置密钥*/memcpy(keyBlock,cszpKey,8);/*将密钥转换为二进制流*/Char8ToBit64(keyBlock,bKey);/*生成子密钥*/DES_MakeSubKeys(bKey,subKeys);string strData;char *pch = pchData;while(true){/*密文的字节数一定是8的整数倍*/memset(cipherBlock, 0, 9);memset(plainBlock, 0, 9);memcpy(cipherBlock,pch,8);DES_DecryptBlock(cipherBlock,subKeys,plainBlock);times += 8;pch += 8;if(times < nSize){strData += plainBlock;}else{break;}}/*判断末尾是否被填充*/if(plainBlock[7] < 8){for(count = 8 - plainBlock[7]; count < 7; count++){if(plainBlock[count] != '\0'){break;}}}if(count == 7){/*有填充*/memset(cipherBlock, 0, 9);memcpy(cipherBlock,plainBlock,8 - plainBlock[7]);strData += cipherBlock;}else{/*无填充*/memset(cipherBlock, 0, 9);memcpy(cipherBlock,plainBlock,8);strData += cipherBlock;}return strData;}/*功能:备份数据至指定的文件中参数:【cszpData】:要备份的数据【cszpKey】:用于对数据加密的密码【cszpFileName】:保存数据的文件名返回值:成功:大于等于零(>=0)失败:小于零(<0)*/int AES::BackUp(const char *cszpData, const char *cszpKey, const char *cszpFileName) {if ((cszpData == NULL) ||(cszpKey == NULL) ||(cszpFileName == NULL)){return PARAM_ERROR;}string strData = EncryptText(cszpData, cszpKey);if (strData.empty()){return -2;}FILE *pfile = NULL;if((pfile = fopen(cszpFileName,"wb")) == NULL){return CIPHER_FILE_OPEN_ERROR;}fwrite(strData.c_str(), strlen(strData.c_str()), 1, pfile);fclose(pfile);pfile = NULL;return 0;}//恢复备份的数据/*功能:从指定的文件中恢复备份的数据参数:【cszpKey】:用于对数据解密的密码【cszpFileName】:保存数据的文件名返回值:成功:解密后的数据失败:空值*/string AES::Recover(const char *cszpKey, const char *cszpFileName) {if ((cszpKey == NULL) || (cszpFileName == NULL)){return "";}string strData;FILE *pfile = NULL;if ((pfile = fopen(cszpFileName, "rb")) == NULL){return "";}/*取文件长度*/fseek(pfile,0,SEEK_END);/*将文件指针置尾*/long fileLen = ftell(pfile); /*取文件指针当前位置*/rewind(pfile); /*将文件指针重指向文件头*/char *szpFileData = (char *)malloc(fileLen + 1);if (szpFileData == NULL){fclose(pfile);pfile = NULL;return "";}memset(szpFileData, 0, fileLen + 1);fread(szpFileData, fileLen, 1, pfile);fclose(pfile);strData = DecryptText(szpFileData, cszpKey);return strData;}。
C++的AES代码
AES加密算法 C++的AES代码(转)在VC7.1下编译调试成功,下面是源代码//AES.H#pragma onceclass AES{public:typedef enum ENUM_KeySize_{BIT128 = 0,BIT192,BIT256}ENUM_KEYSIZE;public:AES( ENUM_KEYSIZE keysize, BYTE *key );~AES(void);void Cipher( BYTE *input, BYTE *output ); void InvCipher( BYTE *input, BYTE *output );protected:BYTE *RotWord( BYTE *word );BYTE *SubWord( BYTE *word );void AddRoundKey(int round);void SubBytes();void InvSubBytes();void ShiftRows();void InvShiftRows();void MixColumns();void InvMixColumns();static BYTE gfmultby01(BYTE b){return b;}static BYTE gfmultby02(BYTE b){if (b < 0x80)return (BYTE)(int)(b <<1);elsereturn (BYTE)( (int)(b << 1) ^ (int)(0x1b) );}static BYTE gfmultby03(BYTE b){return (BYTE) ( (int)gfmultby02(b) ^ (int)b );}static BYTE gfmultby09(BYTE b){return (BYTE)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^(int)b );}static BYTE gfmultby0b(BYTE b){return (BYTE)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ (int)gfmultby02(b) ^(int)b );}static BYTE gfmultby0d(BYTE b){return (BYTE)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^ (int)gfmultby02(gfmultby02(b)) ^(int)(b) );}static BYTE gfmultby0e(BYTE b){return (BYTE)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^(int)gfmultby02(gfmultby02(b)) ^(int)gfmultby02(b) );}int Nb;int Nk;int Nr;BYTE *key;// the seed key. size will be 4 * keySize from ctor.typedef struct BYTE4_{BYTE w[4];}BYTE4;BYTE4 *w;LPBYTE State[4];/*private byte[,] iSbox; // inverse Substitution boxprivate byte[,] w; // key schedule array.private byte[,] Rcon; // Round constants.private byte[,] State; // State matrix*/};//AES.CPP#include "StdAfx.h"#include ".\aes.h"const BYTE Sbox[16][16] = { // populate the Sbox matrix/*0 1 2 3 4 5 6 7 8 9 a b c de f *//*0*/ {0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe,0xd7, 0xab, 0x76},/*1*/ {0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c,0xa4, 0x72, 0xc0},/*2*/ {0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71,0xd8, 0x31, 0x15},/*3*/ {0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb,/*4*/ {0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,0xe3, 0x2f, 0x84},/*5*/ {0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a,0x4c, 0x58, 0xcf},/*6*/ {0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50,0x3c, 0x9f, 0xa8},/*7*/ {0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10,0xff, 0xf3, 0xd2},/*8*/ {0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64,0x5d, 0x19, 0x73},/*9*/ {0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde,0x5e, 0x0b, 0xdb},/*a*/ {0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91,0x95, 0xe4, 0x79},/*b*/ {0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65,0x7a, 0xae, 0x08},/*c*/ {0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b,0xbd, 0x8b, 0x8a},/*d*/ {0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86,0xc1, 0x1d, 0x9e},/*e*/ {0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce,0x55, 0x28, 0xdf},/*f*/ {0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,0x54, 0xbb, 0x16}};const BYTE iSbox[16][16] = { // populate the iSbox matrix/*0 1 2 3 4 5 6 7 8 9 a b c de f *//*0*/ {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81,0xf3, 0xd7, 0xfb},/*1*/ {0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4,0xde, 0xe9, 0xcb},/*2*/ {0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42,/*3*/ {0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d,0x8b, 0xd1, 0x25},/*4*/ {0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,0x65, 0xb6, 0x92},/*5*/ {0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7,0x8d, 0x9d, 0x84},/*6*/ {0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8,0xb3, 0x45, 0x06},/*7*/ {0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01,0x13, 0x8a, 0x6b},/*8*/ {0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0,0xb4, 0xe6, 0x73},/*9*/ {0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c,0x75, 0xdf, 0x6e},/*a*/ {0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa,0x18, 0xbe, 0x1b},/*b*/ {0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78,0xcd, 0x5a, 0xf4},/*c*/ {0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27,0x80, 0xec, 0x5f},/*d*/ {0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93,0xc9, 0x9c, 0xef},/*e*/ {0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83,0x53, 0x99, 0x61},/*f*/ {0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,0x21, 0x0c, 0x7d} };const BYTE Rcon[11][4] = { {0x00, 0x00, 0x00, 0x00},{0x01, 0x00, 0x00, 0x00},{0x02, 0x00, 0x00, 0x00},{0x04, 0x00, 0x00, 0x00},{0x08, 0x00, 0x00, 0x00},{0x10, 0x00, 0x00, 0x00},{0x20, 0x00, 0x00, 0x00},{0x40, 0x00, 0x00, 0x00},{0x80, 0x00, 0x00, 0x00},{0x1b, 0x00, 0x00, 0x00},{0x36, 0x00, 0x00, 0x00} };BYTE *AES::RotWord( BYTE *word ){BYTE *result = new BYTE [4];result[0] = word[1];result[1] = word[2];result[2] = word[3];result[3] = word[0];delete[] word;return result;};BYTE *AES::SubWord( BYTE *word ){BYTE *result = new BYTE[4];result[0] = Sbox[ word[0] >> 4][ word[0] & 0x0f ]; result[1] = Sbox[ word[1] >> 4][ word[1] & 0x0f ]; result[2] = Sbox[ word[2] >> 4][ word[2] & 0x0f ]; result[3] = Sbox[ word[3] >> 4][ word[3] & 0x0f ];delete[] word;return result;}AES::AES( ENUM_KEYSIZE keysize, BYTE *key ){this->Nb = 4;switch( keysize ){case AES::BIT128:this->Nk = 4;this->Nr = 10;break;case AES::BIT192:this->Nk = 6;this->Nr = 12;break;case AES::BIT256:default:this->Nk = 8;this->Nr = 14;break;}this->key = new BYTE[this->Nk * 4];memcpy( this->key, key, this->Nk * 4 );this->w = new BYTE4[Nb * (Nr+1)];for( int row = 0; row < Nk; ++row ){w[row].w[0] = this->key[4*row];w[row].w[1] = this->key[4*row+1];w[row].w[2] = this->key[4*row+2];w[row].w[3] = this->key[4*row+3];}BYTE *temp = new BYTE[4];for( int row = Nk; row < Nb *(Nr + 1); ++ row ){temp[0] = this->w[row-1].w[0];temp[1] = this->w[row-1].w[1];temp[2] = this->w[row-1].w[2];temp[3] = this->w[row-1].w[3];if (row % Nk == 0){temp = SubWord(RotWord(temp));//this change two size temp[0] = (BYTE)( (int)temp[0] ^ (int)Rcon[row/Nk][0] ); temp[1] = (BYTE)( (int)temp[1] ^ (int)Rcon[row/Nk][1] ); temp[2] = (BYTE)( (int)temp[2] ^ (int)Rcon[row/Nk][2] ); temp[3] = (BYTE)( (int)temp[3] ^ (int)Rcon[row/Nk][3] );}else if ( Nk > 6 && (row % Nk == 4) ){temp = SubWord(temp);}// w[row] = w[row-Nk] xor tempthis->w[row].w[0] = (BYTE) ( (int)this->w[row-Nk].w[0] ^ (int)temp[0] ); this->w[row].w[1] = (BYTE) ( (int)this->w[row-Nk].w[1] ^ (int)temp[1] ); this->w[row].w[2] = (BYTE) ( (int)this->w[row-Nk].w[2] ^ (int)temp[2] ); this->w[row].w[3] = (BYTE) ( (int)this->w[row-Nk].w[3] ^ (int)temp[3] );}//loopdelete[] temp;for(int i=0;i<4;i++){this->State = NULL;}}AES::~AES(void){for(int i=0;i<4;i++){if (this->State != NULL){delete []this->State;}}}void AES::Cipher( BYTE *input, BYTE *output ){if (this->State[0] == NULL){for(int i=0;i<4;i++){this->State = new BYTE[this->Nb];}}for (int i = 0; i < (4 * Nb); ++i){this->State[i%4][i/4] = input;}for (int round = 1; round <= (Nr - 1); ++round) // main round loop{SubBytes();ShiftRows();MixColumns();AddRoundKey(round);} // main round loopSubBytes();ShiftRows();AddRoundKey(Nr);// output = statefor (int i = 0; i < (4 * Nb); ++i){output = this->State[i % 4][ i / 4];}}void AES::InvCipher( BYTE *input, BYTE *output ){if (this->State[0] == NULL){for(int i=0;i<4;i++){this->State = new BYTE[this->Nb];}}for (int i = 0; i < (4 * Nb); ++i){this->State[i % 4][ i / 4] = input;}for (int round = Nr-1; round >= 1; --round) // main round loop{InvShiftRows();InvSubBytes();AddRoundKey(round);InvMixColumns();} // end main round loop for InvCipherInvShiftRows();InvSubBytes();AddRoundKey(0);// output = statefor (int i = 0; i < (4 * Nb); ++i){output = this->State[i % 4][ i / 4];}}void AES::AddRoundKey( int round ){for (int r = 0; r < 4; ++r){for (int c = 0; c < 4; ++c){this->State[r][c] = (BYTE) ( (int)this->State[r][c] ^(int)w[(round*4)+c].w[r] );}}}void AES::SubBytes(){for (int r = 0; r < 4; ++r){for (int c = 0; c < 4; ++c){this->State[r][c] = Sbox[ (this->State[r][c] >> 4)][ (this->State[r][c] &0x0f) ];}}}void AES::InvSubBytes(){for (int r = 0; r < 4; ++r){for (int c = 0; c < 4; ++c){this->State[r][c] = iSbox[ (this->State[r][c] >> 4)][ (this->State[r][c] &0x0f) ];}}}void AES::ShiftRows(){BYTE4 temp[4];// byte[,] temp = new byte[4,4];for (int r = 0; r < 4; ++r) // copy State into temp[]{for (int c = 0; c < 4; ++c){temp[r].w[c] = this->State[r][c];// temp[r,c] = this.State[r,c];}}for (int r = 1; r < 4; ++r) // shift temp into State{for (int c = 0; c < 4; ++c){this->State[r][c] = temp[ r].w[ (c + r) % Nb ];}}} // ShiftRows()void AES::InvShiftRows(){BYTE4 temp[4];for (int r = 0; r < 4; ++r) // copy State into temp[]{for (int c = 0; c < 4; ++c){temp[r].w[c] = this->State[r][c];}}for (int r = 1; r < 4; ++r) // shift temp into State{for (int c = 0; c < 4; ++c){this->State[r][ (c + r) % Nb ] = temp[r].w[c];}}} // InvShiftRows()void AES::MixColumns(){BYTE4 temp[4];for (int r = 0; r < 4; ++r) // copy State into temp[]{for (int c = 0; c < 4; ++c){temp[r].w[c] = this->State[r][c];}}for (int c = 0; c < 4; ++c){this->State[0][c] = (BYTE) ( (int)gfmultby02(temp[0].w[c]) ^ (int)gfmultby03(temp[1].w[c]) ^this->State[1][c] = (BYTE) ( (int)gfmultby01(temp[0].w[c]) ^(int)gfmultby02(temp[1].w[c]) ^(int)gfmultby03(temp[2].w[c]) ^ (int)gfmultby01(temp[3].w[c]) );this->State[2][c] = (BYTE) ( (int)gfmultby01(temp[0].w[c]) ^(int)gfmultby01(temp[1].w[c]) ^(int)gfmultby02(temp[2].w[c]) ^ (int)gfmultby03(temp[3].w[c]) );this->State[3][c] = (BYTE) ( (int)gfmultby03(temp[0].w[c]) ^(int)gfmultby01(temp[1].w[c]) ^(int)gfmultby01(temp[2].w[c]) ^ (int)gfmultby02(temp[3].w[c]) );}} // MixColumnsvoid AES::InvMixColumns(){BYTE4 temp[4];for (int r = 0; r < 4; ++r) // copy State into temp[]{for (int c = 0; c < 4; ++c){temp[r].w[c] = this->State[r][c];}}for (int c = 0; c < 4; ++c){this->State[0][c] = (BYTE) ( (int)gfmultby0e(temp[0].w[c]) ^(int)gfmultby0b(temp[1].w[c]) ^(int)gfmultby0d(temp[2].w[c]) ^ (int)gfmultby09(temp[3].w[c]) );this->State[1][c] = (BYTE) ( (int)gfmultby09(temp[0].w[c]) ^(int)gfmultby0e(temp[1].w[c]) ^(int)gfmultby0b(temp[2].w[c]) ^ (int)gfmultby0d(temp[3].w[c]) );this->State[2][c] = (BYTE) ( (int)gfmultby0d(temp[0].w[c]) ^(int)gfmultby09(temp[1].w[c]) ^(int)gfmultby0e(temp[2].w[c]) ^ (int)gfmultby0b(temp[3].w[c]) );this->State[3][c] = (BYTE) ( (int)gfmultby0b(temp[0].w[c]) ^(int)gfmultby0d(temp[1].w[c]) ^} }。
C#对称加密和非对称加密(AES和RSA)
C#对称加密和⾮对称加密(AES和RSA)using System;using System.Collections.Generic;using System.IO;using System.Security.Cryptography;using System.Text;namespace 加密{class Program{static void Main(string[] args){//RSA//var dicKey = RSAHelper.GetKey();//Console.WriteLine($"{dicKey["PublicKey"]}\r\n{dicKey["PrivateKey"]}");//string strText = "aaabbbcc";//Console.WriteLine("要加密的字符串是:{0}", strText);//string str1 = RSAHelper.Encrypt(strText, dicKey["PublicKey"]);//Console.WriteLine("加密后的字符串:{0}", str1);//string str2 = RSAHelper.Decrypt(str1, dicKey["PrivateKey"]);//Console.WriteLine("解密后的字符串:{0}", str2);//AESstring password = "abcAE#$M&*987";Console.WriteLine($"原始密码为:{password} ");// AES的key⽀持128位,最⼤⽀持256位。
256位需要32个字节。
AES算法的C语言实现
( (uint32) MUL( 0x0E, y ) << 24 );
RT0[i] &= 0xFFFFFFFF;
RT1[i] = ROTR8( RT0[i] );
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B,
0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, uint32 Fra bibliotekT3[256];
/* reverse S-box & tables */
uint32 RSb[256];
uint32 RT0[256];
uint32 RT1[256];
uint32 RT2[256];
uint32 RT3[256];
/* round constants */
0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
x ^= y; y = ( y << 1 ) | ( y >> 7 );
x ^= y ^ 0x63;
FSb[i] = x;
RSb[x] = i;
}
/* generate the forward and reverse tables */
AES算法加密C语言完整程序
AES算法加密C语言完整程序#包括〈字符串。
"#包括AES。
"#包括“大众。
”#定义字节无符号字符#定义 bpoly OxlB / /!〈下 8 位(x 8X 1 X4+3+1),艮[I (x+4+x + 3 + x+x)。
#定义块16 / /!〈字节大小的块大小。
#定义 keybits 128 / /!〈使用 AES128。
#定义轮10 / /!轮数。
#定义keylength 16 / /!字节长度的键长度。
字节XDATA酒店[256 ]; //!〈工作区1。
字节数据块 2 [ 256 ]; //! < worksapce 2。
字节数据* powtbl; / /!〈最后位置指数表。
字节数据* logtbl; / /!对数查找表的最后位置。
字节数据* S盒;/ /! < S盒的最终位置。
字节数据* sboxinv; / / !〈逆S盒的最终位置。
字节数据* Expandedkey; / /!〈扩展键的最后位置。
CalcPowLog (* powtbl 无效字节,字节* logtbl){我二0字节数据;T = 1字节数据;做{/ /使用0x03作为幕和对数根。
powtbl [我]=T;logtbl [T]二我;++;/ / muliply T 3在 GF (2 " 8)。
T " = (t<<l) " (T & 0x80? bpoly: 0);} (t! = 1);循环属性确保i〈 255o powtbl [ 255 ] = powtbl [ 0 ]; / / 255 = - 0, 254 - 1, 虚空CalcSBox (字节* S盒)字节数据我,腐;字节数据的温度;字节的数据结果;/ /填写参赛方法[]o我=0;做{/反转 GF (2X8)。
如果(i = 0) {温度=powtbl [ 255 ] logtbl [我];其他{ }温度=0;}/GF (2)的仿射变换。
AES加密C语言实现代码
AES加密C语言实现代码以下是一个简单的C语言实现AES加密算法的代码:```c#include <stdio.h>#include <stdlib.h>#include <stdint.h>//定义AES加密的轮数#define NR 10//定义AES加密的扩展密钥长度#define Nk 4//定义AES加密的行数和列数#define Nb 4//定义AES加密的状态矩阵typedef uint8_t state_t[4][4];//定义AES加密的S盒变换表static const uint8_t sbox[256] =//S盒变换表};//定义AES加密的轮常量表static const uint8_t Rcon[11] =//轮常量表};//定义AES加密的密钥扩展变换函数void KeyExpansion(const uint8_t* key, uint8_t* expandedKey) uint32_t* ek = (uint32_t*)expandedKey;uint32_t temp;//密钥拷贝到扩展密钥中for (int i = 0; i < Nk; i++)ek[i] = (key[4 * i] << 24) , (key[4 * i + 1] << 16) ,(key[4 * i + 2] << 8) , (key[4 * i + 3]);}//扩展密钥生成for (int i = Nk; i < Nb * (NR + 1); i++)temp = ek[i - 1];if (i % Nk == 0)//对上一个密钥的字节进行循环左移1位temp = (temp >> 8) , ((temp & 0xFF) << 24);//对每个字节进行S盒变换temp = (sbox[temp >> 24] << 24) , (sbox[(temp >> 16) & 0xFF] << 16) , (sbox[(temp >> 8) & 0xFF] << 8) , sbox[temp & 0xFF];// 取轮常量Rcontemp = temp ^ (Rcon[i / Nk - 1] << 24);} else if (Nk > 6 && i % Nk == 4)//对每个字节进行S盒变换temp = (sbox[temp >> 24] << 24) , (sbox[(temp >> 16) & 0xFF] << 16) , (sbox[(temp >> 8) & 0xFF] << 8) , sbox[temp & 0xFF];}//生成下一个密钥ek[i] = ek[i - Nk] ^ temp;}//定义AES加密的字节替换函数void SubBytes(state_t* state)for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[i][j] = sbox[(*state)[i][j]];}}//定义AES加密的行移位函数void ShiftRows(state_t* state) uint8_t temp;//第2行循环左移1位temp = (*state)[1][0];(*state)[1][0] = (*state)[1][1]; (*state)[1][1] = (*state)[1][2]; (*state)[1][2] = (*state)[1][3]; (*state)[1][3] = temp;//第3行循环左移2位temp = (*state)[2][0];(*state)[2][0] = (*state)[2][2]; (*state)[2][2] = temp;temp = (*state)[2][1];(*state)[2][1] = (*state)[2][3]; (*state)[2][3] = temp;//第4行循环左移3位temp = (*state)[3][0];(*state)[3][0] = (*state)[3][3];(*state)[3][3] = (*state)[3][2];(*state)[3][2] = (*state)[3][1];(*state)[3][1] = temp;//定义AES加密的列混淆函数void MixColumns(state_t* state)uint8_t temp, tmp, tm;for (int i = 0; i < 4; i++)tmp = (*state)[i][0];tm = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;temp = (*state)[i][0] ^ (*state)[i][1];(*state)[i][0] ^= temp ^ tm;temp = (*state)[i][1] ^ (*state)[i][2];(*state)[i][1] ^= temp ^ tm;temp = (*state)[i][2] ^ (*state)[i][3];(*state)[i][2] ^= temp ^ tm;temp = (*state)[i][3] ^ tmp;(*state)[i][3] ^= temp ^ tm;}//定义AES加密的轮密钥加函数void AddRoundKey(state_t* state, const uint8_t* roundKey) for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[j][i] ^= roundKey[i * 4 + j];}}//定义AES加密函数void AES_Encrypt(const uint8_t* plainText, const uint8_t* key, uint8_t* cipherText)state_t* state = (state_t*)cipherText;uint8_t expandedKey[4 * Nb * (NR + 1)];//密钥扩展KeyExpansion(key, expandedKey);//初始化状态矩阵for (int i = 0; i < 4; i++)for (int j = 0; j < 4; j++)(*state)[j][i] = plainText[i * 4 + j];}}//第1轮密钥加AddRoundKey(state, key);//迭代执行第2至第10轮加密for (int round = 1; round < NR; round++) SubBytes(state);ShiftRows(state);MixColumns(state);AddRoundKey(state, expandedKey + round * 16); }//执行第11轮加密SubBytes(state);ShiftRows(state);AddRoundKey(state, expandedKey + NR * 16);int maiuint8_t plainText[16] =//明文数据};uint8_t key[16] =//密钥数据};uint8_t cipherText[16];AES_Encrypt(plainText, key, cipherText);。
基于C++的AES算法完整源码
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]);
void MixColumns(unsigned char state[][4]);//列混淆
void AddRoundKey(unsigned char state[][4], unsigned char k[][4]);//轮密钥加
void InvSubBytes(unsigned char state[][4]);//逆字节代替
AES::AES(unsigned char* key)
{
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*/
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*/
AES源代码
unsigned char keys[4][44];
int temp,i,j;
printf("请输入信息!\n");
for(i = 0;i <= 3;i ++)
for(j = 0;j <= 3;j ++){
scanf("%x",&temp);
B[j][i] = temp;
void invmixcolum(unsigned char input[][4]);
int jiami(unsigned char S_BOX[][16]);
int jiemi(unsigned char S_BOX[][16],unsigned char N_S_BOX[][16]);
//密钥生成
void keyexpansion(unsigned char S_BOX[][16],unsigned char keys[][44]){
unsigned char Rcon[11] = {0,1,2,4,8,16,32,64,128,27,54};
unsigned char past[4];
register int i,j;
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC,
0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
C语言利用OpenSSL实现AES加解密源代码
#include <stdlib.h>#include <stdio.h>#include <iostream>#include <string>#include <cassert>#include <Windows.h>#include <tchar.h>#include <conio.h>#include <openssl\aes.h>#include <openssl\rand.h>#include <openssl\evp.h>#pragma comment(lib,"libeay32.lib")#pragma comment(lib,"ssleay32.lib")#define BIG_TEST_SIZE 10240using namespace std;std::string EncodeAES( /*const std::string&*/char * strPassword, const std::string& strData){AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8 *//*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;for (unsigned int i = 0; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);unsigned char out[AES_BLOCK_SIZE];AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}return strRet;}std::string EncodeAES_little( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0)assert(false);return "";}unsigned char out[AES_BLOCK_SIZE];AES_encrypt((const unsigned char*)strData.c_str(), out, &aes_key);return std::string((const char*)out);}std::string EncodeAES_Big( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_encrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8 *//*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;unsigned int i = 0;std::string str16;unsigned char out[AES_BLOCK_SIZE];for (; i < strData.length() / AES_BLOCK_SIZE; i++){str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}str16 = strData.substr(i*AES_BLOCK_SIZE, strData.length() - i*AES_BLOCK_SIZE);AES_encrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);cout << "*************:" << str16 << endl;cout << "strRet.length() = " << strRet.length() << endl;return strRet;}std::string DecodeAES( /*const std::string&*/char * strPassword, const std::string& strData){AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0)assert(false);return "";}std::string strRet;for (unsigned int i = 0; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);unsigned char out[AES_BLOCK_SIZE];AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}return strRet;}std::string DecodeAES_little( /*const std::string&*/char * strPassword, const std::string& strData) {AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}unsigned char out[AES_BLOCK_SIZE];AES_decrypt((const unsigned char*)strData.c_str(), out, &aes_key);return std::string((const char*)out);}std::string DecodeAES_Big( /*const std::string&*/char * strPassword, const std::string& strData) {cout << "strData.length() = " << strData.length() << endl;AES_KEY aes_key;if (AES_set_decrypt_key((const unsigned char*)strPassword, AES_BLOCK_SIZE * 8/*strlen(strPassword)*8*/ /*strPassword.length() * 8*/, &aes_key) < 0){assert(false);return "";}std::string strRet;unsigned int i = 0;unsigned char out[AES_BLOCK_SIZE];for (; i < strData.length() / AES_BLOCK_SIZE; i++){std::string str16 = strData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);}std::string str16 = strData.substr(i*AES_BLOCK_SIZE, strData.length() - i*AES_BLOCK_SIZE);AES_decrypt((const unsigned char*)str16.c_str(), out, &aes_key);strRet += std::string((const char*)out, AES_BLOCK_SIZE);return strRet;}int main(int argc, _TCHAR* argv[]){system("cls");std::string buf;cout << "请输入待加密字符串:" << endl;getline(cin, buf);char userkey[AES_BLOCK_SIZE];//std::string userkey;RAND_pseudo_bytes((unsigned char*)userkey, sizeof userkey);std::string encrypt_data;std::string decrypt_data;cout << "输入的字符串长度与16比较大小:" << endl;if (buf.length() % 16 == 0){cout << "等于16 " << endl;encrypt_data = EncodeAES(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}else{if (buf.length()<16){cout << "小于16 " << endl;encrypt_data = EncodeAES_little(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES_little(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}else{cout << "大于16 " << endl;encrypt_data = EncodeAES_Big(userkey, buf);cout << "加密:" << endl;cout << encrypt_data << endl;decrypt_data = DecodeAES_Big(userkey, encrypt_data);cout << "解密:" << endl;cout << decrypt_data << endl;}}getchar();return 0;}。
AES加密算法源代码
//AES.h#define decrypt TRUE#define encrypt FALSE#define TYPE BOOLtypedef struct _AES{int Nb;int Nr;int Nk;unsigned long *Word;unsigned long *State;}AES;/*加密数据,这个函数和下面的InvCipher用于演示用的,只作了一次加密或解密。
要进行大数据量加解密只需对这两个函数稍作修改就可以了。
byte *input 明文byte *inSize 明文长byte *out 密文存放的地方byte *key 密钥keybyte *keySize 密钥长*/void Cipher(unsigned char* input,int inSize,unsigned char* out,unsigned char* key,int keySize);/*解密数据byte *input 密文int *inSize 密文长byte *out 明文存放的地方byte *key 密钥keyint *keySize 密钥长*/void InvCipher(unsigned char* input,int inSize,unsigned char* out, unsigned char* key,int keySize);/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长unsigned long 属性(标实类型) 返回AES结构指针*/AES *InitAES(AES *aes,int inSize,unsigned char* key,int keySize, TYPE type);/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(int inSize,unsigned char* key,int keySize, BOOL );/*加密时进行Nr轮运算AES * aes 运行时参数*/void CipherLoop(AES *aes);/*解密时进行Nr轮逆运算AES * aes 运行时参数*/void InvCipherLoop(AES *aes);/*释放AES结构和State和密钥库word*/void freeAES(AES *aes);//AES.cpp#include "stdafx.h"#include <windows.h>#include <stdio.h>#include "AES.h"unsigned char* SubWord(unsigned char* word);unsigned long* keyExpansion(unsigned char* key, int Nk, int Nr,int); /*加密数据byte *input 明文byte *inSize 明文长byte *out 密文存放的地方byte *key 密钥keybyte *keySize 密钥长*/void Cipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize){AES aes ;InitAES(&aes,inSize,key,keySize,encrypt);//while(...){memcpy(aes.State,input,inSize);CipherLoop(&aes);memcpy(out,aes.State,inSize);//}}/*解密数据byte *input 密文int *inSize 密文长byte *out 明文存放的地方byte *key 密钥keyint *keySize 密钥长*/void InvCipher(unsigned char* input, int inSize, unsigned char* out, unsigned char* key, int keySize){AES aes;InitAES(&aes,inSize,key,keySize,decrypt);memcpy(aes.State,input,inSize);InvCipherLoop(&aes);memcpy(aes.State,out,inSize);}/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(AES *aes,int inSize, unsigned char *key, int keySize, TYPEtype){int Nb = inSize >>2,Nk = keySize >>2,Nr = Nb < Nk ? Nk:Nb+6;aes->Nb = Nb;aes->Nk = Nk;aes->Nr = Nr;aes->Word = keyExpansion(key,Nb,Nr,Nk);aes->State = new unsigned long[Nb+3];if(type)aes->State += 3;return aes;}/*生成加密用的参数AES结构int inSize 块大小byte* 密钥int 密钥长返回AES结构指针*/AES *InitAES(int inSize, unsigned char* key, int keySize,unsigned long type){return InitAES(new AES(),inSize,key,keySize,type);}/**/void CipherLoop(AES *aes){unsigned char temp[4];unsigned long *word8 = aes->Word,*State = aes->State;int Nb = aes->Nb,Nr = aes->Nr;int r;for (r = 0; r < Nb; ++r){State[r] ^= word8[r];}for (int round =1; round <Nr; ++round) {word8 += Nb;/*假设Nb=4;---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | s7 |---------------------| s8 | s9 | sa | sb |---------------------| sc | sd | se | sf |---------------------| | | | |---------------------| | | | |---------------------| | | | |---------------------*/memcpy(State+Nb,State,12);/*Nb=4;---------------------| s0 | | | |---------------------| s4 | s5 | | |---------------------| s8 | s9 | sa | |---------------------| sc | sd | se | sf |---------------------| | s1 | s2 | s3 |---------------------| | | s6 | s7 |---------------------| | | | sb |---------------------*/for(r =0; r<Nb; r++){/*temp = {Sbox[s0],Sbox[s5],Sbox[sa],Sbox[sf]};*/temp[0] = Sbox[*((unsigned char*)State)];temp[1] = Sbox[*((unsigned char*)(State+1)+1)];temp[2] = Sbox[*((unsigned char*)(State+2)+2)];temp[3] = Sbox[*((unsigned char*)(State+3)+3)];*((unsigned char*)State) = Log_02[temp[0]] ^ Log_03[temp[1]] ^ temp[2] ^ temp[3];*((unsigned char*)State+1) = Log_02[temp[1]] ^ Log_03[temp[2]] ^ temp[3] ^ temp[0];*((unsigned char*)State+2) = Log_02[temp[2]] ^ Log_03[temp[3]] ^ temp[0] ^ temp[1];*((unsigned char*)State+3) = Log_02[temp[3]] ^ Log_03[temp[0]] ^ temp[1] ^ temp[2];*State ^= word8[r];State++;State -= Nb;}memcpy(State+Nb,State,12);word8 += Nb;for(r =0; r<Nb; r++){*((unsigned char*)State) = Sbox[*(unsigned char*)State];*((unsigned char*)State+1) = Sbox[*((unsigned char*)(State+1)+1)]; *((unsigned char*)State+2) = Sbox[*((unsigned char*)(State+2)+2)]; *((unsigned char*)State+3) = Sbox[*((unsigned char*)(State+3)+3)];*State ^= word8[r];State++;}}/*解密时进行Nr轮逆运算AES * aes 运行时参数*/void InvCipherLoop(AES *aes){unsigned long *Word = aes->Word,*State = aes->State;int Nb = aes->Nb,Nr = aes->Nr;unsigned char temp[4];int r =0;Word += Nb*Nr;for (r = 0; r < Nb; ++r)State[r] ^= Word[r];}State -= 3;for (int round = Nr-1; round > 0; --round) {/*假设Nb=4;---------------------| | | | |---------------------| | | | |---------------------| | | | |---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | s7 |---------------------| s8 | s9 | sa | sb |---------------------| sc | sd | se | sf |---------------------*/memcpy(State,State+Nb,12);/*Nb=4;---------------------| | | | s7 |---------------------| | | sa | sb |---------------------| | sd | se | sf |---------------------| s0 | s1 | s2 | s3 |---------------------| s4 | s5 | s6 | |---------------------| s8 | s9 | | |---------------------| sc | | | |---------------------*/Word -= Nb;State += Nb+2;for(r = Nb-1; r >= 0; r--){/*temp = {iSbox[s0],iSbox[sd],iSbox[sa],iSbox[s7]};*/temp[0] = iSbox[*(byte*)State];temp[1] = iSbox[*((byte*)(State-1)+1)];temp[2] = iSbox[*((byte*)(State-2)+2)];temp[3] = iSbox[*((byte*)(State-3)+3)];*(unsigned long*)temp ^= Word[r];*(unsigned char*)State = Log_0e[temp[0]] ^ Log_0b[temp[1]] ^Log_0d[temp[2]] ^ Log_09[temp[3]];*((unsigned char*)State+1) = Log_0e[temp[1]] ^ Log_0b[temp[2]] ^ Log_0d[temp[3]] ^ Log_09[temp[0]];*((unsigned char*)State+2) = Log_0e[temp[2]] ^ Log_0b[temp[3]] ^ Log_0d[temp[0]] ^ Log_09[temp[1]];*((unsigned char*)State+3) = Log_0e[temp[3]] ^ Log_0b[temp[0]] ^ Log_0d[temp[1]] ^ Log_09[temp[2]];State --;}State -= 2;}Word -= Nb;memcpy(State,State+Nb,12);State += Nb+2;for(r = Nb-1; r >= 0; r--){*(unsigned char*)State = iSbox[*(unsigned char*)State];*((unsigned char*)State+1) = iSbox[*((unsigned char*)(State-1)+1)]; *((unsigned char*)State+2) = iSbox[*((unsigned char*)(State-2)+2)]; *((unsigned char*)State+3) = iSbox[*((unsigned char*)(State-3)+3)];*State ^= Word[r];State --;}}/**--------------------------------------------*|k0|k1|k2|k3|k4|k5|k6|k7|k8|k9|.......|Nk*4|*--------------------------------------------*Nr轮密钥库*每个密钥列长度为Nb*---------------------*| k0 | k1 | k2 | k3 |*---------------------*| k4 | k5 | k6 | k7 |*---------------------*| k8 | k9 | ka | kb |*---------------------*| kc | kd | ke | kf |*---------------------*/unsigned long* keyExpansion(byte* key, int Nb, int Nr, int Nk){unsigned long *w =new unsigned long[Nb * (Nr+1)]; // 4 columns of bytes corresponds to a wordmemcpy(w,key,Nk<<2);unsigned long temp;for (int c = Nk; c < Nb * (Nr+1); ++c){//把上一轮的最后一行放入temptemp = w[c-1];//判断是不是每一轮密钥的第一行if (c % Nk == 0){//左旋8位temp = (temp<<8)|(temp>>24);//查Sbox表SubWord((byte*)&temp);temp ^= Rcon[c/Nk];}else if ( Nk > 6 && (c % Nk == 4) ){SubWord((byte*)&temp);}//w[c-Nk] 为上一轮密钥的第一行w[c] = w[c-Nk] ^ temp;}return w;}unsigned char* SubWord(unsigned char* word){word[0] = Sbox[ word[0] ];word[1] = Sbox[ word[1] ];word[2] = Sbox[ word[2] ];word[3] = Sbox[ word[3] ];return word;}/*释放AES结构和State和密钥库word */void freeAES(AES *aes){// for(int i=0;i<aes->Nb;i++)// {// printf("%d/n",i);// free(aes->State[i]);// free(aes->Word[i]);// }// printf("sdffd");}。
C语言实现数据加密算法
C语言实现数据加密算法数据加密是对敏感信息进行转换的过程,以保护数据的机密性和完整性。
C语言提供了强大的工具和库来实现各种加密算法,包括对称加密和非对称加密等。
对称加密算法是一种使用相同密钥加密和解密数据的方法。
其中最常见的算法是DES(Data Encryption Standard)和AES(Advanced Encryption Standard)。
下面是一个实现AES算法的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <openssl/aes.h>void encrypt_data(const unsigned char *data, size_t len, const unsigned char *key, unsigned char *encrypted_data) AES_KEY aes_key;AES_set_encrypt_key(key, 128, &aes_key);AES_encrypt(data, encrypted_data, &aes_key);void decrypt_data(const unsigned char *encrypted_data,size_t len, const unsigned char *key, unsigned char *data) AES_KEY aes_key;AES_set_decrypt_key(key, 128, &aes_key);AES_decrypt(encrypted_data, data, &aes_key);int maiunsigned char data[AES_BLOCK_SIZE] = "hello world!";size_t len = sizeof(data);unsigned char encrypted_data[AES_BLOCK_SIZE];encrypt_data(data, len, key, encrypted_data);unsigned char decrypted_data[AES_BLOCK_SIZE];decrypt_data(encrypted_data, len, key, decrypted_data);printf("Original Data: %s\n", data);printf("Encrypted Data: ");for (int i = 0; i < len; i++)printf("%02x ", encrypted_data[i]);}printf("\nDecrypted Data: %s\n", decrypted_data);return 0;```以上代码使用了OpenSSL库中的AES加密算法。
AES算法C源代码
#include<string.h>#include<stdio.h>#include<math.h>#include<conio.h>#include<stdlib.h>#define Nb 4 //分组大小为4int Nr=0; //轮数定义为0,实际值在程序中获取int Nk=0;//密钥长度定义为0,实际值在程序中获取int Nc = 128;//Nc为密钥长度,只能为128,192或256// in:存储明文的数组// out:存储密文的数组// state:存储中间状态的数组unsigned char in[16],out[32],state[4][4]; unsigned char RoundKey[240];//存储轮密钥的数组unsigned char Key[32];//存储输入的密钥int getSBoxInvert(int num){//逆S盒子int rsbox[256] ={ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7,0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6,0x7d };return rsbox[num];}int getSBoxValue(int num){//S盒子int sbox[256] = {//0 1 2 3 4 5 6 7 8 9 A B C D E F0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f,0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab,0x76,0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47,0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72,0xc0,0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7,0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31,0x15,0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2,0x75,0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };return sbox[num];}// The round constant word array, Rcon[i], contains the values given by// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)// Note that i starts at 1, not 0).int Rcon[255] = {0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb };//密钥扩展,生成Nb(Nr+1)的轮密钥,用于每轮的解密密钥void KeyExpansion(){int i,j;unsigned char temp[4],k;//第一个密钥为密钥本身for(i=0;i<Nk;i++){RoundKey[i*4]=Key[i*4];RoundKey[i*4+1]=Key[i*4+1];RoundKey[i*4+2]=Key[i*4+2];RoundKey[i*4+3]=Key[i*4+3];}// 其它密钥由第一个密钥进行扩展得到while (i < (Nb * (Nr+1))){for(j=0;j<4;j++){temp[j]=RoundKey[(i-1) * 4 + j];}if (i % Nk == 0){// 将四个字节进行左移一位,即[a0,a1,a2,a3]变为[a1,a2,a3,a0]{k = temp[0];temp[0] = temp[1];temp[1] = temp[2];temp[2] = temp[3];temp[3] = k;}// SubWord() is a function that takes a four-byte input word and// applies the S-box to each of the four bytes to produce an output word.{temp[0]=getSBoxValue(temp[0]); temp[1]=getSBoxValue(temp[1]);temp[2]=getSBoxValue(temp[2]); temp[3]=getSBoxValue(temp[3]); }temp[0] = temp[0] ^ Rcon[i/Nk];}else if (Nk > 6 && i % Nk == 4){{temp[0]=getSBoxValue(temp[0]); temp[1]=getSBoxValue(temp[1]); temp[2]=getSBoxValue(temp[2]); temp[3]=getSBoxValue(temp[3]); }}RoundKey[i*4+0] = RoundKey[(i-Nk)*4+0] ^ temp[0];RoundKey[i*4+1] = RoundKey[(i-Nk)*4+1] ^ temp[1];RoundKey[i*4+2] = RoundKey[(i-Nk)*4+2] ^ temp[2];RoundKey[i*4+3] = RoundKey[(i-Nk)*4+3] ^ temp[3];i++;}}// This function adds the round key to state. // The round key is added to the state by an XOR function.void AddRoundKey(int round){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[j][i] ^= RoundKey[round * Nb * 4 + i * Nb + j];}}}// The SubBytes Function Substitutes the values in the// state matrix with values in an S-box.void InvSubBytes(){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[i][j] = getSBoxInvert(state[i][j]);}}}// The ShiftRows() function shifts the rows in the state to the left.// Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted.void InvShiftRows(){unsigned char temp;// Rotate first row 1 columns to right temp=state[1][3];state[1][3]=state[1][2];state[1][2]=state[1][1];state[1][1]=state[1][0];state[1][0]=temp;// Rotate second row 2 columns to right temp=state[2][0];state[2][0]=state[2][2];state[2][2]=temp;temp=state[2][1];state[2][1]=state[2][3];state[2][3]=temp;// Rotate third row 3 columns to righttemp=state[3][0];state[3][0]=state[3][1];state[3][1]=state[3][2];state[3][2]=state[3][3];state[3][3]=temp;}// xtime is a macro that finds the product of {02} and the argument to xtime modulo {1b}#define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b))// Multiplty is a macro used to multiply numbersin the field GF(2^8)#define Multiply(x,y) (((y & 1) * x) ^ ((y>>1 & 1) * xtime(x)) ^ ((y>>2 & 1) * xtime(xtime(x))) ^ ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ ((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))))// MixColumns function mixes the columns of the state matrix.// The method used to multiply may be difficult to understand for the inexperienced.// Please use the references to gain more information.void InvMixColumns(){int i;unsigned char a,b,c,d;for(i=0;i<4;i++){a = state[0][i];b = state[1][i];c = state[2][i];d = state[3][i];state[0][i] = Multiply(a, 0x0e) ^Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);state[1][i] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);state[2][i] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);state[3][i] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);}}// InvCipher is the main function that decrypts the CipherText.void InvCipher(){int i,j,round=0;//Copy the input CipherText 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(Nr);// There will be Nr rounds.// The first Nr-1 rounds are identical.// These Nr-1 rounds are executed in the loop below.for(round=Nr-1;round>0;round--){InvShiftRows();InvSubBytes();AddRoundKey(round);InvMixColumns();}// The last round is given below.// The MixColumns function is not here in the last round.InvShiftRows();InvSubBytes();AddRoundKey(0);// The decryption 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];}}}// The SubBytes Function Substitutes the values in the// state matrix with values in an S-box.void SubBytes(){int i,j;for(i=0;i<4;i++){for(j=0;j<4;j++){state[i][j] = getSBoxValue(state[i][j]);}}}// The ShiftRows() function shifts the rows in the state to the left.// Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted.void ShiftRows(){unsigned char temp;// Rotate first row 1 columns to left temp=state[1][0];state[1][0]=state[1][1];state[1][1]=state[1][2];state[1][2]=state[1][3];state[1][3]=temp;// Rotate second row 2 columns to left temp=state[2][0];state[2][0]=state[2][2];state[2][2]=temp;temp=state[2][1];state[2][1]=state[2][3];state[2][3]=temp;// Rotate third row 3 columns to lefttemp=state[3][0];state[3][0]=state[3][3];state[3][3]=state[3][2];state[3][2]=state[3][1];state[3][1]=temp;}// xtime is a macro that finds the product of {02} and the argument to xtime modulo {1b}#define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b))// MixColumns function mixes the columns of the state matrixvoid MixColumns(){int i;unsigned char Tmp,Tm,t;for(i=0;i<4;i++){t=state[0][i];Tmp = state[0][i] ^ state[1][i] ^ state[2][i] ^ state[3][i] ;Tm = state[0][i] ^ state[1][i] ; Tm = xtime(Tm); state[0][i] ^= Tm ^ Tmp ;Tm = state[1][i] ^ state[2][i] ; Tm = xtime(Tm); state[1][i] ^= Tm ^ Tmp ;Tm = state[2][i] ^ state[3][i] ; Tm = xtime(Tm); state[2][i] ^= Tm ^ Tmp ;Tm = state[3][i] ^ t ; Tm = xtime(Tm); state[3][i] ^= Tm ^ Tmp ;}}// 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);}// 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];}}}char *encrypt(char *str, char *key){int i,j,Nl;double len;char *newstr;Nk = Nc / 32;Nr = Nk + 6;len= strlen(str);Nl = (int)ceil(len / 16);//printf("Nl:%d\n", Nl); newstr = (char *)malloc(Nl*32);memset(newstr,0,sizeof(newstr)); for(i=0;i<Nl;i++){for(j=0;j<Nk*4;j++){Key[j]=key[j];in[j]=str[i*16+j];}KeyExpansion();Cipher();memcpy(&newstr[i*32], out, 32); }return newstr;}char *decrypt(char *str, char *key) {int i,j,len,Nl;char *newstr;Nk = Nc / 32;Nr = Nk + 6;len= strlen(str);Nl = (int)ceil(len / 16);newstr = (char *)malloc(16*Nl);memset(newstr,0,sizeof(newstr)); for(i=0;i<Nl;i++){for(j=0;j<Nk*4;j++){Key[j]=key[j];in[j]=str[i*16+j];}KeyExpansion();InvCipher();memcpy(&newstr[i*32], out, 32); }return newstr;}int main(){ char str_1[128];//存明文char str_2[128];//存加密密钥char str_3[128];//存解密密钥char *str;char *str2;printf("请输入明文:\n");scanf("%s",str_1);printf("请输入加密密钥:\n");scanf("%s",str_2);str= encrypt(str_1, str_2);printf("进行加密后:%s\n\n", str);printf("请输入解密密钥:\n");scanf("%s",str_3);str2 = decrypt(str,str_3);printf("进行解密后:%s\n", str2); getch();return 0;}。
AES加密算法的C++实现过程
//AES.H#ifndef _AES_H_#define _AES_H_#include"stdafx.h"#define AES_KEY_ROW_NUMBER 4#define AES_KEY_COLUMN_NUMBER 4#define AES_ROUND_COUNT 10class AES : public Encryption{public:AES(void);AES(BYTE* key);virtual ~AES(void);void Encrypt(BYTE *, BYTE *,size_t);void Decrypt(BYTE *, BYTE *,size_t);private:BYTE swapbox[11][4][4];BYTE* Cipher(BYTE* input);BYTE* InvCipher(BYTE* input);BYTE* Cipher(void * input, size_t length);BYTE* InvCipher(void * input, size_t length);void KeyExpansion(BYTE* key, BYTE w[][4][AES_KEY_COLUMN_NUMBER]);BYTE FFmul(BYTE a, BYTE b);void SubBytes(BYTE state[][AES_KEY_COLUMN_NUMBER]);void ShiftRows(BYTE state[][AES_KEY_COLUMN_NUMBER]);void MixColumns(BYTE state[][AES_KEY_COLUMN_NUMBER]);void AddRoundKey(BYTE state[][AES_KEY_COLUMN_NUMBER], BYTE k[][AES_KEY_COLUMN_NUMBER]);void InvSubBytes(BYTE state[][AES_KEY_COLUMN_NUMBER]);void InvShiftRows(BYTE state[][AES_KEY_COLUMN_NUMBER]);void InvMixColumns(BYTE state[][AES_KEY_COLUMN_NUMBER]);};#endif// _AES_H_//Encryption.h#ifndef _ENCRYPTION_H_#define _ENCRYPTION_H_#include"stdafx.h"class Encryption{public:virtualvoid Encrypt(BYTE *, BYTE *,size_t) = 0;virtualvoid Decrypt(BYTE *, BYTE *,size_t) = 0;};#endif//EncryptionFactory.h#ifndef _ENCRYPTION_FACTORY_H_#define _ENCRYPTION_FACTORY_H_#include"Encryption.h"#include"stdafx.h"class EncryptionFactory{public:EncryptionFactory(void);virtual ~EncryptionFactory(void);static Encryption* getEncryption(int encryptionType,BYTE* key);private :static Encryption* encry;};#endif//AES.cpp#include"stdafx.h"#include"AES.h"#include<stdlib.h>#include<memory.h>//permuteboxstaticunsignedchar permutebox[] ={ /* 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*/};//inversepermutationboxstatic unsignedchar inversepermutationbox[]={ /* 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*/};AES::AES(void){}AES::AES(unsignedchar* key){KeyExpansion(key, swapbox);}AES::~AES(void){}/************************************************************************//* create a Encrypt method *//* param : data encrypt data *//* param :encryptArrayencryptArray *//* param :len encrypt data length *//* return : void *//************************************************************************/void AES::Encrypt(unsignedchar* data ,unsignedchar * encryptArray,size_tlen){memcpy(encryptArray,data,len);Cipher((void *)encryptArray,len);}/************************************************************************//* create a Decrypt method *//* param : data decrypt data *//* param :decryptArraydecryptArray *//* param :len decrypt data length *//* return : void *//************************************************************************/void AES::Decrypt(unsignedchar * data,unsignedchar * decryptArray,size_tlen){memcpy(decryptArray,data,len);InvCipher((void *)decryptArray,len);}/************************************************************************/ /* create a Cipher method only one time Encrypt */ /* param : input input encrypt data */ /* return : unsigned char * */ /************************************************************************/unsignedchar* AES::Cipher(unsignedchar* input){unsignedchar state[AES_KEY_ROW_NUMBER][AES_KEY_COLUMN_NUMBER];int i,r,c;for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER ;c++){state[r][c] = input[c*AES_KEY_COLUMN_NUMBER+r];}}AddRoundKey(state,swapbox[0]);for(i=1; i<=AES_ROUND_COUNT; i++){SubBytes(state);ShiftRows(state);if(i!=AES_ROUND_COUNT)MixColumns(state);AddRoundKey(state,swapbox[i]);}for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER ;c++){input[c*AES_KEY_COLUMN_NUMBER+r] = state[r][c];}}return input;}/************************************************************************/ /* create a InvCipher method only one time decrypt */ /* param : input input decrypt data */ /* return : unsigned char * */ /************************************************************************/ unsignedchar* AES::InvCipher(unsignedchar* input){unsignedchar state[AES_KEY_ROW_NUMBER][AES_KEY_COLUMN_NUMBER];int i,r,c;for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER ;c++){state[r][c] = input[c*AES_KEY_COLUMN_NUMBER+r];}}AddRoundKey(state, swapbox[10]);for(i=9; i>=0; i--){InvShiftRows(state);InvSubBytes(state);AddRoundKey(state, swapbox[i]);if(i){InvMixColumns(state);}}for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER ;c++){input[c*AES_KEY_COLUMN_NUMBER+r] = state[r][c];}}return input;}/************************************************************************/ /* Create a specified length of data encryption method */ /* param : input input data encryption */ /* param : length Input the length of the encrypted data */ /* return : unsigned char * */ /************************************************************************/ unsignedchar* AES::Cipher(void * input, size_t length){unsignedchar* in = (unsignedchar*) input;size_t i;if(!length){while(*(in+length++));in = (unsignedchar*) input;}for(i=0; i<length; i+=16){Cipher(in+i);}return (unsignedchar*)input;}/************************************************************************/ /* Create a specified length of InvCipher method */ /* param : input input data InvCipher *//* param : length Input the length of the InvCipher data *//* return : unsigned char * *//************************************************************************/ unsignedchar* AES::InvCipher(void * input, size_t length){unsignedchar* in = (unsignedchar*) input;size_t i;for(i=0; i<length; i+=16){InvCipher(in+i);}return (unsignedchar*)input;}/************************************************************************//*Create key method *//* param : key input data encryption key *//* param :swapbox Conversion of key array *//* return : void *//************************************************************************/void AES::KeyExpansion(unsignedchar* key, unsignedchar swapbox[][4][4]){int i,j,r,c;unsignedchar rc[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){swapbox[0][r][c] = key[r+c*AES_KEY_COLUMN_NUMBER];}}for(i=1; i<=10; i++){for(j=0; j<AES_KEY_COLUMN_NUMBER; j++){unsignedchar t[AES_KEY_ROW_NUMBER];for(r=0; r<AES_KEY_ROW_NUMBER; r++){t[r] = j ? swapbox[i][r][j-1] : swapbox[i-1][r][3];}if(j == 0){unsignedchar temp = t[0];for(r=0; r<AES_KEY_ROW_NUMBER-1; r++){t[r] = permutebox[t[(r+1)%AES_KEY_ROW_NUMBER]];}t[3] = permutebox[temp];t[0] ^= rc[i-1];}for(r=0; r<AES_KEY_ROW_NUMBER; r++){swapbox[i][r][j] = swapbox[i-1][r][j] ^ t[r];}}}}/************************************************************************/ /*Create mixed operation method ranks */ /* param : a row char */ /* param : b column char */ /* return : unsigned char */ /************************************************************************/unsignedchar AES::FFmul(unsignedchar a, unsignedchar b){unsignedchar bw[AES_KEY_ROW_NUMBER];unsignedchar res=0;int i;bw[0] = b;for(i=1; i<AES_KEY_ROW_NUMBER; i++){bw[i] = bw[i-1]<<1;if(bw[i-1]&0x80){bw[i]^=0x1b;}}for(i=0; i<AES_KEY_ROW_NUMBER; i++){if((a>>i)&0x01){res ^= bw[i];}}return res;}/************************************************************************/ /* Create bytes alternatives */ /* param : state[][] Byte array alternative */ /* return : void */ /************************************************************************/ void AES::SubBytes(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){int r,c;for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){state[r][c] = permutebox[state[r][c]];}}}/************************************************************************//* Create rows transform method */ /* param : state[][] line array alternative */ /* return : void */ /************************************************************************/ void AES::ShiftRows(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){unsignedchar t[AES_KEY_COLUMN_NUMBER];int r,c;for(r=1; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){t[c] = state[r][(c+r)%AES_KEY_COLUMN_NUMBER];}for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){state[r][c] = t[c];}}}/************************************************************************/ /* Create columns transform method */ /* param : state[][] columns array alternative */ /* return : void */ /************************************************************************/ void AES::MixColumns(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){unsignedchar t[AES_KEY_ROW_NUMBER];int r,c;for(c=0; c< AES_KEY_COLUMN_NUMBER; c++){for(r=0; r<AES_KEY_ROW_NUMBER; r++){t[r] = state[r][c];}for(r=0; r<AES_KEY_ROW_NUMBER; r++){state[r][c] = FFmul(0x02, t[r])^ FFmul(0x03, t[(r+1)%AES_KEY_COLUMN_NUMBER])^ FFmul(0x01, t[(r+2)%AES_KEY_COLUMN_NUMBER])^ FFmul(0x01, t[(r+3)%AES_KEY_COLUMN_NUMBER]);}}}/************************************************************************/ /*Create round keys plus transform method */ /* param : state[][] keys plus array alternative */ /* param : k[][] temp array alternative */ /* return : void */ /************************************************************************/ void AES::AddRoundKey(unsignedchar state[][AES_KEY_COLUMN_NUMBER],unsignedchar k[][AES_KEY_COLUMN_NUMBER]){int r,c;for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){for(r=0; r<AES_KEY_ROW_NUMBER; r++){state[r][c] ^= k[r][c];}}}/************************************************************************//* CreateInvSubBytes alternatives *//* param : state[][] InvSubBytes array alternative *//* return : void *//************************************************************************/void AES::InvSubBytes(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){int r,c;for(r=0; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){state[r][c] = inversepermutationbox[state[r][c]];}}}/************************************************************************//* CreateInvShiftRows transform method *//* param : state[][] InvShiftRows array alternative *//* return : void *//************************************************************************/void AES::InvShiftRows(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){unsignedchar t[AES_KEY_COLUMN_NUMBER];int r,c;for(r=1; r<AES_KEY_ROW_NUMBER; r++){for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){t[c] = state[r][(c-r+AES_KEY_COLUMN_NUMBER)%AES_KEY_COLUMN_NUMBER];}for(c=0; c<AES_KEY_COLUMN_NUMBER; c++){state[r][c] = t[c];}}}/************************************************************************//* CreateInvMixColumns transform method *//* param : state[][] InvMixColumns array alternative *//* return : void *//************************************************************************/ void AES::InvMixColumns(unsignedchar state[][AES_KEY_COLUMN_NUMBER]){unsignedchar t[AES_KEY_ROW_NUMBER];int r,c;for(c=0; c< AES_KEY_COLUMN_NUMBER; c++){for(r=0; r<AES_KEY_ROW_NUMBER; r++){t[r] = state[r][c];}for(r=0; r<AES_KEY_ROW_NUMBER; r++){state[r][c] = FFmul(0x0e, t[r])^ FFmul(0x0b, t[(r+1)%AES_KEY_ROW_NUMBER])^ FFmul(0x0d, t[(r+2)%AES_KEY_ROW_NUMBER])^ FFmul(0x09, t[(r+3)%AES_KEY_ROW_NUMBER]);}}}//TestEncryption.cpp用于测试主方法#include<stdio.h>#include<string.h>#include<istream>#include<vector>unsignedchar key[] ={'v' ,'b','c','d','f' ,'i','n','o','e' ,'w','t','i','q' ,'x','l','p',/*0xff, 0x7e, 0x15, 0x16,0x28, 0xae, 0xd2, 0xa6,0xab, 0xf7, 0x15, 0x88,0x09, 0xcf, 0x4f, 0x3c*/};int main(){Encryption* aes = EncryptionFactory::getEncryption(0,key);char* s="1234567891234567abcdefghijklmnop";unsignedchar * strEncrypt = aes->encrypt(s);puts((char*)strEncrypt);unsignedchar * strDecrypt = aes->decrypt((char*)strEncrypt);puts((char*)strDecrypt);getchar();return 0;}。