当前位置:   article > 正文

数据加密与安全专题《mbedtls工具篇,实用教程4@对称加密算法,AES128算法应用》

数据加密与安全专题《mbedtls工具篇,实用教程4@对称加密算法,AES128算法应用》

什么是对称加密

对称加密算法是一种使用相同的密钥加密明文和解密密文的密码算法,通信双方持有相同的密钥,该密钥被称为共享密钥或对称密钥。第三方窃听到密文后,由于没有密钥,没法解密得到原文。对称加密算法单次只能处理一个固定长度得分组数据,例如AES算法单次只能加密或加密128位数据。当然实际场景中被AES加密或解密得消息长度往往不是128位或者128位的整倍,于是AES算法制定了分组密码模式和消息填充方法。

如上电脑A向电脑B的密文传输过程:

  • 电脑A使用共享密钥先对明文进行加密,得到密文
  • 电脑A向电脑B发送密文
  • 电脑B接收到密文后,使用共享密钥对密文进行解密,得到明文
  • 第三方窃听者截获到密文,但是由于没有共享密钥,解密失败,得到一堆加密后的乱码,没有任何参考意义

分组密码模式

  • ECB(电子密码本)模式,需要填充

电子密码本(Electronic Codebook)模式是最简单的分组加密模式,将明文进行分组加密,加密结果为密码分组,ECB模式过于简单,存在明显确点,在安全性要求较高的场合一般不使用。

  • CBC(密码分组链接)模式,需要填充和IV 

密码分组链接(Cipher Block Chaining)模式中,每一组明文在加密前都与前面的密文分组进行异或操作。由于第一个明文分组前面没有密文分组,所以需要准备一个与密文分组长度相等的比特序列来代替密文分组,这个比特序列被称为初始化向量(Initialization Vector),简称IV。(注意:需要加密、解密双方都是用同样的IV值,否则解密失败)

  • CTR(计数器)模式,不需要填充

计数器模式使用与分组长度相同的计数值参与运算,典型的实现方法是通过对逐次累加的计数器进行加密来生成密钥流,通过加密计数器得到的密钥流与明文分组进行异或运算,得到密文分组

