lr1120 0.5.0

Driver for Semtech LR1120
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Crypto commands API

use crate::status::Status;

/// Key identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum KeyId {
    Nwk = 2,
    App = 3,
    JsEnc = 4,
    JsInt = 5,
    GpKe0 = 6,
    GpKe1 = 7,
    GpKe2 = 8,
    GpKe3 = 9,
    GpKe4 = 10,
    GpKe5 = 11,
    AppS = 12,
    FNwkSInt = 13,
    SNwkSInt = 14,
    NwkSEnc = 15,
    Rfu0 = 16,
    Rfu1 = 17,
    McAppS0 = 18,
    McAppS1 = 19,
    McAppS2 = 20,
    McAppS3 = 21,
    McNwkS0 = 22,
    McNwkS1 = 23,
    McNwkS2 = 24,
    McNwkS3 = 25,
    Gp0 = 26,
    Gp1 = 27,
}

impl KeyId {
    /// True when key is Network or application
    pub fn is_core(&self) -> bool {
        matches!(self, KeyId::Nwk|KeyId::App)
    }

    /// True when key is Lifetime
    pub fn is_lifetime(&self) -> bool {
        matches!(self, KeyId::JsEnc|KeyId::JsInt)
    }

    /// True when key is multicast
    pub fn is_multicast(&self) -> bool {
        matches!(self, KeyId::McAppS0|KeyId::McAppS1|KeyId::McAppS2|KeyId::McAppS3|KeyId::McNwkS0|KeyId::McNwkS1|KeyId::McNwkS2|KeyId::McNwkS3)
    }

    /// True when key is general purpose transport
    pub fn is_gp_transport(&self) -> bool {
        matches!(self, KeyId::GpKe0|KeyId::GpKe1|KeyId::GpKe2|KeyId::GpKe3|KeyId::GpKe4|KeyId::GpKe5)
    }

    /// True when key is unicast
    pub fn is_unicast(&self) -> bool {
        matches!(self, KeyId::AppS|KeyId::FNwkSInt|KeyId::SNwkSInt|KeyId::NwkSEnc|KeyId::Rfu0|KeyId::Rfu1)
    }

    /// True when key is general purpose
    pub fn is_gp(&self) -> bool {
        matches!(self, KeyId::Gp0|KeyId::Gp1)
    }
}

/// Crypto Engine status
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum CeStatus {
    Success = 0,
    FailCmac = 1,
    InvKeyId = 3,
    BufSize = 5,
    Error = 6,
}

impl From<u8> for CeStatus {
    fn from(value: u8) -> Self {
        match value {
            6 => CeStatus::Error,
            5 => CeStatus::BufSize,
            3 => CeStatus::InvKeyId,
            1 => CeStatus::FailCmac,
            _ => CeStatus::Success,
        }
    }
}

/// Determines Header size: - LoRaWAN 1.0: 1 byte MHDR - LoRaWAN 1.1: 12 bytes with SIntKey, JoinReqType, JoinEUI, DevNonce, MHDR
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum LorawanVersion {
    V1p0 = 0,
    V1p1 = 1,
}

/// Sets a specific Key identified by KeyID into Crypto Engine. Key is 16-byte AES-128 key as defined in FIPS-197.
pub fn crypto_set_key_req(key_id: KeyId, key: u128) -> [u8; 19] {
    let mut cmd = [0u8; 19];
    cmd[0] = 0x05;
    cmd[1] = 0x02;

    cmd[2] |= key_id as u8;
    cmd[3] |= ((key >> 120) & 0xFF) as u8;
    cmd[4] |= ((key >> 112) & 0xFF) as u8;
    cmd[5] |= ((key >> 104) & 0xFF) as u8;
    cmd[6] |= ((key >> 96) & 0xFF) as u8;
    cmd[7] |= ((key >> 88) & 0xFF) as u8;
    cmd[8] |= ((key >> 80) & 0xFF) as u8;
    cmd[9] |= ((key >> 72) & 0xFF) as u8;
    cmd[10] |= ((key >> 64) & 0xFF) as u8;
    cmd[11] |= ((key >> 56) & 0xFF) as u8;
    cmd[12] |= ((key >> 48) & 0xFF) as u8;
    cmd[13] |= ((key >> 40) & 0xFF) as u8;
    cmd[14] |= ((key >> 32) & 0xFF) as u8;
    cmd[15] |= ((key >> 24) & 0xFF) as u8;
    cmd[16] |= ((key >> 16) & 0xFF) as u8;
    cmd[17] |= ((key >> 8) & 0xFF) as u8;
    cmd[18] |= (key & 0xFF) as u8;
    cmd
}

