AES加密算法的C++实现过程
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_GCM加密算法
AES_GCM加密算法参考:相关概念解释:AES:设AES加密函数为E,则 C = E(K, P),其中P为明⽂,K为密钥,C为密⽂。
也就是说,把明⽂P和密钥K作为加密函数的参数输⼊,则加密函数E会输出密⽂C。
AES为分组密码,分组密码也就是把明⽂分成⼀组⼀组的,每组长度相等,每次加密⼀组数据,直到加密完整个明⽂。
在AES标准规范中,分组长度只能是128位,也就是说,每个分组为16个字节(每个字节8位)。
密钥的长度可以使⽤128位、192位或256位。
密钥的长度不同,推荐加密轮数也不同。
AES算法属于典型的对称算法。
AES算法具体步骤参考:CTR ( CounTeR 计数器模式):计数模式(CTR模式)加密是对⼀系列输⼊(称为计数)进⾏加密,产⽣⼀系列的输出块,输出块与明⽂异或得到密⽂。
对于最后的数据块,可能是长u位的局部数据块,这u位就将⽤于异或操作,⽽剩下的b-u位将被丢弃(b表⽰块的长度)。
CTR解密类似。
这⼀系列的计数必须互不相同的。
IV:Initialization Vector, 初始化向量,⼀般是加密过程初始化产⽣的随机向量。
加密和解密过程需要同⼀组IV。
MAC:密⽂的收发双发需要提前共享⼀个秘钥。
密⽂发送者将密⽂的MAC值随密⽂⼀起发送,密⽂接收者通过共享秘钥计算收到密⽂的MAC值,这样就可以对收到的密⽂做完整性校验。
当篡改者篡改密⽂后,没有共享秘钥,就⽆法计算出篡改后的密⽂的MAC值。
在AES_GCM算法中,MAC⼜称作TAGGCM:GCM ( Galois/Counter Mode) 指的是该对称加密采⽤Counter模式,并带有GMAC消息认证码。
下图的解释:Ek使⽤秘钥k对输⼊做对称加密运算XOR异或运算Mh将输⼊与秘钥h在有限域GF(2^128)上做乘法算法详细步骤:AES_GCM 算法加密过程:1. AES加密输⼊: IV值 (⼀般随机产⽣) 密钥 明⽂附加消息Aad: 附加消息不是明⽂内容, 作AES加密时作为输⼊,对产⽣MAC值产⽣影响.可有可⽆2. 算法对明⽂进⾏分段,并通过输⼊的密钥分别与分段的明⽂作AES对称加密运算, ⽣成密⽂3. 对上⼀步的每段加密结果, 以及附加消息进⾏Mh运算. 得到的结果⽣成MAC值作为验证信息, 再GCM算法中⼜叫做TAG值AES_GCM 算法解密过程:1. AES解密输⼊: IV值 (与加密过程所⽤的IV值相同) 密钥 密⽂附加消息Aad: 与加密过程所⽤的IAad值相同 加密产⽣的TAG2. 分别⽤密钥, 对每段密⽂进⾏解密3. 对Aad和解密结果进程Mh计算⽣成TAG, 和加密产⽣的TAG进⾏⽐对可以验证加/解密过程的完整性。
AES加密算法的实现及应用
AES加密算法的实现及应用AES(Advanced Encryption Standard)是一种对称加密算法,旨在替代DES(Data Encryption Standard)以及3DES(Triple Data Encryption Standard)进行数据加密。
AES算法安全可靠,广泛应用于各种场景中,包括网络通信、存储安全和移动设备等领域。
AES算法的实现可以分为以下几个步骤:1.密钥扩展:根据密钥的长度,生成一系列的轮密钥。
AES算法支持128比特、192比特及256比特三种密钥长度。
2.轮密钥加:将密钥和输入数据按位进行异或运算。
3. 字节替代:通过S盒(Substitution box)对输入数据的每一个字节进行替换,S盒是一个16×16字节的固定查找表,根据输入字节的值查找替换的字节。
4.行移位:对输入数据的每一行进行循环移位操作,第一行不变,第二行循环左移一位,第三行循环左移两位,第四行循环左移三位。
5.列混淆:将输入数据的每一列进行混淆,用固定的矩阵乘法运算。
6.轮密钥加:将轮密钥和上一步得到的结果按位进行异或运算。
以上步骤将重复进行,除了最后一轮以外,每一轮都包含字节替代、行移位、列混淆和轮密钥加四个步骤。
AES算法的应用非常广泛1. 数据通信:AES算法可以用于保护数据的机密性,确保在数据传输过程中不被未经授权的人员所获取。
AES算法被广泛应用于网络通信中,例如TLS(Transport Layer Security)和IPsec(Internet Protocol Security)协议中。
2.文件加密:AES算法可以对文件进行加密,以保护文件的机密性。
例如,一些加密软件可以使用AES算法对敏感文件进行加密,在文件传输或存储过程中保护文件的安全性。
3.移动设备安全:由于移动设备的广泛使用,需求越来越高的数据安全性。
AES算法可以用于对移动设备中的敏感数据进行加密,以防止非法访问和数据泄露。
C#实现AES加密--解密
C#实现AES加密--解密///<summary>/// AES 加密///</summary>///<param name="str">明⽂(待加密)</param>///<param name="key">密⽂</param>///<returns></returns>public static string AesEncrypt(string str, string key){if (string.IsNullOrEmpty(str)) return null;Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged {Key = Encoding.UTF8.GetBytes(key),Mode = System.Security.Cryptography.CipherMode.ECB,Padding = System.Security.Cryptography.PaddingMode.PKCS7};System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Convert.ToBase64String(resultArray, 0, resultArray.Length);}///<summary>/// AES 解密///</summary>///<param name="str">明⽂(待解密)</param>///<param name="key">密⽂</param>///<returns></returns>public static string AesDecrypt(string str, string key){if (string.IsNullOrEmpty(str)) return null;Byte[] toEncryptArray = Convert.FromBase64String(str);System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged {Key = Encoding.UTF8.GetBytes(key),Mode = System.Security.Cryptography.CipherMode.ECB,Padding = System.Security.Cryptography.PaddingMode.PKCS7};System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);return Encoding.UTF8.GetString(resultArray);}欢迎评论。
AES加密算法(C++实现,附源码)
AES加密算法(C++实现,附源码)原创作品,转载请注明出⾃博客地址:本⽂地址:快毕业了,最后⼀个课程设计,《基于Windows Socket的安全通信》,内容就是基于AES加密的SOCKET通信,貌似挺简单,不过要⽤VC++6.0开发,C++我确实没有任何代码经验,虽然不是强制性,但由于机房⾥各种纠结,只能⽤它了(⽤Java没有挑战性,封装得太好了...也算熟悉下VC++吧)先搞定AES算法,基本变换包括SubBytes(字节替代)、ShiftRows(⾏移位)、MixColumns(列混淆)、AddRoundKey(轮密钥加)其算法⼀般描述为明⽂及密钥的组织排列⽅式ByteSubstitution(字节替代)⾮线性的字节替代,单独处理每个字节:求该字节在有限域GF(28)上的乘法逆,"0"被映射为⾃⾝,即对于α∈GF(28),求β∈GF(28),使得α·β=β·α=1mod(x 8+x 4+x 2+x+1)。
对上⼀步求得的乘法逆作仿射变换y i =x i + x (i+4)mod8 + x (i+6)mod8 + x (i+7)mod8 + c i(其中c i 是6310即011000112的第i位),⽤矩阵表⽰为本来打算把求乘法逆和仿射变换算法敲上去,最后还是放弃了...直接打置换表12345678910111213141516171819unsigned char sBox[] ={ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, /*0*/0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, /*1*/0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, /*2*/ 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, /*3*/ 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, /*4*/0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, /*5*/0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, /*6*/0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, /*7*/0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, /*8*/ 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, /*9*/ 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, /*a*/0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, /*b*/0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, /*c*/0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, /*d*/ 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, /*e*/ 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 /*f*/};下⾯是逆置换表,解密时使⽤12345678*********unsigned char invsBox[256] ={ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb, /*0*/ 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb, /*1*/ 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e, /*2*/0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25, /*3*/0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92, /*4*/0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84, /*5*/ 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06, /*6*/ 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b, /*7*/ 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73, /*8*/0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e, /*9*/0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b, /*a*/ 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4, /*b*/14 15 16 17 18 19 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*/ };这⾥遇到问题了,本来⽤纯c初始化数组很正常,封装成类以后发现不能初始化,不管是声明、构造函数都⽆法初始化,百歌⾕度了⼀通后没有任何答案,⽆奈只能在构造函数中声明⼀个局部变量数组并初始化,然后⽤memcpy,(成员变量名为Sbox/InvSbox,局部变量名sBox/invsBox)12 3 4 5 6 7 8 9 10 11void AES::SubBytes(unsigned char state[][4]) {int r,c;for(r=0; r<4; r++){for(c=0; c<4; c++){state[r][c] = Sbox[state[r][c]];}}}ShiftRows(⾏移位变换)⾏移位变换完成基于⾏的循环位移操作,变换⽅法:即⾏移位变换作⽤于⾏上,第0⾏不变,第1⾏循环左移1个字节,第2⾏循环左移2个字节,第3⾏循环左移3个字节。
AESECB加密算法C语言代码实现
AESECB加密算法C语言代码实现要实现AESECB加密算法的C语言代码,需要先了解AES算法的基本原理和步骤。
以下是一个使用C语言实现AESECB加密算法的示例代码:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <openssl/aes.h>//定义密钥长度#define KEY_LENGTH 16//ECBAES加密函数void AESEncrypt_ECB(const unsigned char* plainText, int plainTextLength, unsigned char* cipherText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置加密密码AES_set_encrypt_key(key, KEY_LENGTH * 8, &aesKey);//加密数据AES_ecb_encrypt(plainText, cipherText, &aesKey, AES_ENCRYPT);//ECBAES解密函数void AESDecrypt_ECB(const unsigned char* cipherText, int cipherTextLength, unsigned char* plainText,const unsigned char* key)//创建AES密钥结构体AES_KEY aesKey;//设置解密密码AES_set_decrypt_key(key, KEY_LENGTH * 8, &aesKey);//解密数据AES_ecb_encrypt(cipherText, plainText, &aesKey, AES_DECRYPT);int mai//指定原始明文和密钥unsigned char plainText[] = "Hello, World!";unsigned char key[] = "secretkey";//计算明文长度int plainTextLength = strlen(plainText);//计算加密后的数据长度int cipherTextLength = ((plainTextLength / KEY_LENGTH) + 1) * KEY_LENGTH;//分配加密后数据的内存unsigned char* cipherText = (unsignedchar*)malloc(cipherTextLength);//加密数据AESEncrypt_ECB(plainText, plainTextLength, cipherText, key);//打印加密后的结果printf("Cipher text: ");for (int i = 0; i < cipherTextLength; i++)printf("%02x ", cipherText[i]);}printf("\n");//分配解密后数据的内存unsigned char* decryptedText = (unsignedchar*)malloc(cipherTextLength);//解密数据AESDecrypt_ECB(cipherText, cipherTextLength, decryptedText, key);//打印解密后的结果printf("Decrypted text: %s\n", decryptedText);//释放已分配的内存free(cipherText);free(decryptedText);return 0;```上述代码使用了OpenSSL库提供的AES函数来实现ECB模式的AES加密和解密操作。
AES加密(java和C#)
AES加密(java和C#)需求:Java和C#进⾏数据交互,互相采⽤AES/CBC/PKCS5Padding进⾏加解密Java加密和解密的代码如下:/*** 加密 1.构造密钥⽣成器 2.根据 ecnodeRules 规则初始化密钥⽣成器 3.产⽣密钥 4.创建和初始化密码器 5.内容加密 6.返回字符串 * @param encodeRules 密钥规则,类似于密钥* @param content 待加密内容* @return*/public static String AESEncode(String encodeRules, String content) {// 初始化向量,必须 16 位String ivStr = "AESCBCPKCS5Paddi";try {// 1.构造密钥⽣成器,指定为 AES 算法,不区分⼤⼩写KeyGenerator keygen = KeyGenerator.getInstance("AES");// 新增下⾯两⾏,处理 Linux 操作系统下随机数⽣成不⼀致的问题SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");secureRandom.setSeed(encodeRules.getBytes());keygen.init(128, secureRandom);// 3.产⽣原始对称密钥SecretKey original_key = keygen.generateKey();// 4.获得原始对称密钥的字节数组byte[] raw = original_key.getEncoded();System.out.println(Base64.getEncoder().encodeToString(raw));// 5.根据字节数组⽣成 AES 密钥SecretKey key = new SecretKeySpec(raw, "AES");// 6.根据指定算法 AES ⾃成密码器Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 7.初始化密码器,第⼀个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第⼆个参数为使⽤的 KEY//// 指定⼀个初始化向量 (Initialization vector,IV), IV 必须是 16 位cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivStr.getBytes("UTF-8")));// 8.获取加密内容的字节数组(这⾥要设置为 utf-8)不然内容中如果有中⽂和英⽂混合中⽂就会解密为乱码byte[] byte_encode = content.getBytes("utf-8");// 9.根据密码器的初始化⽅式--加密:将数据加密byte[] byte_AES = cipher.doFinal(byte_encode);// 10.将加密后的数据转换为字符串// 这⾥⽤ Base64Encoder 中会找不到包// 解决办法:// 在项⽬的 Build path 中先移除 JRE System Library,再添加库 JRE System// Library,重新编译后就⼀切正常了。
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。
iOS开发之Objective-c的AES加密和解密算法的实现
iOS开发之Objective-c的AES加密和解密算法的实现⾼级加密标准(Advanced Encryption Standard,AES),⼜称Rijndael加密法。
以下实现代码中分别为NSData和NSString增加了⼀个Category。
使⽤时直接调⽤即可。
需要注意的是,AES并不能作为HASH算法,加密并解密后的结果,并不⼀定与原⽂相同,使⽤时请注意进⾏结果验算。
例如解密原⽂的长度,格式规则等。
NG实例原⽂:170987350密码:170Objective-c的AES加密和解密算法的具体实现代码如下: 1.拓展NSData,增加AES256加密⽅法////NSData+AES256.h//#import <Foundation/Foundation.h>#import <CommonCrypto/CommonDigest.h>#import <CommonCrypto/CommonCryptor.h>@interface (AES256)-( *) aes256_encrypt:( *)key;-( *) aes256_decrypt:( *)key;@end////NSData+AES256.m//#import "NSData+AES256.h"@implementation (AES256)- ( *)aes256_encrypt:( *)key //加密{char keyPtr[kCCKeySizeAES256+1];bzero(keyPtr, (keyPtr));[key getCString:keyPtr maxLength:(keyPtr) encoding:NSUTF8StringEncoding];NSUInteger dataLength = [self length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void *buffer = (bufferSize);size_t numBytesEncrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding | kCCOptionECBMode,keyPtr, kCCBlockSizeAES128,NULL,[self bytes], dataLength,buffer, bufferSize,&numBytesEncrypted);if (cryptStatus == kCCSuccess) {return [ dataWithBytesNoCopy:buffer length:numBytesEncrypted];}(buffer);return nil;}- ( *)aes256_decrypt:( *)key //解密{char keyPtr[kCCKeySizeAES256+1];bzero(keyPtr, (keyPtr));[key getCString:keyPtr maxLength:(keyPtr) encoding:NSUTF8StringEncoding];NSUInteger dataLength = [self length];size_t bufferSize = dataLength + kCCBlockSizeAES128;void *buffer = (bufferSize);size_t numBytesDecrypted = 0;CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding | kCCOptionECBMode,keyPtr, kCCBlockSizeAES128,NULL,[self bytes], dataLength,buffer, bufferSize,&numBytesDecrypted);if (cryptStatus == kCCSuccess) {return [ dataWithBytesNoCopy:buffer length:numBytesDecrypted];}(buffer);return nil;}@end@end2.拓展NSString,增加AES256加密⽅法,需要导⼊NSData+AES256.h ////NSString +AES256.h//#import <Foundation/Foundation.h>#import <CommonCrypto/CommonDigest.h>#import <CommonCrypto/CommonCryptor.h>#import "NSData+AES256.h"@interface (AES256)-( *) aes256_encrypt:( *)key;-( *) aes256_decrypt:( *)key;@end////NSString +AES256.h//@implementation (AES256)-( *) aes256_encrypt:( *)key{const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];*data = [ dataWithBytes:cstr length:self.length];//对数据进⾏加密*result = [data aes256_encrypt:key];//转换为2进制字符串if (result && result.length > 0) {Byte *datas = (Byte*)[result bytes];*output = [ stringWithCapacity:result.length * 2];for(int i = 0; i < result.length; i++){[output appendFormat:@"%02x", datas[i]];}return output;}return nil;}-( *) aes256_decrypt:( *)key{//转换为2进制Data*data = [ dataWithCapacity:self.length / 2];unsigned char whole_byte;char byte_chars[3] = {'\0','\0','\0'};int i;for (i=0; i < [self length] / 2; i++) {byte_chars[0] = [self characterAtIndex:i*2];byte_chars[1] = [self characterAtIndex:i*2+1];whole_byte = (byte_chars, NULL, 16);[data appendBytes:&whole_byte length:1];}//对数据进⾏解密* result = [data aes256_decrypt:key];if (result && result.length > 0) {return [[ alloc] initWithData:result encoding:NSUTF8StringEncoding]autorelease]; }return nil;}@end。
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-256算法C语言实现
AES-256算法C语⾔实现AES是美国确⽴的⼀种⾼级数据加密算法标准,它是⼀种对数据分组进⾏对称加密的算法,这种算法是由⽐利时的Joan Daemen和Vincent Rijmen设计的,因此⼜被称为RIJNDAE算法.根据密钥长度的不同,AES标准⼜区分为AES-128, AES-192, AES-256三种,密钥越长,对每⼀数据分组进⾏的加密步骤(加密轮数)也越多.AES-128/192/256分别对应10/12/14轮加密步骤. AES-256对应的密钥长度为256bits, 其每⼀数据分组都需要进⾏14轮的加密运算,(若将初始轮+结束轮视为完整⼀轮, 总共就是14轮).AES规定每⼀数据分组长度均为128bits.由于加密过程中每⼀轮都需要⼀个密钥,因此⾸先需要从输⼊密钥(也称为种⼦密码)扩展出Nr(10/12/14)个密钥,总共是Nr+1个密钥.AES加密步骤:密钥扩展(每⼀轮加密都需要⼀个密钥) -> 初始轮加密(⽤输⼊密钥 AddRoundKey) ->重复轮加密(⽤扩展密钥SubBytes/ShiftRow/MixColumns/AddRoundKey) -> 结束轮加密(⽤扩展密钥 SubBytes/ShiftRows/AddRoundKey)AES解密步骤:密钥扩展(每⼀轮解密都需要⼀个密钥) -> 初始轮解密(⽤输⼊密钥AddRoundKey) ->重复轮解密(⽤扩展密钥InvShiftRows/InvSubBytes/AddRoundKey/InvMixColumns) -> 结束轮解密(⽤扩展密钥InvShiftRows/InvSubBytes/AddRoundKey)加/解密步骤由以下基本算⼦组成AddRoundKey: 加植密钥SubBytes: 字节代换InvSubBytes: 字节逆代换ShiftRow: ⾏移位InvShiftRow: ⾏逆移位MixColumn: 列混合InvMixColumn: 列逆混合AES的加密和解密互为逆过程, 因此两个过程其实可以相互交换.对⽂件进⾏AES加密, 就是将⽂件划分成多个数据分组,每个为128bit,然后对每⼀个数据分组进⾏如上所叙的加密处理.参考资料:Advanced Encryption Standard (AES) (FIPS PUB 197) (November 26, 2001)Advanced Encryption Standard by Example (by Adam Berent)下⾯是具体的AES-256加密解/密程序和注释.程序内也包含了AES-128/AES-192相应的测试数据,如有兴趣可以选择不同标准进⾏测试.为了演⽰⽅便,程序只进⾏了⼀个分组的加密和解密运算.并在密钥扩展和每轮计算后都将结果打印出来,以⽅便与AES标准⽂件中的例⼦进⾏⽐较.在Linux环境下编译和执⾏:gcc -o aes256 aes256.c./aes256/*---------------------------------------------------------------------This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License version 2 aspublished by the Free Software Foundation.A test for AES encryption (RIJNDAEL symmetric key encryption algorithm).Reference:1. Advanced Encryption Standard (AES) (FIPS PUB 197)2. Advanced Encryption Standard by Example (by Adam Berent)Note:1. Standard and parameters.Key Size Block Size Number of Rounds(Nk words) (Nb words) (Nr)AES-128 4 4 10AES-192 6 4 12AES-256 8 4 14Midas Zhoumidaszhou@https:///widora/wegi----------------------------------------------------------------------*/#include <stdio.h>#include <stdint.h>#include <string.h>/* S_BOX S盒 */static const uint8_t sbox[256] = {/* 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, 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 };/* Reverse S_BOX 反向S盒 */static const uint8_t rsbox[256] = {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 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, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 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, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D };/* Galois Field Multiplication E-table GF乘法E表 */static const uint8_t Etab[256]= {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01};/* Galois Field Multiplication L-table GF乘法L表 */static const uint8_t Ltab[256]= {/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */0x0, 0x0, 0x19, 0x01, 0x32, 0x02, 0x1A, 0xC6, 0x4B, 0xC7, 0x1B, 0x68, 0x33, 0xEE, 0xDF, 0x03, // 00x64, 0x04, 0xE0, 0x0E, 0x34, 0x8D, 0x81, 0xEF, 0x4C, 0x71, 0x08, 0xC8, 0xF8, 0x69, 0x1C, 0xC1, // 10x7D, 0xC2, 0x1D, 0xB5, 0xF9, 0xB9, 0x27, 0x6A, 0x4D, 0xE4, 0xA6, 0x72, 0x9A, 0xC9, 0x09, 0x78, // 20x65, 0x2F, 0x8A, 0x05, 0x21, 0x0F, 0xE1, 0x24, 0x12, 0xF0, 0x82, 0x45, 0x35, 0x93, 0xDA, 0x8E, // 30x96, 0x8F, 0xDB, 0xBD, 0x36, 0xD0, 0xCE, 0x94, 0x13, 0x5C, 0xD2, 0xF1, 0x40, 0x46, 0x83, 0x38, // 40x66, 0xDD, 0xFD, 0x30, 0xBF, 0x06, 0x8B, 0x62, 0xB3, 0x25, 0xE2, 0x98, 0x22, 0x88, 0x91, 0x10, // 50x7E, 0x6E, 0x48, 0xC3, 0xA3, 0xB6, 0x1E, 0x42, 0x3A, 0x6B, 0x28, 0x54, 0xFA, 0x85, 0x3D, 0xBA, // 60x2B, 0x79, 0x0A, 0x15, 0x9B, 0x9F, 0x5E, 0xCA, 0x4E, 0xD4, 0xAC, 0xE5, 0xF3, 0x73, 0xA7, 0x57, // 70xAF, 0x58, 0xA8, 0x50, 0xF4, 0xEA, 0xD6, 0x74, 0x4F, 0xAE, 0xE9, 0xD5, 0xE7, 0xE6, 0xAD, 0xE8, // 80x2C, 0xD7, 0x75, 0x7A, 0xEB, 0x16, 0x0B, 0xF5, 0x59, 0xCB, 0x5F, 0xB0, 0x9C, 0xA9, 0x51, 0xA0, // 90x7F, 0x0C, 0xF6, 0x6F, 0x17, 0xC4, 0x49, 0xEC, 0xD8, 0x43, 0x1F, 0x2D, 0xA4, 0x76, 0x7B, 0xB7, // A0xCC, 0xBB, 0x3E, 0x5A, 0xFB, 0x60, 0xB1, 0x86, 0x3B, 0x52, 0xA1, 0x6C, 0xAA, 0x55, 0x29, 0x9D, // B0x97, 0xB2, 0x87, 0x90, 0x61, 0xBE, 0xDC, 0xFC, 0xBC, 0x95, 0xCF, 0xCD, 0x37, 0x3F, 0x5B, 0xD1, // C0x53, 0x39, 0x84, 0x3C, 0x41, 0xA2, 0x6D, 0x47, 0x14, 0x2A, 0x9E, 0x5D, 0x56, 0xF2, 0xD3, 0xAB, // D0x44, 0x11, 0x92, 0xD9, 0x23, 0x20, 0x2E, 0x89, 0xB4, 0x7C, 0xB8, 0x26, 0x77, 0x99, 0xE3, 0xA5, // E0x67, 0x4A, 0xED, 0xDE, 0xC5, 0x31, 0xFE, 0x18, 0x0D, 0x63, 0x8C, 0x80, 0xC0, 0xF7, 0x70, 0x07 // F};/* RCON 表 */static const uint32_t Rcon[15]= {0x01000000,0x02000000,0x04000000,0x08000000,0x10000000,0x20000000,0x40000000,0x80000000,0x1B000000,0x36000000,0x6C000000,0xD8000000,0xAB000000,0x4D000000,0x9A000000};/* Functions */void print_state(const uint8_t *s); /* 打印分组数据 */int aes_ShiftRows(uint8_t *state); /* ⾏移位 */int aes_InvShiftRows(uint8_t *state); /* ⾏逆移位 */int aes_ExpRoundKeys(uint8_t Nr, uint8_t Nk, const uint8_t *inkey, uint32_t *keywords); /* 密钥扩展 */int aes_AddRoundKey(uint8_t Nr, uint8_t Nk, uint8_t round, uint8_t *state, const uint32_t *keywords); /* 加植密钥 */ int aes_EncryptState(uint8_t Nr, uint8_t Nk, uint32_t *keywords, uint8_t *state); /* 分组加密 */int aes_DecryptState(uint8_t Nr, uint8_t Nk, uint32_t *keywords, uint8_t *state); /* 分组解密 *//*==============MAIN===============*/int main(void){int i,k;const uint8_t Nb=4; /* 分组长度 Block size in words, 4/4/4 for AES-128/192/256 */uint8_t Nk; /* 密钥长度 column number, as of 4xNk, 4/6/8 for AES-128/192/256 */uint8_t Nr; /* 加密轮数 Number of rounds, 10/12/14 for AES-128/192/256 */uint8_t state[4*4]; /* 分组数据 State array, data in row sequence! */uint64_t ns; /* 总分组数 Total number of states *//* 待加密数据 */const uint8_t input_msg[]= {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff};/* AES-128/192/256 对应的密钥长度,加密轮数, 输⼊密钥 */#if 0 /* TEST data --- AES-128 */Nk=4;Nr=10;const uint8_t inkey[4*4]= { /* Nb*Nk */0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};#endif#if 0 /* TEST data --- AES-192 */Nk=6;Nr=12;const uint8_t inkey[4*6]= { /* Nb*Nk */0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17};#endif#if 1 /* TEST data --- AES-256 */Nk=8;Nr=14;const uint8_t inkey[4*8]= { /* Nb*Nk */0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f};#endif/* 密钥扩展测试数据------TEST: For Key expansion */#if 0Nk=4;Nr=10;const uint8_t inkey[4*4]= /* Nb*Nk */{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; #endif#if 0Nk=6;Nr=12;const uint8_t inkey[4*6]= /* Nb*Nk */{ 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b,0x80, 0x90, 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };#endif#if 0Nk=8;const uint8_t inkey[4*8]= /* Nb*Nk */{ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };#endifuint32_t keywords[Nb*(Nr+1)]; /* ⽤于存放扩展密钥,总共Nr+1把密钥 Nb==4, All expended keys, as of words in a column: 0xb0b1b2b3 *//* 从输⼊密钥产⽣Nk+1个轮密,每轮需要⼀个密钥 Generate round keys */aes_ExpRoundKeys(Nr, Nk, inkey, keywords);/* 数据分组数量,这⾥我们只设定为1组. Cal. total states *///ns=(strlen(input_msg)+15)/16;ns=1;/* 如果是多个分组,那么分别对每个分组进⾏加密,i=0 ~ ns-1 */i=0; /* i=0 ~ ns-1 *//* 将待加密数据放⼊到数据分组state[]中,注意:state[]中数据按column顺序存放! */bzero(state,16);for(k=0; k<16; k++)state[(k%4)*4+k/4]=input_msg[i*16+k];/* 加密数据分组 Encrypt each state */aes_EncryptState(Nr, Nk, keywords, state);/* 打印加密后的分组数据 */printf("***********************************\n");printf("******* Finish Encryption *******\n");printf("***********************************\n");print_state(state);/* 解密数据分组 Decrypt state */aes_DecryptState(Nr, Nk, keywords, state);//printf("Finish decrypt message, Round Nr=%d, KeySize Nk=%d, States ns=%llu.\n", Nr, Nk, ns);/* 打印解密后的分组数据 */printf("***********************************\n");printf("******* Finish Decryption *******\n");printf("***********************************\n");print_state(state);return 0;}/* 打印分组数据 Print state */void print_state(const uint8_t *s){int i,j;for(i=0; i<4; i++) {for(j=0; j<4; j++) {printf("%02x",s[i*4+j]);//printf("'%c'",s[i*4+j]); /* A control key MAY erase previous chars on screen! */printf(" ");}printf("\n");}printf("\n");}/*------------------------------⾏移位Shift operation of the state.Return:0 OK<0 Fails-------------------------------*/int aes_ShiftRows(uint8_t *state){int j,k;uint8_t tmp;if(state==NULL)return -1;for(k=0; k<4; k++) {/* each row shift k times */for(j=0; j<k; j++) {tmp=*(state+4*k); /* save the first byte *///memcpy(state+4*k, state+4*k+1, 3);memmove(state+4*k, state+4*k+1, 3);*(state+4*k+3)=tmp; /* set the last byte */}}return 0;}/*------------------------------⾏逆移位Shift operation of the state.@state[4*4]Return:0 OK<0 Fails-------------------------------*/int aes_InvShiftRows(uint8_t *state){int j,k;uint8_t tmp;if(state==NULL)return -1;for(k=0; k<4; k++) {/* each row shift k times */for(j=0; j<k; j++) {tmp=*(state+4*k+3); /* save the last byte */memmove(state+4*k+1, state+4*k, 3);*(state+4*k)=tmp; /* set the first byte */}}return 0;}/*-------------------------------------------------------------加植密钥Add round key to the state.@Nr: Number of rounds, 10/12/14 for AES-128/192/256 @Nk: Key size, in words.@round: Current round number.@state: Pointer to state.@keywords[Nb*(Nr+1)]: All round keys, in words.int aes_AddRoundKey(uint8_t Nr, uint8_t Nk, uint8_t round, uint8_t *state, const uint32_t *keywords){int k;if(state==NULL || keywords==NULL)return -1;for(k=0; k<4*4; k++)state[k] = ( keywords[round*4+k%4]>>((3-(k>>2))<<3) &0xFF )^state[k];return 0;}/*----------------------------------------------------------------------------------------------------------密钥扩展从输⼊密钥(也称为种⼦密码)扩展出Nr(10/12/14)个密钥,总共是Nr+1个密钥Generate round keys.@Nr: Number of rounds, 10/12/14 for AES-128/192/256@Nk: Key size, in words.@inkey[4*Nk]: Original key, 4*Nk bytes, arranged row by row.@keywords[Nb*(Nr+1)]: Output keys, in words. Nb*(Nr+1)one keywords(32 bytes) as one column of key_bytes(4 bytes)Note:1. The caller MUST ensure enough mem space of input params.Return:0 Ok<0 Fails---------------------------------------------------------------------------------------------------------------*/int aes_ExpRoundKeys(uint8_t Nr, uint8_t Nk, const uint8_t *inkey, uint32_t *keywords){int i;const int Nb=4;uint32_t temp;if(inkey==NULL || keywords==NULL)return -1;/* Re_arrange inkey to keywords, convert 4x8bytes each row_data to a 32bytes keyword, as a complex column_data. */ for( i=0; i<Nk; i++ ) {keywords[i]=(inkey[4*i]<<24)+(inkey[4*i+1]<<16)+(inkey[4*i+2]<<8)+inkey[4*i+3];}/* Expend round keys */for(i=Nk; i<Nb*(Nr+1); i++) {temp=keywords[i-1];if( i%Nk==0 ) {/* RotWord */temp=( temp<<8 )+( temp>>24 );/* Subword */temp=(sbox[temp>>24]<<24) +(sbox[(temp>>16)&0xFF]<<16) +(sbox[(temp>>8)&0xFF]<<8)+sbox[temp&0xFF];/* temp=SubWord(RotWord(temp)) XOR Rcon[i/Nk-1] */temp=temp ^ Rcon[i/Nk-1];}else if (Nk>6 && i%Nk==4 ) {/* Subword */temp=(sbox[temp>>24]<<24) +(sbox[(temp>>16)&0xFF]<<16) +(sbox[(temp>>8)&0xFF]<<8)+sbox[temp&0xFF];}/* Get keywords[i] */}/* Print all keys */for(i=0; i<Nb*(Nr+1); i++)printf("keywords[%d]=0x%08X\n", i, keywords[i]);return 0;}/*----------------------------------------------------------------------数据分组加密Encrypt state.@Nr: Number of rounds, 10/12/14 for AES-128/192/256@Nk: Key length, in words.@keywordss[Nb*(Nr+1)]: All round keys, in words.@state[4*4]: The state block.Note:1. The caller MUST ensure enough mem space of input params.Return:0 Ok<0 Fails------------------------------------------------------------------------*/int aes_EncryptState(uint8_t Nr, uint8_t Nk, uint32_t *keywords, uint8_t *state) {int i,k;uint8_t round;uint8_t mc[4]; /* Temp. var */if(keywords==NULL || state==NULL)return -1;/* 1. AddRoundKey: 加植密钥 */printf(" --- Add Round_key ---\n");aes_AddRoundKey(Nr, Nk, 0, state, keywords);print_state(state);/* 循环Nr-1轮加密运算 Run Nr round functions */for( round=1; round<Nr; round++) { /* Nr *//* 2. SubBytes: 字节代换 Substitue State Bytes with SBOX */printf(" --- SubBytes() Round:%d ---\n",round);for(k=0; k<16; k++)state[k]=sbox[state[k]];print_state(state);/* 3. ShiftRow: ⾏移位 Shift State Rows */printf(" --- ShiftRows() Round:%d ---\n",round);aes_ShiftRows(state);print_state(state);/* 4. MixColumn: 列混合 Mix State Cloumns *//* Galois Field Multiplication, Multi_Matrix:2 3 1 11 2 3 11 12 33 1 1 2Note:1. Any number multiplied by 1 is equal to the number itself.2. Any number multiplied by 0 is 0!*/printf(" --- MixColumn() Round:%d ---\n",round);mc[0]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[2])%0xFF] )^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[3])%0xFF] )^state[i+8]^state[i+12];mc[1]= state[i]^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[2])%0xFF] )^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[3])%0xFF] )^state[i+12];mc[2]= state[i]^state[i+4]^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[2])%0xFF] )^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[3])%0xFF] );mc[3]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[3])%0xFF] )^state[i+4]^state[i+8]^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[2])%0xFF] );state[i+0]=mc[0];state[i+4]=mc[1];state[i+8]=mc[2];state[i+12]=mc[3];}print_state(state);/* 5. AddRoundKey: 加植密钥 Add State with Round Key */printf(" --- Add Round_key ---\n");aes_AddRoundKey(Nr, Nk, round, state, keywords);print_state(state);} /* END Nr rounds *//* 6. SubBytes: 字节代换 Substitue State Bytes with SBOX */printf(" --- SubBytes() Round:%d ---\n",round);for(k=0; k<16; k++)state[k]=sbox[state[k]];print_state(state);/* 7. ShiftRow: ⾏移位 Shift State Rows */printf(" --- ShiftRows() Round:%d ---\n",round);aes_ShiftRows(state);print_state(state);/* 8. AddRoundKey: 加植密钥 Add State with Round Key */printf(" --- Add Round_key ---\n");aes_AddRoundKey(Nr, Nk, round, state, keywords);print_state(state);return 0;}/*----------------------------------------------------------------------Decrypt the state.@Nr: Number of rounds, 10/12/14 for AES-128/192/256@Nk: Key length, in words.@keywordss[Nb*(Nr+1)]: All round keys, in words.@state[4*4]: The state block.Note:1. The caller MUST ensure enough mem space of input params.Return:0 Ok<0 Fails------------------------------------------------------------------------*/int aes_DecryptState(uint8_t Nr, uint8_t Nk, uint32_t *keywords, uint8_t *state)int i,k;uint8_t round;uint8_t mc[4]; /* Temp. var */if(keywords==NULL || state==NULL)return -1;/* 1. AddRoundKey: 加植密钥 Add round key */printf(" --- Add Round_key ---\n");aes_AddRoundKey(Nr, Nk, Nr, state, keywords); /* From Nr_th round */ print_state(state);/* 循环Nr-1轮加密运算 Run Nr round functions */for( round=Nr-1; round>0; round--) { /* round [Nr-1 1] *//* 2. InvShiftRow: ⾏逆移位 InvShift State Rows */printf(" --- InvShiftRows() Round:%d ---\n",Nr-round);aes_InvShiftRows(state);print_state(state);/* 3. InvSubBytes: 字节逆代换 InvSubstitue State Bytes with R_SBOX */printf(" --- (Inv)SubBytes() Round:%d ---\n",Nr-round);for(k=0; k<16; k++)state[k]=rsbox[state[k]];print_state(state);/* 4. AddRoundKey: 加植密钥 Add State with Round Key */printf(" --- Add Round_key Round:%d ---\n", Nr-round);aes_AddRoundKey(Nr, Nk, round, state, keywords);print_state(state);/* 5. InvMixColumn: 列逆混合 Inverse Mix State Cloumns *//* Galois Field Multiplication, Multi_Matrix:0x0E 0x0B 0x0D 0x090x09 0x0E 0x0B 0x0D0x0D 0x09 0x0E 0x0B0x0B 0x0D 0x09 0x0ENote:1. Any number multiplied by 1 is equal to the number itself.2. Any number multiplied by 0 is 0!*/printf(" --- InvMixColumn() Round:%d ---\n",Nr-round);for(i=0; i<4; i++) { /* i as column index */mc[0]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[0x0E])%0xFF] )^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[0x0B])%0xFF] )^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[0x0D])%0xFF] )^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[0x09])%0xFF] );mc[1]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[0x09])%0xFF] )^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[0x0E])%0xFF] )^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[0x0B])%0xFF] )^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[0x0D])%0xFF] );mc[2]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[0x0D])%0xFF] )^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[0x09])%0xFF] )^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[0x0E])%0xFF] )^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[0x0B])%0xFF] );mc[3]= ( state[i]==0 ? 0 : Etab[(Ltab[state[i]]+Ltab[0x0B])%0xFF] )^( state[i+4]==0 ? 0 : Etab[(Ltab[state[i+4]]+Ltab[0x0D])%0xFF] )^( state[i+8]==0 ? 0 : Etab[(Ltab[state[i+8]]+Ltab[0x09])%0xFF] )^( state[i+12]==0 ? 0 : Etab[(Ltab[state[i+12]]+Ltab[0x0E])%0xFF] );state[i+0]=mc[0];state[i+4]=mc[1];state[i+8]=mc[2];state[i+12]=mc[3];print_state(state);} /* END Nr rounds *//* 6. InvShiftRow: ⾏逆移位 Inverse Shift State Rows */printf(" --- InvShiftRows() Round:%d ---\n",Nr-round);aes_InvShiftRows(state);print_state(state);/* 7. InvSubBytes: 字节逆代换 InvSubstitue State Bytes with SBOX */ printf(" --- InvSubBytes() Round:%d ---\n",Nr-round);for(k=0; k<16; k++)state[k]=rsbox[state[k]];print_state(state);/* 8. AddRoundKey: 加植密钥 Add State with Round Key */printf(" --- Add Round_key Round:%d ---\n",Nr-round);aes_AddRoundKey(Nr, Nk, 0, state, keywords);print_state(state);return 0;}。
C语言中的网络安全技术
C语言中的网络安全技术网络安全是当今信息技术领域中的一个重要问题,而C语言作为一种广泛应用于系统开发和网络编程的编程语言,也需要具备相应的网络安全技术来保护程序和数据的安全性。
本文将介绍C语言中常用的网络安全技术,包括加密解密算法、数据校验和认证、安全编码规范等。
一、加密解密算法1. 对称加密算法对称加密算法是指加密和解密过程中使用相同的密钥,常用的对称加密算法有DES、3DES、AES等。
在C语言中,我们可以使用openssl库来实现对称加密算法。
例如,使用AES对称加密算法加密数据的代码如下:```c#include <openssl/aes.h>#include <string.h>void encryptAES(unsigned char *input, unsigned char *output, const char *key) {AES_KEY aesKey;AES_set_encrypt_key((const unsigned char*)key, 128, &aesKey);AES_encrypt(input, output, &aesKey);}int main() {unsigned char input[] = "Hello, World!";unsigned char output[16];const char* key = "0123456789abcdef";encryptAES(input, output, key);return 0;}```2. 非对称加密算法非对称加密算法包括公钥和私钥两个密钥,常用的非对称加密算法有RSA和ECC。
在C语言中,我们可以使用openssl库来实现非对称加密算法。
例如,使用RSA非对称加密算法加密数据的代码如下:```c#include <openssl/rsa.h>#include <openssl/pem.h>#include <string.h>void encryptRSA(unsigned char *input, int inputLen, unsigned char*output, int *outputLen, RSA *rsaPublicKey) {*outputLen = RSA_public_encrypt(inputLen, input, output, rsaPublicKey, RSA_PKCS1_PADDING);}int main() {RSA *rsaPublicKey = RSA_new();// 从PEM文件中加载公钥FILE* publicKeyFile = fopen("public_key.pem", "r");PEM_read_RSA_PUBKEY(publicKeyFile, &rsaPublicKey, NULL, NULL);fclose(publicKeyFile);unsigned char input[] = "Hello, World!";unsigned char output[128];int outputLen = 0;encryptRSA(input, strlen((char*)input), output, &outputLen, rsaPublicKey);return 0;}```二、数据校验和认证数据校验是一种用来验证数据完整性的技术,常用的数据校验算法有CRC和MD5。
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);。
AES加密算法中的S盒及其C语言实现
AES加密算法中的S盒及其C语言实现
魏凤兰;汤秀芬;米晨
【期刊名称】《宁夏工程技术》
【年(卷),期】2005(004)001
【摘要】详细叙述了算法中S盒的构造,并给出了其C语言实现的程序代码.S盒由有限域GF(28)上所有元素的乘法逆元及在域GF(2)上的仿射变换构成,经过S盒的非线性字节代换,密文的差分均匀性和线性偏差都达到较理想的状态,提高了AES算法抗击差分密码分析及线性密码分析的能力.在AES算法中,Nr轮的加密过程都要对状态矩阵中的字节求其在有限域GF(28)上的乘法逆元和作GF(2)上的仿射变换,这些都要多次用到大运算量的非线性字节变换操作,为此可以通过一定的算法先算出GF(28)上所有元素的乘法逆元并作相应的仿射变换以形成对字节代换的代换表,即S盒,然后通过查表的方法进行加密过程中的字节代换,从而缩短明文的加密时间,提高AES加密算法的整体效率.
【总页数】3页(P42-44)
【作者】魏凤兰;汤秀芬;米晨
【作者单位】西北第二民族学院,教务处成人教育中心,宁夏,银川,750021;宁夏大学,物理电气信息学院,宁夏,银川,750021;宁夏大学,设备与物资管理处,宁夏,银
川,750021
【正文语种】中文
【中图分类】TP309.7
【相关文献】
1.基于AES算法中S盒的分析研究与改进 [J], 张丽红;凌朝东
2.DES加密算法中S盒的分析与研究 [J], 常巧霞;程铁良
3.AES的S盒和逆S盒的代数表达式 [J], 马虹博;刘连浩
4.基于AES加密算法的S盒优化设计 [J], 胡春燕;易波
5.一种AES算法中S盒和逆S盒替换的表达式方法 [J], 覃晓草;李树国
因版权原因,仅展示原文概要,查看原文内容请购买。
AES算法C语言实现源码
AES算法C语言实现源码/*AES-128 bit CBC Encryptionby Jacob Lister - Mar. 2024AES128-CBC Encryption for CNOTE: This is a C implementation with minimal cost checking, designed for embedded systems with tight code space constraintsgcc -Wall -c aes.cDescription:This code is the implementation of the AES128 algorithm,specifically ECB and CBC mode. ECB stands for ElectronicCode Book mode, which is essentially plain AES encryption.CBC (Cipher Block Chaining) is a mode that allows forenhanced security.*/#include <stdio.h>#include <stdlib.h>#include <string.h>typedef unsigned char AES_BYTE;/*constant in AES. Value=4*/#define Nb 4/* The number of 32 bit words in a key. */#define Nk 4/*Key length in bytes [128 bit](Nk * 4), or 16 bytes.*/#define KEYLEN 16/*The number of rounds in AES Cipher.Number of rounds=10, 12, 14.*/#define Nr 14AES_BYTE * AES_Encrypt(AES_BYTE *plainText, AES_BYTE *key); AES_BYTE * AES_Decrypt(AES_BYTE *cipherText, AES_BYTE *key);Function to store the round keysgenerated from the cipher key.*/void AES_KeyExpansion(AES_BYTE key[4*Nk], AES_BYTE roundKey[4*Nb*(Nr+1)]);/*Cipher is the main function that encryptsthe plaintext given the key [128 bit].*/void AES_Cipher(AES_BYTE *in, AES_BYTE *out, AES_BYTE *roundKey);/*The SubBytes Function is usedto substitute each byte of the statewith its corresponding byte in theRijndael S-box.*/void SubBytes(AES_BYTE *state);The ShiftRows function is usedto shift the rows cyclically aroundthe state.*/void ShiftRows(AES_BYTE *state);/*The MixColumns function is usedto mix the columns of the statematrix.*/void MixColumns(AES_BYTE *state);/*The AddRoundKey function is usedto add round key word to thestate matrix to produce the output.*/void AddRoundKey(AES_BYTE *state, AES_BYTE* roundKey); /*The SubBytes Function is usedto substitute each byte of the state with its inverse in the Rijndael S-box. */void InvSubBytes(AES_BYTE *state);/*The InvShiftRows function is usedto shift the rows cyclically aroundthe state in the opposite direction.*/void InvShiftRows(AES_BYTE *state);/*The InvMixColumns function is usedto mix the columns of the statematrix in the opposite direction.*/void InvMixColumns(AES_BYTE *state);/*The AES_Encrypt functionencrypts the plaintext usingthe provided AES_128 encryptionkey.*/AES_BYTE* AES_Encrypt(AES_BYTE *plainText, AES_BYTE *key) //struct to store ciphertextAES_BYTE *cipherText;int stat_len = 4 * Nb;// The KeyExpansion routine must be called// before encryption.AES_BYTE roundKey[4 * Nb * (Nr + 1)];。
aes算法c语言实现
aes算法c语言实现AES(Advanced Encryption Standard)是一种广泛应用于数据加密的算法。
以下是一个使用C语言实现的AES加密算法示例,用于对字符串进行加密和解密。
这个实现是基于ECB模式的,这是一种常用的加密模式,因为它简单且易于实现。
注意:这个实现是为了教学目的而提供的,可能不适合用于生产环境。
生产环境中的加密实现通常需要更复杂和安全的方法。
```c #include <stdio.h> #include <string.h> #include <stdint.h> #include <openssl/aes.h>void AES_encrypt(const uint8_t *key, const uint8_t*plaintext, uint8_t *ciphertext) { AES_KEY aesKey; AES_set_encrypt_key(key, 128, &aesKey);AES_encrypt(plaintext, ciphertext, &aesKey); }void AES_decrypt(const uint8_t *key, const uint8_t*ciphertext, uint8_t *plaintext) { AES_KEY aesKey; AES_set_decrypt_key(key, 128, &aesKey);AES_decrypt(ciphertext, plaintext, &aesKey); }int main() { // 定义密钥和明文/密文缓冲区uint8_t key[AES_BLOCK_SIZE]; // AES_BLOCK_SIZE是AES算法的块大小,通常是16字节(128位) uint8_tplaintext[AES_BLOCK_SIZE], ciphertext[AES_BLOCK_SIZE];// 填充密钥和明文/密文缓冲区 // 这里省略了填充代码,因为在实际应用中,你应该使用合适的填充方案来保护数据的完整性。
C语言实现AES加密解密
C语言实现AES加密解密AES(Advanced Encryption Standard)是一种对称加密算法,它是目前广泛使用的加密标准之一、本文将介绍如何使用C语言实现AES加密和解密。
AES算法使用128位(16字节)的块进行加密和解密。
它支持128位、192位和256位长度的密钥。
在下面的示例中,我们将演示如何使用128位的密钥进行AES加密和解密。
首先,我们需要准备一个AES加密所需的密钥。
我们可以通过一个字符串来表示密钥,然后将其转换为字节数组。
在C语言中,可以使用`strncpy`函数将字符串复制到字节数组中。
```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <openssl/aes.h>#define AES_KEY_SIZE 128int mai//准备AES密钥unsigned char key[AES_KEY_SIZE/8];strncpy((char*)key, keyStr, AES_KEY_SIZE/8);//创建AES加密上下文AES_KEY aesKey;AES_set_encrypt_key(key, AES_KEY_SIZE, &aesKey); //待加密的数据unsigned char input[] = "Hello, AES!";int inputLen = sizeof(input)/sizeof(input[0]); //加密数据unsigned char encrypted[AES_BLOCK_SIZE];AES_encrypt(input, encrypted, &aesKey);//输出加密结果printf("Encrypted: ");for (int i = 0; i < AES_BLOCK_SIZE; i++)printf("%02x", encrypted[i]);}printf("\n");//创建AES解密上下文AES_set_decrypt_key(key, AES_KEY_SIZE, &aesKey); //解密数据unsigned char decrypted[AES_BLOCK_SIZE];AES_decrypt(encrypted, decrypted, &aesKey);//输出解密结果printf("Decrypted: ");for (int i = 0; i < AES_BLOCK_SIZE; i++)printf("%c", decrypted[i]);}printf("\n");return 0;```在上面的示例中,我们使用OpenSSL库提供的AES函数来执行加密和解密操作。
c语言 aes256 ecb 算法
一、介绍C语言是一种广泛应用的计算机编程语言,而AES256 ECB算法是一种高级加密标准,也是一种对称加密算法。
本文将详细介绍C语言中实现AES256 ECB算法的方式及其原理。
二、AES256 ECB算法AES256 ECB算法是一种对称加密算法,使用256位的密钥进行加密和解密。
ECB(Electronic Codebook)模式是AES加密算法中最简单的模式,它将整个消息分割成固定长度的块,然后对每个块进行加密。
1. 加密过程- 对明文进行填充,使其长度为块的整数倍。
- 将填充后的明文分割成若干块,每个块的长度与密钥长度相同。
- 接下来,对每个块使用AES256算法进行加密,并将加密结果拼接在一起,得到密文。
2. 解密过程- 将密文分割成若干块,每个块的长度与密钥长度相同。
- 对每个块使用AES256算法进行解密,并将解密结果拼接在一起。
- 去除填充得到明文。
三、C语言中实现AES256 ECB算法的方式在C语言中实现AES256 ECB算法可以借助开源的加密库,例如openssl库。
以下是使用openssl库实现AES256 ECB算法的示例代码:```#include <openssl/aes.h>void aes_encrypt_ecb(const unsigned char *pl本人ntext, const unsigned char *key, unsigned char *ciphertext) {AES_KEY aes_key;AES_set_encrypt_key(key, 256, aes_key);AES_encrypt(pl本人ntext, ciphertext, aes_key);}void aes_decrypt_ecb(const unsigned char *ciphertext, const unsigned char *key, unsigned char *pl本人ntext) {AES_KEY aes_key;AES_set_decrypt_key(key, 256, aes_key);AES_decrypt(ciphertext, pl本人ntext, aes_key);}```以上代码中,aes_encrypt_ecb函数用于对明文进行加密,aes_decrypt_ecb函数用于对密文进行解密。
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加密算法。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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*/
{ /* 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,
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*/
//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 10
class AES : public Encryption { public:
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 _ENCRYPTIOdafx.h"
class Encryption { public:
virtual void Encrypt(BYTE *, BYTE *,size_t) = 0; virtual void Decrypt(BYTE *, BYTE *,size_t) = 0; }; #endif
/*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,
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 AES::Encrypt(unsigned char* data ,unsigned char * encryptArray,size_t len) {
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*/
/*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,
/* create a Encrypt method
*/
/* param : data encrypt data
*/
/* param : encryptArray encryptArray
*/
/* param : len encrypt data length
*/
/* return : void
*/
/*9*/ 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
/*a*/
/*b*/ /*c*/ /*d*/ /*e*/ /*f*/
};
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,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16 /*f*/
}; //inversepermutationbox static unsigned char inversepermutationbox[]=
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*/
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];
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*/
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);
//AES.cpp
#include "stdafx.h" #include "AES.h" #include <stdlib.h> #include <memory.h>
//permutebox static unsigned char 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,
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*/
//EncryptionFactory.h
#ifndef _ENCRYPTION_FACTORY_H_ #define _ENCRYPTION_FACTORY_H_