当前位置:   article > 正文

C语言实现AES加密解密_aes_crypt_cbc()

aes_crypt_cbc()

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模式两种。源代码如下:


  1. #include<stdio.h>
  2. #include "mbedtls/aes.h"
  3. #include "mbedtls/compat-1.3.h"
  4. #define AES_ECB 0
  5. #define AES_CBC 1
  6. #define AES_CFB 2
  7. #define AES_CTR 3
  8. #define MODE AES_ECB
  9. unsigned char key[16] = { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 };
  10. unsigned char plain[32] = { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
  11. unsigned char plain_decrypt[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  12. unsigned char IV[16];
  13. unsigned char cypher[32];
  14. int i = 0;
  15. mbedtls_aes_context aes;
  16. void SetIV()
  17. {
  18. int i;
  19. for (i = 0; i < 16; i++)
  20. {
  21. IV[i] = 0x55;
  22. }
  23. }
  24. int main()
  25. {
  26. if (MODE == AES_ECB)
  27. {
  28. mbedtls_aes_setkey_enc(&aes, key, 128);// set encrypt key
  29. mbedtls_aes_crypt_ecb(&aes, AES_ENCRYPT, plain, cypher);
  30. mbedtls_aes_setkey_dec(&aes, key, 128);// set decrypt key
  31. mbedtls_aes_crypt_ecb(&aes, AES_DECRYPT, cypher, plain_decrypt);
  32. i++;
  33. }
  34. if (MODE == AES_CBC)
  35. {
  36. mbedtls_aes_setkey_enc(&aes, key, 128);// set encrypt key
  37. SetIV();
  38. mbedtls_aes_crypt_cbc(&aes, AES_ENCRYPT, 32, IV, plain, cypher);
  39. mbedtls_aes_setkey_dec(&aes, key, 128);// set decrypt key
  40. SetIV();
  41. mbedtls_aes_crypt_cbc(&aes, AES_DECRYPT, 32, IV, cypher, plain_decrypt);
  42. i++;
  43. }
  44. }
单步运行,在 debug 窗口中可以观察到 cypher 数组的值改变,变为加密后的值,以及 plain _decrypt 数组中的值变为解密后的值,也就是和 plain 数组中一样。J~




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51779
推荐阅读
相关标签
  

闽ICP备14008679号