/// Derives (encrypts) input value into destination Key using source Key. Generated key stored in Crypto Engine RAM - use CryptoStoreToFlash to persist. See LoRaWAN key derivation schemes in Ch 16.3-16.4.
pub fn crypto_derive_key_req(src_key_id: KeyId, dst_key_id: KeyId, input: u128) -> [u8; 20] {
    let mut cmd = [0u8; 20];
    cmd[0] = 0x05;
    cmd[1] = 0x03;

    cmd[2] |= src_key_id as u8;
    cmd[3] |= dst_key_id as u8;
    cmd[4] |= ((input >> 120) & 0xFF) as u8;
    cmd[5] |= ((input >> 112) & 0xFF) as u8;
    cmd[6] |= ((input >> 104) & 0xFF) as u8;
    cmd[7] |= ((input >> 96) & 0xFF) as u8;
    cmd[8] |= ((input >> 88) & 0xFF) as u8;
    cmd[9] |= ((input >> 80) & 0xFF) as u8;
    cmd[10] |= ((input >> 72) & 0xFF) as u8;
    cmd[11] |= ((input >> 64) & 0xFF) as u8;
    cmd[12] |= ((input >> 56) & 0xFF) as u8;
    cmd[13] |= ((input >> 48) & 0xFF) as u8;
    cmd[14] |= ((input >> 40) & 0xFF) as u8;
    cmd[15] |= ((input >> 32) & 0xFF) as u8;
    cmd[16] |= ((input >> 24) & 0xFF) as u8;
    cmd[17] |= ((input >> 16) & 0xFF) as u8;
    cmd[18] |= ((input >> 8) & 0xFF) as u8;
    cmd[19] |= (input & 0xFF) as u8;
    cmd
}

/// Decrypts join accept message (using AES-ECB encrypt per LoRaWAN spec) on Data and Header, then verifies MIC. Returns decrypted data if MIC verification successful.
pub fn crypto_process_join_accept_req(dec_key_id: KeyId, ver_key_id: KeyId, lorawan_version: LorawanVersion) -> [u8; 5] {
    let mut cmd = [0u8; 5];
    cmd[0] = 0x05;
    cmd[1] = 0x04;

    cmd[2] |= dec_key_id as u8;
    cmd[3] |= ver_key_id as u8;
    cmd[4] |= lorawan_version as u8;
    cmd
}

/// Computes AES CMAC of provided data using specified Key and returns MIC (first 4 bytes of CMAC). Maximum data size 256 bytes.
pub fn crypto_compute_aes_cmac_req(key_id: KeyId) -> [u8; 3] {
    let mut cmd = [0u8; 3];
    cmd[0] = 0x05;
    cmd[1] = 0x05;

    cmd[2] |= key_id as u8;
    cmd
}

