C语言实现AES加密解密

AES加密是美国联邦政府采用的一种块加密标准,如今已经被全世界广为使用。嵌入式开发中我们也经常会用到加密解密算法,如果没有硬件模块来实现,就需要用到C代码软件实现。下面介绍调用mbedTLS中的AES加密解密函数实现AES算法。

mbedTLS是一个开源TLS协议栈,主要用于嵌入式开发,其源代码网址为https://tls.mbed.org/aes-source-code。在该页面上点击downloadmbedTLS即可下载最新的协议栈,解压该压缩包就可以得到协议栈源代码。协议栈中的各种算法都独立封装在C文件中,彼此耦合度较低,目的是便于调用。我这里下的是2.2.1版本,解压后可以看到mbedtls-2.2.1\include\mbedtls路径下有许多header文件,将其添加到IDE的头文件中。在mbedtls-2.2.1\library下有许多c文件,我们只添加需要用到的aes.c。

这里使用Visual Studio2013 C/C++环境进行编译演示。新建控制台应用,空工程。在Header Files文件夹下添加头文件,注意连文件夹一起添加,因为C文件中的include是包含路径的。然后把aes.c添加到source文件夹里。此时直接编译就能通过啦!


接下来就是在主函数里调用函数。这里调用了ECB模式和CBC模式两种。源代码如下:

#include<stdio.h>
#include "mbedtls/aes.h"
#include "mbedtls/compat-1.3.h"
 
#define AES_ECB 0
#define AES_CBC 1
#define AES_CFB 2
#define AES_CTR 3
#define MODE AES_ECB
 
unsigned char key[16] = { 0x22,
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C语言实现AES加密解密算法可以使用现成的库,也可以自己实现。下面是一个使用OpenSSL库实现AES加密解密的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/aes.h> #define BLOCK_SIZE 16 int aes_encrypt(unsigned char *in, int in_len, unsigned char *key, unsigned char *out) { AES_KEY aes_key; if (AES_set_encrypt_key(key, 128, &aes_key) < 0) { return -1; } int len = in_len; unsigned char *padding = NULL; if (len % BLOCK_SIZE != 0) { padding = (unsigned char *)malloc(BLOCK_SIZE - len % BLOCK_SIZE); memset(padding, BLOCK_SIZE - len % BLOCK_SIZE, BLOCK_SIZE - len % BLOCK_SIZE); len += BLOCK_SIZE - len % BLOCK_SIZE; } int i = 0; while (i < len) { AES_encrypt(in + i, out + i, &aes_key); i += BLOCK_SIZE; } if (padding != NULL) { memcpy(out + len - BLOCK_SIZE, padding, BLOCK_SIZE - len % BLOCK_SIZE); free(padding); } return 0; } int aes_decrypt(unsigned char *in, int in_len, unsigned char *key, unsigned char *out) { AES_KEY aes_key; if (AES_set_decrypt_key(key, 128, &aes_key) < 0) { return -1; } int len = in_len; unsigned char *padding = NULL; if (len % BLOCK_SIZE != 0) { return -1; } int i = 0; while (i < len) { AES_decrypt(in + i, out + i, &aes_key); i += BLOCK_SIZE; } return 0; } int main() { unsigned char in[] = "Hello, world!"; unsigned char key[] = "0123456789abcdef"; unsigned char out[32] = {0}; aes_encrypt(in, strlen(in), key, out); unsigned char dec[32] = {0}; aes_decrypt(out, 16, key, dec); printf("in: %s\n", in); printf("out: "); for (int i = 0; i < 16; i++) { printf("%02x", out[i]); } printf("\n"); printf("dec: %s\n", dec); return 0; } ``` 在上面的代码中,使用了OpenSSL库提供的AES加密解密函数。需要注意的是,加密的数据长度必须为16的倍数,如果不足16个字节,需要进行填充。在示例中,使用了简单的尾部填充方式。另外,密钥长度为128位,可以根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青年夏日科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值