Browse Source

P帧解码

chenzubin 3 months ago
parent
commit
5155fdb9c9
1 changed files with 176 additions and 0 deletions
  1. 176 0
      app/src/main/cpp/PCode.c

+ 176 - 0
app/src/main/cpp/PCode.c

@@ -0,0 +1,176 @@
1
+
2
+#include "mbedtls/cipher.h"
3
+#include "mbedtls/entropy.h"
4
+#include "mbedtls/ctr_drbg.h"
5
+
6
+#include <stdio.h>
7
+#include <string.h>
8
+
9
+static void print_hex(const char *title, const unsigned char buf[], size_t len)
10
+{
11
+    printf("%s: ", title);
12
+    for (size_t i = 0; i < len; i++)
13
+        printf("%02x", buf[i]);
14
+
15
+    printf("\r\n");
16
+}
17
+
18
+/*
19
+ * The pre-shared key. Should be generated randomly and be unique to the
20
+ * device/channel/etc. Just used a fixed on here for simplicity.
21
+ */
22
+static const unsigned char secret_key[16] = {
23
+        0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
24
+        0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
25
+};
26
+
27
+static int pcode(void)
28
+{
29
+    /* message that should be protected */
30
+    const char message[] = "Some things are better left unread";
31
+    /* metadata transmitted in the clear but authenticated */
32
+    const char metadata[] = "eg sequence number, routing info";
33
+    /* ciphertext buffer large enough to hold message + nonce + tag */
34
+    unsigned char ciphertext[128] = { 0 };
35
+    int ret;
36
+
37
+    printf("\r\n\r\n");
38
+    print_hex("plaintext message", (unsigned char *) message, sizeof message);
39
+
40
+    /*
41
+     * Setup random number generator
42
+     * (Note: later this might be done automatically.)
43
+     */
44
+    mbedtls_entropy_context entropy;    /* entropy pool for seeding PRNG */
45
+    mbedtls_ctr_drbg_context drbg;      /* pseudo-random generator */
46
+
47
+    mbedtls_entropy_init(&entropy);
48
+    mbedtls_ctr_drbg_init(&drbg);
49
+
50
+    /* Seed the PRNG using the entropy pool, and throw in our secret key as an
51
+     * additional source of randomness. */
52
+    ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
53
+                                secret_key, sizeof (secret_key));
54
+    if (ret != 0) {
55
+        printf("mbedtls_ctr_drbg_init() returned -0x%04X\r\n", -ret);
56
+        return 1;
57
+    }
58
+
59
+    /*
60
+     * Setup AES-CCM contex
61
+     */
62
+    mbedtls_cipher_context_t ctx;
63
+
64
+    mbedtls_cipher_init(&ctx);
65
+
66
+    ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
67
+    if (ret != 0) {
68
+        printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
69
+        return 1;
70
+    }
71
+
72
+    ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
73
+    if (ret != 0) {
74
+        printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
75
+        return 1;
76
+    }
77
+
78
+    /*
79
+     * Encrypt-authenticate the message and authenticate additional data
80
+     *
81
+     * First generate a random 8-byte nonce.
82
+     * Put it directly in the output buffer as the recipient will need it.
83
+     *
84
+     * Warning: you must never re-use the same (key, nonce) pair. One of the
85
+     * best ways to ensure this to use a counter for the nonce. However this
86
+     * means you should save the counter accross rebots, if the key is a
87
+     * long-term one. The alternative we choose here is to generate the nonce
88
+     * randomly. However it only works if you have a good source of
89
+     * randomness.
90
+     */
91
+    const size_t nonce_len = 8;
92
+    mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
93
+
94
+    size_t ciphertext_len = 0;
95
+    /* Go for a conservative 16-byte (128-bit) tag
96
+     * and append it to the ciphertext */
97
+    const size_t tag_len = 16;
98
+    ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
99
+                                      (const unsigned char *) metadata, sizeof metadata,
100
+                                      (const unsigned char *) message, sizeof message,
101
+                                      ciphertext + nonce_len, &ciphertext_len,
102
+                                      ciphertext + nonce_len + sizeof message, tag_len );
103
+    if (ret != 0) {
104
+        printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
105
+        return 1;
106
+    }
107
+    ciphertext_len += nonce_len + tag_len;
108
+
109
+    /*
110
+     * The following information should now be transmitted:
111
+     * - first ciphertext_len bytes of ciphertext buffer
112
+     * - metadata if not already transmitted elsewhere
113
+     */
114
+    print_hex("ciphertext", ciphertext, ciphertext_len);
115
+
116
+    /*
117
+     * Decrypt-authenticate
118
+     */
119
+    unsigned char decrypted[128] = { 0 };
120
+    size_t decrypted_len = 0;
121
+
122
+    ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
123
+    if (ret != 0) {
124
+        printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
125
+        return 1;
126
+    }
127
+
128
+    ret = mbedtls_cipher_auth_decrypt(&ctx,
129
+                                      ciphertext, nonce_len,
130
+                                      (const unsigned char *) metadata, sizeof metadata,
131
+                                      ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
132
+                                      decrypted, &decrypted_len,
133
+                                      ciphertext + ciphertext_len - tag_len, tag_len );
134
+    /* Checking the return code is CRITICAL for security here */
135
+    if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
136
+        printf("Something bad is happening! Data is not authentic!\r\n");
137
+        return 1;
138
+    }
139
+    if (ret != 0) {
140
+        printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
141
+        return 1;
142
+    }
143
+
144
+    print_hex("decrypted", decrypted, decrypted_len);
145
+
146
+    printf("\r\nDONE\r\n");
147
+
148
+    return 0;
149
+}
150
+
151
+#if defined(TARGET_LIKE_MBED)
152
+
153
+#include "mbed-drivers/test_env.h"
154
+#include "minar/minar.h"
155
+
156
+static void run() {
157
+    MBED_HOSTTEST_TIMEOUT(10);
158
+    MBED_HOSTTEST_SELECT(default);
159
+    MBED_HOSTTEST_DESCRIPTION(mbed TLS example authcrypt);
160
+    MBED_HOSTTEST_START("MBEDTLS_EX_AUTHCRYPT");
161
+    MBED_HOSTTEST_RESULT(example() == 0);
162
+}
163
+
164
+void app_start(int, char*[]) {
165
+    /* Use 115200 bps for consistency with other examples */
166
+    get_stdio_serial().baud(115200);
167
+    minar::Scheduler::postCallback(mbed::util::FunctionPointer0<void>(run).bind());
168
+}
169
+
170
+#else
171
+
172
+int main() {
173
+    return example();
174
+}
175
+
176
+#endif