/// Computes AES CMAC of provided data using specified Key and compares with provided MIC. Returns SUCCESS if MICs match, FAIL_CMAC otherwise. Maximum data size 256 bytes.
pub fn crypto_verify_aes_cmac_req(key_id: KeyId, expected_mic: u32) -> [u8; 7] {
    let mut cmd = [0u8; 7];
    cmd[0] = 0x05;
    cmd[1] = 0x06;

    cmd[2] |= key_id as u8;
    cmd[3] |= ((expected_mic >> 24) & 0xFF) as u8;
    cmd[4] |= ((expected_mic >> 16) & 0xFF) as u8;
    cmd[5] |= ((expected_mic >> 8) & 0xFF) as u8;
    cmd[6] |= (expected_mic & 0xFF) as u8;
    cmd
}

/// Encrypts provided data using specified Key and returns encrypted data. Cannot be used on key indexes 2-11 (prevents re-calculating session keys). For LoRaWAN encryption operations.
pub fn crypto_aes_encrypt01_req(key_id: KeyId) -> [u8; 3] {
    let mut cmd = [0u8; 3];
    cmd[0] = 0x05;
    cmd[1] = 0x07;

    cmd[2] |= key_id as u8;
    cmd
}

/// Encrypts provided data using specified Key and returns encrypted data. For generic non-LoRaWAN operations using Crypto Engine as hardware accelerator. Only for General Purpose keys (26-27).
pub fn crypto_aes_encrypt_req(key_id: KeyId) -> [u8; 3] {
    let mut cmd = [0u8; 3];
    cmd[0] = 0x05;
    cmd[1] = 0x08;

    cmd[2] |= key_id as u8;
    cmd
}

/// Decrypts provided data using specified Key and returns decrypted data. For non-LoRaWAN security tasks using Crypto Engine as standalone hardware accelerator.
pub fn crypto_aes_decrypt_req(key_id: KeyId) -> [u8; 3] {
    let mut cmd = [0u8; 3];
    cmd[0] = 0x05;
    cmd[1] = 0x09;

    cmd[2] |= key_id as u8;
    cmd
}

/// Stores all Keys and Parameters from Crypto Engine RAM into flash memory for persistence
pub fn crypto_store_to_flash_req() -> [u8; 2] {
    [0x05, 0x0A]
}

/// Restores all Keys and Parameters from flash memory into Crypto Engine RAM
pub fn crypto_restore_from_flash_req() -> [u8; 2] {
    [0x05, 0x0B]
}

/// Sets a specific Parameter into Crypto Engine RAM
pub fn crypto_set_param_req(param_id: u8, data: u32) -> [u8; 7] {
    let mut cmd = [0u8; 7];
    cmd[0] = 0x05;
    cmd[1] = 0x0D;

    cmd[2] |= param_id;
    cmd[3] |= ((data >> 24) & 0xFF) as u8;
    cmd[4] |= ((data >> 16) & 0xFF) as u8;
    cmd[5] |= ((data >> 8) & 0xFF) as u8;
    cmd[6] |= (data & 0xFF) as u8;
    cmd
}

/// Gets a specific Parameter from Crypto Engine RAM
pub fn crypto_get_param_req(param_id: u8) -> [u8; 3] {
    let mut cmd = [0u8; 3];
    cmd[0] = 0x05;
    cmd[1] = 0x0E;

    cmd[2] |= param_id;
    cmd
}

/// Adds a chunk to encrypted firmware image to be checked. Call multiple times until complete image sent. Takes max 64x32-bit words (256 bytes) per call, except last segment may be shorter. BUSY released when ready for next chunk. Call CryptoCheckEncryptedFirmwareImageResult to get final result.
pub fn crypto_check_encrypted_firmware_image_cmd(offset: u32) -> [u8; 6] {
    let mut cmd = [0u8; 6];
    cmd[0] = 0x05;
    cmd[1] = 0x0F;

    cmd[2] |= ((offset >> 24) & 0xFF) as u8;
    cmd[3] |= ((offset >> 16) & 0xFF) as u8;
    cmd[4] |= ((offset >> 8) & 0xFF) as u8;
    cmd[5] |= (offset & 0xFF) as u8;
    cmd
}

