
Small portable AES128/192/256 in C
这是一个用 C 语言编写的小型、可移植的 AES ECB、CTR 和 CBC 加密算法实现。
你可以通过在 aes.h 中定义符号 AES192 或 AES256,将默认的 128 位密钥长度覆盖为 192 位或 256 位。
API 非常简单,如下所示(我使用了 C99 <stdint.h> 风格的注解类型):
/* Initialize context calling one of: */
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
/* ... or reset IV at random point: */
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
/* Then start encrypting and decrypting with the functions below: */
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
/* Same function for encrypting as for decrypting in CTR mode */
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
重要说明:
你可以通过在 aes.h 中定义 CBC、CTR 或 ECB 符号,选择使用任何一种或全部操作模式(请阅读注释以了解详情)。
C++ 用户应 #include aes.hpp 而不是 aes.h。
没有内置的错误检查,也没有针对恶意输入导致的内存越界访问错误的保护。
该模块在为 ARM 编译时使用不到 200 字节的 RAM 和 1-2K 的 ROM,但实际结果可能因启用的模式而异。
这是我所见过的 C 语言实现中体积最小的一种,但如果你知道更小的实现(或对这里的代码有改进),请联系我。
我已经在 64 位 x86、32 位 ARM 和 8 位 AVR 平台上成功使用了该代码。
仅为 ARM 编译 CTR 模式时的 GCC 体积输出:
$ arm-none-eabi-gcc -Os -DCBC=0 -DECB=0 -DCTR=1 -c aes.c
$ size aes.o
text data bss dec hex filename
1171 0 0 1171 493 aes.o
……而针对 THUMB 指令集编译时,代码体积最终远低于 1K。
$ arm-none-eabi-gcc -Os -mthumb -DCBC=0 -DECB=0 -DCTR=1 -c aes.c
$ size aes.o
text data bss dec hex filename
903 0 0 903 387 aes.o
我使用的是自由软件基金会的 ARM GCC 编译器:
$ arm-none-eabi-gcc --version
arm-none-eabi-gcc (4.8.4-1+11-1) 4.8.4 20141219 (release)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
该实现已根据以下文档中的数据进行验证:
美国国家标准与技术研究院特别出版物 800-38A 2001 版 附录 F:AES 操作模式示例向量。
文档中的其他附录对于了解实现细节非常有价值,例如填充、CTR 模式下 IV 和 nonce 的生成等。
衷心感谢所有为此项目做出贡献的好心人。
本仓库中的所有材料均属于公有领域。