Subversion Repositories ESP8266_P1_Meter

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 raymond 1
#pragma once
2
 
3
#if defined(ESP8266)
4
#include <bearssl/bearssl.h>
5
#include <stdint.h>
6
#include <stddef.h>
7
#include <string.h>
8
 
9
#ifdef __cplusplus
10
extern "C" {
11
#endif
12
 
13
#define MBEDTLS_AES_ENCRYPT 1
14
#define MBEDTLS_AES_DECRYPT 0
15
 
16
typedef struct {
17
    br_aes_ct_cbcenc_keys enc;
18
    br_aes_ct_cbcdec_keys dec;
19
    uint8_t has_enc;
20
    uint8_t has_dec;
21
} mbedtls_aes_context;
22
 
23
static inline void mbedtls_aes_init(mbedtls_aes_context *ctx) {
24
    if (ctx) {
25
        memset(ctx, 0, sizeof(*ctx));
26
    }
27
}
28
 
29
static inline void mbedtls_aes_free(mbedtls_aes_context *ctx) {
30
    (void)ctx;
31
}
32
 
33
static inline int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) {
34
    if (!ctx || !key || (keybits % 8) != 0) {
35
        return -1;
36
    }
37
    br_aes_ct_cbcenc_init(&ctx->enc, key, keybits / 8);
38
    ctx->has_enc = 1;
39
    return 0;
40
}
41
 
42
static inline int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) {
43
    if (!ctx || !key || (keybits % 8) != 0) {
44
        return -1;
45
    }
46
    br_aes_ct_cbcdec_init(&ctx->dec, key, keybits / 8);
47
    ctx->has_dec = 1;
48
    return 0;
49
}
50
 
51
static inline int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx, int mode, size_t length,
52
                                       unsigned char iv[16], const unsigned char *input, unsigned char *output) {
53
    if (!ctx || !iv || !input || !output) {
54
        return -1;
55
    }
56
    if (length % 16 != 0) {
57
        return -1;
58
    }
59
 
60
    if (input != output) {
61
        memcpy(output, input, length);
62
    }
63
 
64
    if (mode == MBEDTLS_AES_ENCRYPT) {
65
        if (!ctx->has_enc) {
66
            return -1;
67
        }
68
        br_aes_ct_cbcenc_run(&ctx->enc, iv, output, length);
69
        return 0;
70
    }
71
 
72
    if (mode == MBEDTLS_AES_DECRYPT) {
73
        if (!ctx->has_dec) {
74
            return -1;
75
        }
76
        br_aes_ct_cbcdec_run(&ctx->dec, iv, output, length);
77
        return 0;
78
    }
79
 
80
    return -1;
81
}
82
 
83
#ifdef __cplusplus
84
}
85
#endif
86
 
87
#else
88
#include_next <mbedtls/aes.h>
89
#endif