////////////////////////////////////////////////////////////////////////// // 函数名: AES_Decrypt // 描述: 解密数据 // 输入参数: pCipherText -- 密文,即需解密的数据,其长度为nDataLen字节。 // nDataLen -- 数据长度,以字节为单位,必须为AES_KEY_LENGTH/8的整倍数。 // pIV -- 初始化向量,如果使用ECB模式,可设为NULL。 // 输出参数: pPlainText -- 明文,即由密文解密后的数据,可以与pCipherText相同。 // 返回值: 无。 ////////////////////////////////////////////////////////////////////////// void AES_Decrypt(unsigned char *pPlainText, const unsigned char *pCipherText, unsigned int nDataLen, const unsigned char *pIV) { unsigned int i; if (pPlainText != pCipherText) { memcpy(pPlainText, pCipherText, nDataLen); } // 从最后一块数据开始解密,这样不用开辟空间来保存IV pPlainText += nDataLen - 4*Nb; for (i = nDataLen/(4*Nb); i > 0 ; i--, pPlainText -= 4*Nb) { BlockDecrypt(pPlainText); #if AES_MODE == AES_MODE_CBC if (i == 1) {// 最后一块数据 XorBytes(pPlainText, pIV, 4*Nb); } else { XorBytes(pPlainText, pPlainText - 4*Nb, 4*Nb); } #endif } }
/////////////////////////////////////////////////////////////////////////////// // 函数名: AES_Init // 描述: 初始化,在此执行扩展密钥操作。 // 输入参数: pKey -- 原始密钥,其长度必须为 AES_KEY_LENGTH/8 字节。 // 输出参数: 无。 // 返回值: 无。 /////////////////////////////////////////////////////////////////////////////// void AES_Init(const void *pKey) { // 扩展密钥 unsigned char i; unsigned char *pRoundKey; unsigned char Rcon[4] = {0x01, 0x00, 0x00, 0x00}; memcpy(g_roundKeyTable, pKey, 4*Nk); pRoundKey = &g_roundKeyTable[4*Nk]; for (i = Nk; i < Nb*(Nr+1); pRoundKey += 4, i++) { memcpy(pRoundKey, pRoundKey - 4, 4); if (i % Nk == 0) { RotationWord(pRoundKey); SubBytes(pRoundKey, 4, 0); XorBytes(pRoundKey, Rcon, 4); Rcon[0] = GfMultBy02(Rcon[0]); } else if (Nk > 6 && i % Nk == Nb) { SubBytes(pRoundKey, 4, 0); } XorBytes(pRoundKey, pRoundKey - 4*Nk, 4); } }
void CryptModeCBC::Decrypt(const unsigned char* source, unsigned char* target, unsigned int size) { unsigned int chunk_size=cipher->GetBlockSize(); while(size>=chunk_size){ feedback_buffer.assign(source, chunk_size); block_transformer->ProcessData(source, target); XorBytes(target, feedback_buffer.c_str(), chunk_size); source+=chunk_size; target+=chunk_size; size-=chunk_size; } }
////////////////////////////////////////////////////////////////////////// // 函数名: AES_Encrypt // 描述: 加密数据 // 输入参数: pPlainText -- 明文,即需加密的数据,其长度为nDataLen字节。 // nDataLen -- 数据长度,以字节为单位,必须为AES_KEY_LENGTH/8的整倍数。 // pIV -- 初始化向量,如果使用ECB模式,可设为NULL。 // 输出参数: pCipherText -- 密文,即由明文加密后的数据,可以与pPlainText相同。 // 返回值: 无。 ////////////////////////////////////////////////////////////////////////// void AES_Encrypt(const unsigned char *pPlainText, unsigned char *pCipherText, unsigned int nDataLen, const unsigned char *pIV) { unsigned int i; if (pPlainText != pCipherText) { memcpy(pCipherText, pPlainText, nDataLen); } for (i = nDataLen/(4*Nb); i > 0 ; i--, pCipherText += 4*Nb) { #if AES_MODE == AES_MODE_CBC XorBytes(pCipherText, pIV, 4*Nb); #endif BlockEncrypt(pCipherText); pIV = pCipherText; } }