天天看点

C语言AES算法实现(基于Mbedtls)oem_portinsdk_porting.cauthref.c${my_src_crypto}${my_src_crypto_dbg}

${my_src_crypto_dbg}

)

set(src_list_decrypt_lib

oem_porting.c

sdk_porting.c

authref.c

auth.c

${my_src_crypto}

#set(src_list_auth_dev

g.c

#)

add_definitions(-fpic)

#add_library(authd static ${src_list_auth_dev})

add_library(authoal static ${src_list_decrypt_lib})

add_executable(eaidkauth ${src_list_encrypt_bin})

工程结构如下:

C语言AES算法实现(基于Mbedtls)oem_portinsdk_porting.cauthref.c${my_src_crypto}${my_src_crypto_dbg}

引入完成之后我们就可以开始aes代码编写。

3、aes代码编写

authref.h 头文件代码如下:

#ifndef __authref_h__

#define __authref_h__

#include <assert.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#undef debug

#define aes_key_size 48

#define aes_iv_len 16

#ifdef __cplusplus

extern "c" {

#endif

// aes加密

// aes_key -- 最长48字节

// iv -- 最长16字节

// plaintext -- 待加密文本

// ciphertext -- 加密得到的文本

// len -- len should be 16*n bytes

// return – 0 for ok, else for error

int aes_cbc_encryp(uint8_t aes_key, uint8_t iv, uint8_t plaintext, uint8_t ciphertext, uint32_t len);

// aes解密

// ciphertext -- 待解密的文本

// plaintext -- 解密好的文本

int aes_cbc_decryp(uint8_t aes_key, uint8_t iv, uint8_t ciphertext, uint8_t plaintext, uint32_t len);

}

#endif //__authref_h__

authref.c 代码如下:?

#include "authref.h"

#include "mbedtls/entropy.h"

#include "mbedtls/ctr_drbg.h"

#include "mbedtls/aes.h"

//len should be 16*n bytes

int aes_cbc_encryp(uint8_t aes_key, uint8_t iv, uint8_t plaintext, uint8_t ciphertext, uint32_t len) {

int i;

int blk = (len + 15) >> 4;

mbedtls_aes_context aes_ctx;

mbedtls_aes_init(&aes_ctx);

//setkey_dec

mbedtls_aes_setkey_enc(&aes_ctx, aes_key, 256);

for (i = 0; i < blk; ++i) {

mbedtls_aes_crypt_cbc(&aes_ctx, mbedtls_aes_encrypt, 16, iv, plaintext + (i 16), ciphertext + (i 16));

mbedtls_aes_free(&aes_ctx);

return 0; //ok

int aes_cbc_decryp(uint8_t aes_key, uint8_t iv, uint8_t ciphertext, uint8_t plaintext, uint32_t len) {

mbedtls_aes_setkey_dec(&aes_ctx, aes_key, 256);

mbedtls_aes_crypt_cbc(&aes_ctx, mbedtls_aes_decrypt, 16, iv, ciphertext + (i 16), plaintext + (i 16));