You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求ESP8266 AES128 CBC零填充解密代码技术支持

ESP8266上AES-128-CBC零填充解密实现

以下是基于Arduino框架的ESP8266解密代码,使用内置BearSSL库实现AES-128-CBC解密,同时处理Base64编码密文和零填充:

#include <BearSSL.h>
#include <base64.h>

// 定义密钥、IV和Base64编码密文
const uint8_t aesKey[] = "aaaaaaaaaaaaaaaa"; // 16字节AES-128密钥
const uint8_t aesIV[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // 16字节全0IV
const char* encryptedBase64 = "o9MfCaefrs8pM8zQqyQ2mQ==";

void setup() {
  Serial.begin(115200);
  while (!Serial);

  // 1. Base64解码密文为字节数组
  size_t encryptedLen = base64_dec_len(encryptedBase64, strlen(encryptedBase64));
  uint8_t encryptedData[encryptedLen];
  base64_decode(encryptedData, encryptedBase64, strlen(encryptedBase64));

  // 2. 初始化AES-128-CBC解密器
  BearSSL::AES aes;
  aes.setKey(aesKey, sizeof(aesKey), BearSSL::AES::MODE_DECRYPT);
  aes.setIV(aesIV);

  // 3. 执行CBC解密
  uint8_t decryptedData[encryptedLen];
  aes.CBC_decrypt(decryptedData, encryptedData, encryptedLen);

  // 4. 移除零填充:去掉末尾的填充0
  size_t plaintextLen = encryptedLen;
  while (plaintextLen > 0 && decryptedData[plaintextLen - 1] == 0x00) {
    plaintextLen--;
  }

  // 5. 输出明文
  Serial.print("解密后的明文: ");
  Serial.write(decryptedData, plaintextLen);
  Serial.println();
}

void loop() {
  // 无需循环操作
}

关键说明:

  • Base64解码:用ESP8266内置base64库将Base64密文转成字节数组,这是AES解密的前置步骤。
  • AES配置:BearSSL的AES类支持直接配置解密模式、密钥和IV,AES-128要求密钥和IV必须是16字节长度。
  • CBC解密:调用CBC_decrypt完成解密,输出数据长度与密文一致。
  • 零填充处理:零填充会在明文末尾补0至16字节整数倍,解密后需移除这些填充0才能得到原始明文。

使用注意:

  1. 确保Arduino IDE中已正确安装ESP8266开发板支持包。
  2. 代码无需额外安装第三方加密库,直接编译运行即可。

内容的提问来源于stack exchange,提问作者Knowledge Seeker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:42:11