我目前正在开发一个项目来解密来自智能电表的字节流,使用带有ESP-IDF工具链的ESP32。 (智能电表规范适用于那些感兴趣的人:P1PortSpecification.pdf,第2.6章第9页)。
我正在使用状态机将流分成文档中的不同部分,当将它们打印到终端时,我得到了预期的结果,所以我认为输入当前是正确的。
到达解密有效载荷的最终状态我不确定我是否正确使用mbedtls库,因为我无法使其正常工作。使用的加密是AES128-GCM,因此我使用gcm.h.这是我目前的功能:
int decrypt_next_telegram(unsigned char *output) {
//Run the state machine, and get pointers to the IV, cipher and length, GCM tag
Encrypted_Data ed = get_next_telegram();
//Key specific to my smart meter I use for testing purposes and the Auth data
const unsigned char key[] = {0xD4, 0x91, 0x47, 0x0F, 0x47, 0x12, 0x63,
0x32, 0xB0, 0x7D, 0x19, 0x23, 0xB3, 0x50, 0x41, 0x88};
const unsigned char aad[] = {0x30, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}
mbedtls_gcm_context ctx;
mbedtls_gcm_init(&ctx);
int err1 = mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key, 128);
int err2 = mbedtls_gcm_auth_decrypt(&ctx, ed.payload_length, ed.initial_value, 12, aad, 17, ed.gcm_tag, 12, ed.payload, output);
mbedtls_gcm_free(&ctx);
return err1 + err2;
}
为了提供Encrypted_Data的更多详细信息:
typedef struct Encrypted_Data Encrypted_Data;
struct Encrypted_Data {
unsigned char * initial_value;
unsigned char * payload;
unsigned int payload_length;
unsigned char * gcm_tag;
};
当两个错误都打印到终端时,我看到err1 = 0和err2 = -0x0012,这是:
#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */
所以我深入研究了gcm.c文件,注意到只有一个地方使用了这个定义(here),但其他东西引起了我的注意。我怀疑这是一个错误,但我无法理解这一部分背后的原因
int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits )
{
int ret;
const mbedtls_cipher_info_t *cipher_info;
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits, MBEDTLS_MODE_ECB );
...
}
找到了here。为什么使用该模式?如果我正在调查cipher_info
的内容,它告诉我它使用MBEDTLS_CIPHER_AES_128_ECB
作为mbedtls_cipher_type_t
,而不是我在第一次MBEDTLS_CIPHER_AES_128_GCM
时所期望的。这是一个问题吗?
总结一下我的主要问题:
mbedtls_cipher_type_t
问题吗?谢谢阅读。
好吧,我找到了解决个人问题的方法。我使用预先录制的电报,我通过USB发送到UART引脚。不幸的是,我的电脑的USB控制器在这里和那里搞砸了。
将电报硬编码到代码中可以很好地工作......