与ECB模式和CRC模式相比,CTR模式具有几个优点:

  • 软件效率:支持并行计算,提高效率,节省时间
  • 随机访问特性:部分密文分组受到破坏也不会影响到其他密文分组的解密过程
  • 简单性:CTR模式仅需要加密算法,不需要解密算法,不需要对明文进行填充处理(若明文长度不是分组长度的整数倍,假设最后一个明文分组的长度为L位,那么最后一个明文分组只需与计数器加密结果的左侧L位异或,获得的密文分组长度也就是L位,这种算法结构使得CRT模式不需要对明文进行填充

消息填充方法

上面说到ECB和CBC模式需要进行消息填充,常用的填充方案有几种,这里介绍下PKCS7填充方法,简记,缺多少填多少,缺什么填什么。

  • 例如AES128算法中,分组长度为16字节,若待加密明文为28字节,则需要在明文末尾填充4字节04,使其达到分组长度的整数倍(128bit整数倍)
  • 若待加密数据刚好是16字节,需要在明文后面额外填充16字节,并将其全部填充为16(注意,解密需要使用对应的填充方案还原原数据长度,剔除解密内容里面的填充字节,得到原文)

mbedtls工具对称加密算法,AES128算法的实现

AES128算法,参照路径mbedtls/programs/aes/aescrypt2.c

  1. /*
  2. * AES-256 file encryption program
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. /* Enable definition of fileno() even when compiling with -std=c99. Must be
  22. * set before config.h, which pulls in glibc's features.h indirectly.
  23. * Harmless on other platforms. */
  24. #define _POSIX_C_SOURCE 1
  25. #if !defined(MBEDTLS_CONFIG_FILE)
  26. #include "mbedtls/config.h"
  27. #else
  28. #include MBEDTLS_CONFIG_FILE
  29. #endif
  30. #if defined(MBEDTLS_PLATFORM_C)
  31. #include "mbedtls/platform.h"
  32. #else
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #define mbedtls_fprintf fprintf
  36. #define mbedtls_printf printf
  37. #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
  38. #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
  39. #endif /* MBEDTLS_PLATFORM_C */
  40. #include "mbedtls/aes.h"
  41. #include "mbedtls/md.h"
  42. #include <stdio.h>
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #if defined(_WIN32)
  46. #include <windows.h>
  47. #if !defined(_WIN32_WCE)
  48. #include <io.h>
  49. #endif
  50. #else
  51. #include <sys/types.h>
  52. #include <unistd.h>
  53. #endif
  54. #define MODE_ENCRYPT 0
  55. #define MODE_DECRYPT 1
  56. #define USAGE \
  57. "\n aescrypt2 <mode> <input filename> <output filename> <key>\n" \
  58. "\n <mode>: 0 = encrypt, 1 = decrypt\n" \
  59. "\n example: aescrypt2 0 file file.aes hex:E76B2413958B00E193\n" \
  60. "\n"
  61. #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_SHA256_C) || \
  62. !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_MD_C)
  63. int main( void )
  64. {
  65. mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_SHA256_C "
  66. "and/or MBEDTLS_FS_IO and/or MBEDTLS_MD_C "
  67. "not defined.\n");
  68. return( 0 );
  69. }
  70. #else
  71. int main( int argc, char *argv[] )
  72. {
  73. int ret = 0;
  74. int exit_code = MBEDTLS_EXIT_FAILURE;
  75. unsigned int i, n;
  76. int mode, lastn;
  77. size_t keylen;
  78. FILE *fkey, *fin = NULL, *fout = NULL;
  79. char *p;
  80. unsigned char IV[16];
  81. unsigned char tmp[16];
  82. unsigned char key[512];
  83. unsigned char digest[32];
  84. unsigned char buffer[1024];
  85. unsigned char diff;
  86. mbedtls_aes_context aes_ctx;
  87. mbedtls_md_context_t sha_ctx;
  88. #if defined(_WIN32_WCE)
  89. long filesize, offset;
  90. #elif defined(_WIN32)
  91. LARGE_INTEGER li_size;
  92. __int64 filesize, offset;
  93. #else
  94. off_t filesize, offset;
  95. #endif
  96. mbedtls_aes_init( &aes_ctx );
  97. mbedtls_md_init( &sha_ctx );
  98. ret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
  99. if( ret != 0 )
  100. {
  101. mbedtls_printf( " ! mbedtls_md_setup() returned -0x%04x\n", -ret );
  102. goto exit;
  103. }
  104. /*
  105. * Parse the command-line arguments.
  106. */
  107. if( argc != 5 )
  108. {
  109. mbedtls_printf( USAGE );
  110. #if defined(_WIN32)
  111. mbedtls_printf( "\n Press Enter to exit this program.\n" );
  112. fflush( stdout ); getchar();
  113. #endif
  114. goto exit;
  115. }
  116. mode = atoi( argv[1] );
  117. memset( IV, 0, sizeof( IV ) );
  118. memset( key, 0, sizeof( key ) );
  119. memset( digest, 0, sizeof( digest ) );
  120. memset( buffer, 0, sizeof( buffer ) );
  121. if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
  122. {
  123. mbedtls_fprintf( stderr, "invalide operation mode\n" );
  124. goto exit;
  125. }
  126. if( strcmp( argv[2], argv[3] ) == 0 )
  127. {
  128. mbedtls_fprintf( stderr, "input and output filenames must differ\n" );
  129. goto exit;
  130. }
  131. if( ( fin = fopen( argv[2], "rb" ) ) == NULL )
  132. {
  133. mbedtls_fprintf( stderr, "fopen(%s,rb) failed\n", argv[2] );
  134. goto exit;
  135. }
  136. if( ( fout = fopen( argv[3], "wb+" ) ) == NULL )
  137. {
  138. mbedtls_fprintf( stderr, "fopen(%s,wb+) failed\n", argv[3] );
  139. goto exit;
  140. }
  141. /*
  142. * Read the secret key from file or command line
  143. */
  144. if( ( fkey = fopen( argv[4], "rb" ) ) != NULL )
  145. {
  146. keylen = fread( key, 1, sizeof( key ), fkey );
  147. fclose( fkey );
  148. }
  149. else
  150. {
  151. if( memcmp( argv[4], "hex:", 4 ) == 0 )
  152. {
  153. p = &argv[4][4];
  154. keylen = 0;
  155. while( sscanf( p, "%02X", &n ) > 0 &&
  156. keylen < (int) sizeof( key ) )
  157. {
  158. key[keylen++] = (unsigned char) n;
  159. p += 2;
  160. }
  161. }
  162. else
  163. {
  164. keylen = strlen( argv[4] );
  165. if( keylen > (int) sizeof( key ) )
  166. keylen = (int) sizeof( key );
  167. memcpy( key, argv[4], keylen );
  168. }
  169. }
  170. #if defined(_WIN32_WCE)
  171. filesize = fseek( fin, 0L, SEEK_END );
  172. #else
  173. #if defined(_WIN32)
  174. /*
  175. * Support large files (> 2Gb) on Win32
  176. */
  177. li_size.QuadPart = 0;
  178. li_size.LowPart =
  179. SetFilePointer( (HANDLE) _get_osfhandle( _fileno( fin ) ),
  180. li_size.LowPart, &li_size.HighPart, FILE_END );
  181. if( li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR )
  182. {
  183. mbedtls_fprintf( stderr, "SetFilePointer(0,FILE_END) failed\n" );
  184. goto exit;
  185. }
  186. filesize = li_size.QuadPart;
  187. #else
  188. if( ( filesize = lseek( fileno( fin ), 0, SEEK_END ) ) < 0 )
  189. {
  190. perror( "lseek" );
  191. goto exit;
  192. }
  193. #endif
  194. #endif
  195. if( fseek( fin, 0, SEEK_SET ) < 0 )
  196. {
  197. mbedtls_fprintf( stderr, "fseek(0,SEEK_SET) failed\n" );
  198. goto exit;
  199. }
  200. if( mode == MODE_ENCRYPT )
  201. {
  202. /*
  203. * Generate the initialization vector as:
  204. * IV = SHA-256( filesize || filename )[0..15]
  205. */
  206. for( i = 0; i < 8; i++ )
  207. buffer[i] = (unsigned char)( filesize >> ( i << 3 ) );
  208. p = argv[2];
  209. mbedtls_md_starts( &sha_ctx );
  210. mbedtls_md_update( &sha_ctx, buffer, 8 );
  211. mbedtls_md_update( &sha_ctx, (unsigned char *) p, strlen( p ) );
  212. mbedtls_md_finish( &sha_ctx, digest );
  213. memcpy( IV, digest, 16 );
  214. /*
  215. * The last four bits in the IV are actually used
  216. * to store the file size modulo the AES block size.
  217. */
  218. lastn = (int)( filesize & 0x0F );
  219. IV[15] = (unsigned char)
  220. ( ( IV[15] & 0xF0 ) | lastn );
  221. /*
  222. * Append the IV at the beginning of the output.
  223. */
  224. if( fwrite( IV, 1, 16, fout ) != 16 )
  225. {
  226. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
  227. goto exit;
  228. }
  229. /*
  230. * Hash the IV and the secret key together 8192 times
  231. * using the result to setup the AES context and HMAC.
  232. */
  233. memset( digest, 0, 32 );
  234. memcpy( digest, IV, 16 );
  235. for( i = 0; i < 8192; i++ )
  236. {
  237. mbedtls_md_starts( &sha_ctx );
  238. mbedtls_md_update( &sha_ctx, digest, 32 );
  239. mbedtls_md_update( &sha_ctx, key, keylen );
  240. mbedtls_md_finish( &sha_ctx, digest );
  241. }
  242. mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 );
  243. mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
  244. /*
  245. * Encrypt and write the ciphertext.
  246. */
  247. for( offset = 0; offset < filesize; offset += 16 )
  248. {
  249. n = ( filesize - offset > 16 ) ? 16 : (int)
  250. ( filesize - offset );
  251. if( fread( buffer, 1, n, fin ) != (size_t) n )
  252. {
  253. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", n );
  254. goto exit;
  255. }
  256. for( i = 0; i < 16; i++ )
  257. buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
  258. mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, buffer, buffer );
  259. mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
  260. if( fwrite( buffer, 1, 16, fout ) != 16 )
  261. {
  262. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
  263. goto exit;
  264. }
  265. memcpy( IV, buffer, 16 );
  266. }
  267. /*
  268. * Finally write the HMAC.
  269. */
  270. mbedtls_md_hmac_finish( &sha_ctx, digest );
  271. if( fwrite( digest, 1, 32, fout ) != 32 )
  272. {
  273. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", 16 );
  274. goto exit;
  275. }
  276. }
  277. if( mode == MODE_DECRYPT )
  278. {
  279. /*
  280. * The encrypted file must be structured as follows:
  281. *
  282. * 00 .. 15 Initialization Vector
  283. * 16 .. 31 AES Encrypted Block #1
  284. * ..
  285. * N*16 .. (N+1)*16 - 1 AES Encrypted Block #N
  286. * (N+1)*16 .. (N+1)*16 + 32 HMAC-SHA-256(ciphertext)
  287. */
  288. if( filesize < 48 )
  289. {
  290. mbedtls_fprintf( stderr, "File too short to be encrypted.\n" );
  291. goto exit;
  292. }
  293. if( ( filesize & 0x0F ) != 0 )
  294. {
  295. mbedtls_fprintf( stderr, "File size not a multiple of 16.\n" );
  296. goto exit;
  297. }
  298. /*
  299. * Subtract the IV + HMAC length.
  300. */
  301. filesize -= ( 16 + 32 );
  302. /*
  303. * Read the IV and original filesize modulo 16.
  304. */
  305. if( fread( buffer, 1, 16, fin ) != 16 )
  306. {
  307. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
  308. goto exit;
  309. }
  310. memcpy( IV, buffer, 16 );
  311. lastn = IV[15] & 0x0F;
  312. /*
  313. * Hash the IV and the secret key together 8192 times
  314. * using the result to setup the AES context and HMAC.
  315. */
  316. memset( digest, 0, 32 );
  317. memcpy( digest, IV, 16 );
  318. for( i = 0; i < 8192; i++ )
  319. {
  320. mbedtls_md_starts( &sha_ctx );
  321. mbedtls_md_update( &sha_ctx, digest, 32 );
  322. mbedtls_md_update( &sha_ctx, key, keylen );
  323. mbedtls_md_finish( &sha_ctx, digest );
  324. }
  325. mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 );
  326. mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
  327. /*
  328. * Decrypt and write the plaintext.
  329. */
  330. for( offset = 0; offset < filesize; offset += 16 )
  331. {
  332. if( fread( buffer, 1, 16, fin ) != 16 )
  333. {
  334. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 16 );
  335. goto exit;
  336. }
  337. memcpy( tmp, buffer, 16 );
  338. mbedtls_md_hmac_update( &sha_ctx, buffer, 16 );
  339. mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_DECRYPT, buffer, buffer );
  340. for( i = 0; i < 16; i++ )
  341. buffer[i] = (unsigned char)( buffer[i] ^ IV[i] );
  342. memcpy( IV, tmp, 16 );
  343. n = ( lastn > 0 && offset == filesize - 16 )
  344. ? lastn : 16;
  345. if( fwrite( buffer, 1, n, fout ) != (size_t) n )
  346. {
  347. mbedtls_fprintf( stderr, "fwrite(%d bytes) failed\n", n );
  348. goto exit;
  349. }
  350. }
  351. /*
  352. * Verify the message authentication code.
  353. */
  354. mbedtls_md_hmac_finish( &sha_ctx, digest );
  355. if( fread( buffer, 1, 32, fin ) != 32 )
  356. {
  357. mbedtls_fprintf( stderr, "fread(%d bytes) failed\n", 32 );
  358. goto exit;
  359. }
  360. /* Use constant-time buffer comparison */
  361. diff = 0;
  362. for( i = 0; i < 32; i++ )
  363. diff |= digest[i] ^ buffer[i];
  364. if( diff != 0 )
  365. {
  366. mbedtls_fprintf( stderr, "HMAC check failed: wrong key, "
  367. "or file corrupted.\n" );
  368. goto exit;
  369. }
  370. }
  371. exit_code = MBEDTLS_EXIT_SUCCESS;
  372. exit:
  373. if( fin )
  374. fclose( fin );
  375. if( fout )
  376. fclose( fout );
  377. /* Zeroize all command line arguments to also cover
  378. the case when the user has missed or reordered some,
  379. in which case the key might not be in argv[4]. */
  380. for( i = 0; i < (unsigned int) argc; i++ )
  381. memset( argv[i], 0, strlen( argv[i] ) );
  382. memset( IV, 0, sizeof( IV ) );
  383. memset( key, 0, sizeof( key ) );
  384. memset( tmp, 0, sizeof( tmp ) );
  385. memset( buffer, 0, sizeof( buffer ) );
  386. memset( digest, 0, sizeof( digest ) );
  387. mbedtls_aes_free( &aes_ctx );
  388. mbedtls_md_free( &sha_ctx );
  389. return( exit_code );
  390. }
  391. #endif /* MBEDTLS_AES_C && MBEDTLS_SHA256_C && MBEDTLS_FS_IO */

使用示例:(注意模式与填充方法,新人经常在这里犯错)

开发过程中的排错方法:

  • 确认双方都是使用AES128对称解密算法
  • 确认双方密钥的正确性,建议统一转化成二进制数据来排查,注意大端/小端问题
  • 确认使用的分组模式一致,使用ECB、CBC模式注意填充方法一致,使用CBC同时要求IV一致
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/325045
推荐阅读
相关标签
  

闽ICP备14008679号