/// Gets result of encrypted firmware image check after all chunks sent via CryptoCheckEncryptedFirmwareImage
pub fn crypto_check_encrypted_firmware_image_result_req() -> [u8; 2] {
    [0x05, 0x10]
}

// Response structs

/// Response for CryptoSetKey command
#[derive(Default)]
pub struct CryptoSetKeyRsp([u8; 2]);

impl CryptoSetKeyRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoSetKeyRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoDeriveKey command
#[derive(Default)]
pub struct CryptoDeriveKeyRsp([u8; 2]);

impl CryptoDeriveKeyRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoDeriveKeyRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoProcessJoinAccept command
#[derive(Default)]
pub struct CryptoProcessJoinAcceptRsp([u8; 2]);

impl CryptoProcessJoinAcceptRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoProcessJoinAcceptRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoComputeAesCmac command
#[derive(Default)]
pub struct CryptoComputeAesCmacRsp([u8; 6]);

impl CryptoComputeAesCmacRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }

    /// Message Integrity Check (first 4 bytes of CMAC)
    pub fn mic(&self) -> u32 {
        (self.0[5] as u32) |
        ((self.0[4] as u32) << 8) |
        ((self.0[3] as u32) << 16) |
        ((self.0[2] as u32) << 24)
    }
}

impl AsMut<[u8]> for CryptoComputeAesCmacRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoVerifyAesCmac command
#[derive(Default)]
pub struct CryptoVerifyAesCmacRsp([u8; 2]);

impl CryptoVerifyAesCmacRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoVerifyAesCmacRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoAesEncrypt01 command
#[derive(Default)]
pub struct CryptoAesEncrypt01Rsp([u8; 2]);

impl CryptoAesEncrypt01Rsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoAesEncrypt01Rsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoAesEncrypt command
#[derive(Default)]
pub struct CryptoAesEncryptRsp([u8; 2]);

impl CryptoAesEncryptRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoAesEncryptRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoAesDecrypt command
#[derive(Default)]
pub struct CryptoAesDecryptRsp([u8; 2]);

impl CryptoAesDecryptRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoAesDecryptRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoStoreToFlash command
#[derive(Default)]
pub struct CryptoStoreToFlashRsp([u8; 2]);

impl CryptoStoreToFlashRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoStoreToFlashRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoRestoreFromFlash command
#[derive(Default)]
pub struct CryptoRestoreFromFlashRsp([u8; 2]);

impl CryptoRestoreFromFlashRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoRestoreFromFlashRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoSetParam command
#[derive(Default)]
pub struct CryptoSetParamRsp([u8; 2]);

impl CryptoSetParamRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }
}

impl AsMut<[u8]> for CryptoSetParamRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoGetParam command
#[derive(Default)]
pub struct CryptoGetParamRsp([u8; 6]);

impl CryptoGetParamRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Crypto Engine status
    pub fn ce_status(&self) -> CeStatus {
        self.0[1].into()
    }

    /// Parameter data (32-bit)
    pub fn data(&self) -> u32 {
        (self.0[5] as u32) |
        ((self.0[4] as u32) << 8) |
        ((self.0[3] as u32) << 16) |
        ((self.0[2] as u32) << 24)
    }
}

impl AsMut<[u8]> for CryptoGetParamRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

/// Response for CryptoCheckEncryptedFirmwareImageResult command
#[derive(Default)]
pub struct CryptoCheckEncryptedFirmwareImageResultRsp([u8; 2]);

impl CryptoCheckEncryptedFirmwareImageResultRsp {
    /// Create a new response buffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Return Status
    pub fn status(&mut self) -> Status {
        self.0[0].into()
    }

    /// Firmware verification result: 0: Verification error, 1: Verification success
    pub fn success(&self) -> bool {
        self.0[1] & 0x1 != 0
    }
}

impl AsMut<[u8]> for CryptoCheckEncryptedFirmwareImageResultRsp {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}