C 语言 AES 算法实现(基于 Mbedtls),java 中高级面试题最新
project("device-authentication")
cmake_minimum_required(VERSION 3.5)
INCLUDE_DIRECTORIES(
../include/
../../src/net/mbedtls/include
../../src/smalgo/sms4/include
)
SET(my_src_crypto
../../src/net/mbedtls/library/aes.c
../../src/net/mbedtls/library/aesni.c
../../src/net/mbedtls/library/base64.c
../../src/net/mbedtls/library/rsa.c
../../src/net/mbedtls/library/rsa_internal.c
../../src/net/mbedtls/library/entropy.c
../../src/net/mbedtls/library/entropy_poll.c
../../src/net/mbedtls/library/bignum.c
../../src/net/mbedtls/library/sha1.c
../../src/net/mbedtls/library/sha256.c
../../src/net/mbedtls/library/sha512.c
../../src/net/mbedtls/library/md.c
../../src/net/mbedtls/library/md5.c
../../src/net/mbedtls/library/md_wrap.c
../../src/net/mbedtls/library/ripemd160.c
../../src/net/mbedtls/library/platform_util.c
../../src/net/mbedtls/library/oid.c
../../src/net/mbedtls/library/timing.c
../../src/net/mbedtls/library/net_sockets.c
../../src/smalgo/sms4/cbc128.c
../../src/smalgo/sms4/sms4_cbc.c
../../src/smalgo/sms4/sms4_common.c
../../src/smalgo/sms4/sms4_enc.c
../../src/smalgo/sms4/sms4_setkey.c
)
SET(my_src_crypto_dbg
../../src/net/mbedtls/library/ctr_drbg.c
)
SET(SRC_LIST_ENCRYPT_BIN
oem_porting.c
sdk_porting.c
authref.c
test.c
${my_src_crypto}
${my_src_crypto_dbg}
)
SET(SRC_LIST_DECRYPT_LIB
oem_porting.c
sdk_porting.c
authref.c
auth.c
${my_src_crypto}
${my_src_crypto_dbg}
)
#SET(SRC_LIST_AUTH_DEV
oem_porting.c
sdk_porting.c
authref.c
${my_src_crypto}
${my_src_crypto_dbg}
#)
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})
工程结构如下:
引入完成之后我们就可以开始 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 解密
// aes_key -- 最长 48 字节
// iv -- 最长 16 字节
// ciphertext -- 待解密的文本
// plaintext -- 解密好的文本
// len -- len should
be 16*N bytes
// return – 0 for ok, else for error
int aes_cbc_decryp(uint8_t *aes_key, uint8_t *iv, uint8_t *ciphertext, uint8_t *plaintext, uint32_t len);
#ifdef __cplusplus
}
#endif
#endif //AUTHREF_H
authref.c 代码如下:?
#include "authref.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
评论