- mbed-crypto的開源項目倉庫:mbed-crypto
- IDE:codeblocks
- 系統:Ubuntu 16.04 LTS
- 編譯器,調試器:gcc,gdb
一、AES加密算法的簡介,以及五種加密方式
轉載文章:AES加密之五種模式
二、建立測試的項目工程
- 打開codeblocks,NewFIle->Project->Console application;将項目名稱命名為aes_test;
- 在Workspace右擊項目名稱,add file recursively添加庫檔案,将include和library檔案夾中的所有檔案添加到項目目錄;添加完成的project tree如下圖所示。
- 将頭檔案包含進項目的索引目錄下;Settings->Compiler->Search directories->add将inlude檔案目錄包含進來
三、閱讀源碼
crypto/library/aes.c中有一個測試函數int mbedtls_aes_self_test( int verbose )就是官方給出的測試函數。作為測試,先隻看CBC加密模式。
- 初始化
int mode; //判斷加密或解密
unsigned int keybits; //密鑰的長度
unsigned char key[32]; //密鑰的緩存
unsigned char buf[64]; //加密的秘文與解密的明文的緩存區
mbedtls_aes_context ctx; //定義aes的工作場景類型
memset( key, 0, 32 ); //設定密鑰,這裡設定的密鑰全為0
mbedtls_aes_init( &ctx ); //aes的工作場景初始化
- 設定解密的密鑰與解密的密鑰
if( mode == MBEDTLS_AES_DECRYPT )
{
ret = mbedtls_aes_setkey_dec( &ctx, key, keybits ); //設定解密的密鑰
aes_tests = aes_test_cbc_dec[u];
}
else
{
ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );//設定加密的密鑰
aes_tests = aes_test_cbc_enc[u];
}
- 加密或者解密共用一個函數
函數原型:
/**
* \brief This function performs an AES single-block encryption or
* decryption operation.
*
* It performs the operation defined in the \p mode parameter
* (encrypt or decrypt), on the input data buffer defined in
* the \p input parameter.
*
* mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
* mbedtls_aes_setkey_dec() must be called before the first
* call to this API with the same context.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param input The buffer holding the input data.
* It must be readable and at least \c 16 Bytes long.
* \param output The buffer where the output data will be written.
* It must be writeable and at least \c 16 Bytes long.
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
其中參數mode控制解密還是加密,當mode=1時加密;當mode=0時解密。
* \param mode The AES operation:
* #MBEDTLS_AES_ENCRYPT or#MBEDTLS_AES_DECRYPT.
/* padlock.c and aesni.c rely on these values! */
#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */
#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */
四、編寫測試代碼
void my_test(void)
{
char *key="12345678";
char buf[64]="hello";
mbedtls_aes_context ctx;
mbedtls_aes_init( &ctx );
mbedtls_aes_setkey_enc( &ctx, key, 128 );
mbedtls_aes_crypt_ecb( &ctx, 1, buf, buf ); //加密
mbedtls_printf("this is encrypt:%s\n",buf);
mbedtls_aes_setkey_dec( &ctx, key, 128 );
mbedtls_aes_crypt_ecb( &ctx, 0, buf, buf ); //解密
mbedtls_printf("this is encrypt:%s\n",buf);
}