forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MifareCard.cs
1335 lines (1173 loc) · 51.6 KB
/
MifareCard.cs
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Iot.Device.Ndef;
#if DEBUG
using Microsoft.Extensions.Logging;
using nanoFramework.Logging;
#endif
namespace Iot.Device.Card.Mifare
{
/// <summary>
/// A Mifare card class
/// Supports Mifare Classic 1K and 4K
/// Also supports Mifare Plus 2K and 4K operating in SL1
/// </summary>
public class MifareCard
{
private const byte BytesPerBlock = 16;
private const byte BlocksPerSmallSector = 4;
private const byte BlocksPerLargeSector = 16;
private const byte NumberOfSmallSectors = 32;
private static readonly byte[] Mifare1KBlock1 = new byte[] { 0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1 };
private static readonly byte[] Mifare1KBlock2 = new byte[] { 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1 };
private static readonly byte[] Mifare1KBlock4 = new byte[] { 0x03, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private static readonly byte[] Mifare2KBlock64 = new byte[] { 0xBE, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1 };
private static readonly byte[] Mifare2KBlock66 = new byte[] { 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05, 0x00, 0x05 };
private static readonly byte[] Mifare4KBlock64 = new byte[] { 0xE8, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1 };
private static readonly byte[] StaticDefaultKeyA = new byte[6] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private static readonly byte[] StaticDefaultKeyB = new byte[6] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
private static readonly byte[] StaticDefaultFirstBlockNdefKeyA = new byte[6] { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 };
private static readonly byte[] StaticDefaultBlocksNdefKeyA = new byte[6] { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
// This is the actual RFID reader
private readonly CardTransceiver _rfid;
#if DEBUG
private readonly ILogger _logger;
#endif
/// <summary>
/// Default Key A
/// </summary>
public static SpanByte DefaultKeyA => StaticDefaultKeyA;
/// <summary>
/// Default Key B
/// </summary>
public static SpanByte DefaultKeyB => StaticDefaultKeyB;
/// <summary>
/// Default Mifare Application Directory block Key A for NDEF card
/// The MAD is in the first sector on all cards and also sector 16 on 2K and 4K cards
/// </summary>
/// <remarks>See https://www.nxp.com/docs/en/application-note/AN10787.pdf for more information</remarks>
public static SpanByte DefaultFirstBlockNdefKeyA => StaticDefaultFirstBlockNdefKeyA;
/// <summary>
/// Default block Key A for NDEF card
/// </summary>
/// <remarks>See https://www.nxp.com/docs/en/application-note/AN10787.pdf for more information</remarks>
public static SpanByte DefaultBlocksNdefKeyA => StaticDefaultBlocksNdefKeyA;
/// <summary>
/// The tag number detected by the reader, only 1 or 2
/// </summary>
public byte Target { get; set; }
/// <summary>
/// The command to execute on the card
/// </summary>
public MifareCardCommand Command { get; set; }
/// <summary>
/// Key A Used for encryption/decryption
/// </summary>
public byte[]? KeyA { get; set; }
/// <summary>
/// Key B Used for encryption/decryption
/// </summary>
public byte[]? KeyB { get; set; }
/// <summary>
/// UUID is the Serial Number, called MAC sometimes
/// </summary>
public byte[]? SerialNumber { get; set; }
/// <summary>
/// The storage capacity
/// </summary>
public MifareCardCapacity Capacity { get; set; }
/// <summary>
/// The block number to authenticate or read or write
/// </summary>
public byte BlockNumber { get; set; }
/// <summary>
/// The Data which has been read or to write for the specific block
/// </summary>
public byte[] Data { get; set; } = new byte[0];
/// <summary>
/// Determine the block group corresponding to a block number
/// </summary>
/// <param name="blockNumber">block number</param>
/// <returns>block group</returns>
/// In a 1K card there are 16 sectors, each containing four blocks.
/// In a 2K card there are 32 sectors, each containing four blocks.
/// In a 4K card there are four blocks in the first 32 sectors and 16 blocks in the remaining sectors.
/// There are three groups of data blocks (either 1 or 5 blocks per group).
/// The last block in the sector is the sector trailer.
public static byte BlockNumberToBlockGroup(byte blockNumber) =>
(byte)((blockNumber < 128) ? (blockNumber % 4) : (blockNumber % 16) / 5);
/// <summary>
/// Determine the sector number corresponding to a particular block number
/// </summary>
/// <param name="blockNumber">block number</param>
/// <returns>sector number</returns>
public static byte BlockNumberToSector(byte blockNumber) =>
(byte)((blockNumber < 128) ? blockNumber / 4 : 32 + (blockNumber - 128) / 16);
/// <summary>
/// Determine the first block number of a specified sector and block group
/// </summary>
/// <param name="sector">sector number</param>
/// <param name="group">group (0 to 3, where 3 is the sector trailer)</param>
/// <returns>block number of the first (or only) block in the group</returns>
public static byte SectorToBlockNumber(byte sector, byte group = 0) =>
(byte)((sector < 32) ? sector * 4 + group : 128 + (sector - 32) * 16 + group * 5);
/// <summary>
/// Constructor for Mifarecard
/// </summary>
/// <param name="rfid">A card transceiver class</param>
/// <param name="target">The target number as some card readers attribute one</param>
public MifareCard(CardTransceiver rfid, byte target)
{
_rfid = rfid;
Target = target;
#if DEBUG
_logger = this.GetCurrentClassLogger();
#endif
}
/// <summary>
/// Run the last setup command. In case of reading bytes, they are automatically pushed into the Data property
/// </summary>
/// <returns>-1 if the process fails otherwise the number of bytes read</returns>
public int RunMifareCardCommand()
{
byte[] dataOut = new byte[0];
if (Command == MifareCardCommand.Read16Bytes)
{
dataOut = new byte[16];
}
var ret = _rfid.Transceive(Target, Serialize(), dataOut);
#if DEBUG
_logger.LogDebug($"{nameof(RunMifareCardCommand)}: {Command}, Target: {Target}, Data: {BitConverter.ToString(Serialize())}, Success: {ret}, Dataout: {BitConverter.ToString(dataOut)}");
#endif
if ((ret > 0) && (Command == MifareCardCommand.Read16Bytes))
{
Data = dataOut;
}
return ret;
}
#region Sector Tailer and Access Type
private Sixtet DecodeSectorTailer(byte blockGroup, byte[] sectorData)
{
// Bit 7 6 5 4 3 2 1 0
// Byte 6 !C23 !C22 !C21 !C20 !C13 !C12 !C11 !C10
// Byte 7 C13 C12 C11 C10 !C33 !C32 !C31 !C30
// Byte 8 C33 C32 C31 C30 C23 C22 C21 C20
// Cab a = access bit and b = block number
// Extract the C1
byte c1a = (byte)((~(sectorData[6]) >> blockGroup) & 0b0000_0001);
byte c1b = (byte)((sectorData[7] >> (4 + blockGroup)) & 0b0000_0001);
// Extract the C2
byte c2a = (byte)((sectorData[8] >> blockGroup) & 0b0000_0001);
byte c2b = (byte)((~(sectorData[6]) >> (4 + blockGroup)) & 0b0000_0001);
// Extract the C3
byte c3a = (byte)((~(sectorData[7]) >> blockGroup) & 0b0000_0001);
byte c3b = (byte)((sectorData[8] >> (4 + blockGroup)) & 0b0000_0001);
return new Sixtet(c1a, c1b, c2a, c2b, c3a, c3b);
}
/// <summary>
/// Get the sector tailer bytes for a specific access sector configuration
/// </summary>
/// <param name="accessSector">the access sector</param>
/// <returns>the 3 bytes for configuration</returns>
public Triplet EncodeSectorTailer(AccessSector accessSector)
{
byte c1 = 0;
byte c2 = 0;
byte c3 = 0;
// Ignore AccessSector.KeyBRead
accessSector = accessSector & ~AccessSector.ReadKeyB;
// Find the table of truth and the core Access Bits
if (accessSector == (AccessSector.WriteKeyAWithKeyA | AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA |
AccessSector.WriteKeyBWithKeyA))
{
c1 = 0;
c2 = 0;
c3 = 0;
}
if (accessSector == (AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA))
{
c1 = 0;
c2 = 1;
c3 = 0;
}
if (accessSector == (AccessSector.WriteKeyAWithKeyB | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteKeyBWithKeyB))
{
c1 = 1;
c2 = 0;
c3 = 0;
}
if (accessSector == (AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadAccessBitsWithKeyB))
{
c1 = 1;
c2 = 1;
c3 = 0;
}
if (accessSector == (AccessSector.WriteKeyAWithKeyA | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.WriteAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA |
AccessSector.WriteKeyBWithKeyA))
{
c1 = 0;
c2 = 0;
c3 = 1;
}
if (accessSector == (AccessSector.WriteKeyAWithKeyB | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteAccessBitsWithKeyB |
AccessSector.WriteKeyBWithKeyB))
{
c1 = 0;
c2 = 1;
c3 = 1;
}
if (accessSector == (AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteAccessBitsWithKeyB))
{
c1 = 1;
c2 = 0;
c3 = 1;
}
if (accessSector == (AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB))
{
c1 = 1;
c2 = 1;
c3 = 1;
}
// Encode the into the 3 bytes
byte b6 = (byte)((((~c2) & 0x01) << 7) | (((~c1) & 0x01) << 3));
byte b7 = (byte)(((c1) << 7) | (((~c3) & 0x01) << 3));
byte b8 = (byte)(((c3) << 7) | ((c2) << 3));
return new Triplet(b6, b7, b8);
}
/// <summary>
/// Encode the sector tailer access type for a specific block
/// </summary>
/// <param name="blockNumber">The block sector to encode</param>
/// <param name="accessType">The access type to encode</param>
/// <returns>The encoded sector tailer for the specific block</returns>
public Triplet EncodeSectorTailer(byte blockNumber, AccessType accessType)
{
byte blockGroup = BlockNumberToBlockGroup(blockNumber);
byte c1 = 0;
byte c2 = 0;
byte c3 = 0;
if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyA | AccessType.WriteKeyB |
AccessType.IncrementKeyA | AccessType.IncrementKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
{
c1 = 0;
c2 = 0;
c3 = 0;
}
if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB))
{
c1 = 0;
c2 = 1;
c3 = 0;
}
if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB))
{
c1 = 1;
c2 = 0;
c3 = 0;
}
if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB |
AccessType.IncrementKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
{
c1 = 1;
c2 = 1;
c3 = 0;
}
if (accessType == (AccessType.ReadKeyA | AccessType.ReadKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB))
{
c1 = 0;
c2 = 0;
c3 = 1;
}
if (accessType == (AccessType.ReadKeyB | AccessType.WriteKeyB))
{
c1 = 0;
c2 = 1;
c3 = 1;
}
if (accessType == AccessType.ReadKeyB)
{
c1 = 1;
c2 = 0;
c3 = 1;
}
if (accessType == AccessType.None)
{
c1 = 1;
c2 = 1;
c3 = 1;
}
// Encore the access bits
byte b6 = (byte)((((~c2) & 0x01) << (4 + blockGroup)) | (((~c1) & 0x01) << blockGroup));
byte b7 = (byte)(((c1) << (4 + blockGroup)) | (((~c3) & 0x01) << blockGroup));
byte b8 = (byte)(((c3) << (4 + blockGroup)) | ((c2) << blockGroup));
return new Triplet(b6, b7, b8);
}
/// <summary>
/// Get the sector tailer access information
/// </summary>
/// <param name="blockNumber">the block sector number</param>
/// <param name="sectorData">The full sector data to decode</param>
/// <returns>the access sector rights</returns>
public AccessSector SectorTailerAccess(byte blockNumber, byte[] sectorData)
{
// Bit 7 6 5 4 3 2 1 0
// Byte 6 !C23 !C22 !C21 !C20 !C13 !C12 !C11 !C10
// Byte 7 C13 C12 C11 C10 !C33 !C32 !C31 !C30
// Byte 8 C33 C32 C31 C30 C23 C22 C21 C20
// Cab a = access bit and b = block number
byte blockGroup = BlockNumberToBlockGroup(blockNumber);
if (blockGroup != 3)
{
return AccessSector.None;
}
var sixtet = DecodeSectorTailer(blockGroup, sectorData);
if (sixtet.C1a != sixtet.C1b)
{
return AccessSector.None;
}
if (sixtet.C2a != sixtet.C2b)
{
return AccessSector.None;
}
if (sixtet.C3a != sixtet.C3b)
{
return AccessSector.None;
}
// Table of truth
if ((sixtet.C1a == 0) && (sixtet.C2a == 0) && (sixtet.C3a == 0))
{
return AccessSector.WriteKeyAWithKeyA | AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA |
AccessSector.WriteKeyBWithKeyA | AccessSector.ReadKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 1) && (sixtet.C3a == 0))
{
return AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA | AccessSector.ReadKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 0) && (sixtet.C3a == 0))
{
return AccessSector.WriteKeyAWithKeyB | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteKeyBWithKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 1) && (sixtet.C3a == 0))
{
return AccessSector.ReadAccessBitsWithKeyA | AccessSector.ReadAccessBitsWithKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 0) && (sixtet.C3a == 1))
{
return AccessSector.WriteKeyAWithKeyA | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.WriteAccessBitsWithKeyA | AccessSector.ReadKeyBWithKeyA |
AccessSector.WriteKeyBWithKeyA | AccessSector.ReadKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 1) && (sixtet.C3a == 1))
{
return AccessSector.WriteKeyAWithKeyB | AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteAccessBitsWithKeyB |
AccessSector.WriteKeyBWithKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 0) && (sixtet.C3a == 1))
{
return AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB | AccessSector.WriteAccessBitsWithKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 0) && (sixtet.C3a == 1))
{
return AccessSector.ReadAccessBitsWithKeyA |
AccessSector.ReadAccessBitsWithKeyB;
}
return AccessSector.None;
}
/// <summary>
/// Get the block access information
/// </summary>
/// <param name="blockNumber">the block number</param>
/// <param name="sectorData">the sector tailer data</param>
/// <returns>The access type rights</returns>
public AccessType BlockAccess(byte blockNumber, byte[] sectorData)
{
// Bit 7 6 5 4 3 2 1 0
// Byte 6 !C23 !C22 !C21 !C20 !C13 !C12 !C11 !C10
// Byte 7 C13 C12 C11 C10 !C33 !C32 !C31 !C30
// Byte 8 C33 C32 C31 C30 C23 C22 C21 C20
// Cab a = access bit and b = block number
byte blockGroup = BlockNumberToBlockGroup(blockNumber);
if (blockGroup == 3)
{
return AccessType.None;
}
var sixtet = DecodeSectorTailer(blockGroup, sectorData);
if (sixtet.C1a != sixtet.C1b)
{
return AccessType.None;
}
if (sixtet.C2a != sixtet.C2b)
{
return AccessType.None;
}
if (sixtet.C3a != sixtet.C3b)
{
return AccessType.None;
}
// Table of truth
if ((sixtet.C1a == 0) && (sixtet.C2a == 0) && (sixtet.C3a == 0))
{
return AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyA | AccessType.WriteKeyB |
AccessType.IncrementKeyA | AccessType.IncrementKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 1) && (sixtet.C3a == 0))
{
return AccessType.ReadKeyA | AccessType.ReadKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 0) && (sixtet.C3a == 0))
{
return AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 1) && (sixtet.C3a == 0))
{
return AccessType.ReadKeyA | AccessType.ReadKeyB | AccessType.WriteKeyB |
AccessType.IncrementKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 0) && (sixtet.C3a == 1))
{
return AccessType.ReadKeyA | AccessType.ReadKeyB |
AccessType.DecrementTransferRestoreKeyA | AccessType.DecrementTransferRestoreKeyB;
}
if ((sixtet.C1a == 0) && (sixtet.C2a == 1) && (sixtet.C3a == 1))
{
return AccessType.ReadKeyB | AccessType.WriteKeyB;
}
if ((sixtet.C1a == 1) && (sixtet.C2a == 0) && (sixtet.C3a == 1))
{
return AccessType.ReadKeyB;
}
return AccessType.None;
}
/// <summary>
/// Encode the desired access for the full sector including the block tailer
/// </summary>
/// <param name="accessSector">The access desired</param>
/// <param name="accessTypes">An array of 3 AccessType determining access of each block</param>
/// <returns>The 3 bytes encoding the rights</returns>
/// This is a synonym of EncodeSectorAndBlockTailer (for backward compatibility)
[Obsolete("deprecated, use EncodeSectorAndBlockTailer instead")]
public Triplet EncodeSectorAndClockTailer(AccessSector accessSector, AccessType[] accessTypes) =>
EncodeSectorAndBlockTailer(accessSector, accessTypes);
/// <summary>
/// Encode the desired access for the full sector including the block tailer
/// </summary>
/// <param name="accessSector">The access desired</param>
/// <param name="accessTypes">An array of 3 AccessType determining access of each block</param>
/// <returns>The 3 bytes encoding the rights</returns>
public Triplet EncodeSectorAndBlockTailer(AccessSector accessSector, AccessType[] accessTypes)
{
if (accessTypes.Length != 3)
{
throw new ArgumentException("Array must have 3 elements.", nameof(accessTypes));
}
var tupleRes = EncodeSectorTailer(accessSector);
byte b6 = tupleRes.B6;
byte b7 = tupleRes.B7;
byte b8 = tupleRes.B8;
for (byte i = 0; i < 3; i++)
{
tupleRes = EncodeSectorTailer(i, accessTypes[i]);
b6 |= tupleRes.B6;
b7 |= tupleRes.B7;
b8 |= tupleRes.B8;
}
return new Triplet(b6, b7, b8);
}
/// <summary>
/// Encode with default value the access sector and tailer blocks
/// </summary>
/// <returns></returns>
public Triplet EncodeDefaultSectorAndBlockTailer() => new Triplet(0xFF, 0x07, 0x80);
/// <summary>
/// From the ATQA ans SAK data find common card capacity
/// </summary>
/// <param name="ATQA">The ATQA response</param>
/// <param name="SAK">The SAK response</param>
/// <remarks>Does not recognize Mifare Plus cards, capacity must be set manually</remarks>
public void SetCapacity(ushort ATQA, byte SAK)
{
// Type of Mifare can be partially determined by ATQA and SAK
// https://www.nxp.com/docs/en/application-note/AN10833.pdf
// Not complete
if (ATQA == 0x0004)
{
if (SAK == 0x08)
{
Capacity = MifareCardCapacity.Mifare1K;
}
else if (SAK == 0x09)
{
Capacity = MifareCardCapacity.Mifare300;
}
}
else if ((ATQA == 0x0002) && (SAK == 0x18))
{
Capacity = MifareCardCapacity.Mifare4K;
}
}
/// <summary>
/// Is it a block sector?
/// </summary>
/// <param name="blockNumber">Input block number</param>
/// <returns>True if it is a sector block</returns>
public bool IsSectorBlock(byte blockNumber) => BlockNumberToBlockGroup(blockNumber) == 3;
/// <summary>
/// Get the number of blocks for a specific sector
/// </summary>
/// <param name="sectorNumber">Input sector number</param>
/// <returns>The number of blocks for this specific sector</returns>
public byte GetNumberBlocks(byte sectorNumber) => sectorNumber < 32 ? BlocksPerSmallSector : BlocksPerLargeSector;
/// <summary>
/// Get the number of blocks for a specific sector
/// </summary>
/// <returns>The number of blocks for this specific sector</returns>
public int GetNumberBlocks() => Capacity switch
{
MifareCardCapacity.Mifare1K => 1024 / 16,
MifareCardCapacity.Mifare2K => 2048 / 16,
MifareCardCapacity.Mifare4K => 4096 / 16,
_ or MifareCardCapacity.Mifare300 or MifareCardCapacity.Unknown => 0,
};
/// <summary>
/// Get the number of sectors
/// </summary>
/// <returns></returns>
public int GetNumberSectors() => Capacity switch
{
MifareCardCapacity.Mifare1K => 16,
MifareCardCapacity.Mifare2K => 32,
MifareCardCapacity.Mifare4K => 40,
_ or MifareCardCapacity.Mifare300 or MifareCardCapacity.Unknown => 0,
};
#endregion
/// <summary>
/// Depending on the command, serialize the needed data
/// Authentication will serialize the command, the concerned key and
/// the serial number
/// Reading data will just serialize the command
/// Writing data will serialize the data as well
/// </summary>
/// <returns>The serialized bits</returns>
private byte[] Serialize()
{
byte[]? ser = null;
switch (Command)
{
case MifareCardCommand.AuthenticationA:
if (KeyA is null || SerialNumber is null)
{
throw new ArgumentException($"Card is not configured for {nameof(MifareCardCommand.AuthenticationA)}.");
}
ser = new byte[2 + KeyA.Length + SerialNumber.Length];
ser[0] = (byte)Command;
ser[1] = BlockNumber;
if (KeyA.Length > 0)
{
KeyA.CopyTo(ser, 2);
}
if (SerialNumber.Length > 0)
{
SerialNumber.CopyTo(ser, 2 + KeyA.Length);
}
return ser;
case MifareCardCommand.AuthenticationB:
if (KeyB is null || SerialNumber is null)
{
throw new ArgumentException($"Card is not configured for {nameof(MifareCardCommand.AuthenticationB)}.");
}
ser = new byte[2 + KeyB.Length + SerialNumber.Length];
ser[0] = (byte)Command;
ser[1] = BlockNumber;
if (KeyB.Length > 0)
{
KeyB.CopyTo(ser, 2);
}
if (SerialNumber.Length > 0)
{
SerialNumber.CopyTo(ser, 2 + KeyB.Length);
}
return ser;
case MifareCardCommand.Write16Bytes:
case MifareCardCommand.Write4Bytes:
if (Data is null)
{
throw new ArgumentException($"Card is not configured for {nameof(MifareCardCommand.Write4Bytes)}.");
}
ser = new byte[2 + Data.Length];
ser[0] = (byte)Command;
ser[1] = BlockNumber;
if (Data.Length > 0)
{
Data.CopyTo(ser, 2);
}
return ser;
case MifareCardCommand.Incrementation:
case MifareCardCommand.Decrementation:
case MifareCardCommand.Transfer:
case MifareCardCommand.Restore:
case MifareCardCommand.Read16Bytes:
ser = new byte[2];
ser[0] = (byte)Command;
ser[1] = BlockNumber;
return ser;
default:
return new byte[0];
}
}
/// <summary>
/// Erase one sector
/// </summary>
/// <param name="newKeyA">The new key A, empty to use current one</param>
/// <param name="newKeyB">The new key B, empty to use current one</param>
/// <param name="sector">The sector number. Refer to Mifare documentation to understand how blocks work especially for Mifare 2K and 4K</param>
/// <param name="authenticateWithKeyA">True to authenticate with current Key A, false to authenticate with Key B</param>
/// <param name="resetAccessBytes">True to reset all the access bytes</param>
/// <returns>True if success</returns>
/// <remarks>Sector 0 can't be fully erase, only the blocks 1 and 2 will be erased</remarks>
public bool EraseSector(SpanByte newKeyA, SpanByte newKeyB, byte sector, bool authenticateWithKeyA, bool resetAccessBytes)
{
int nbSectors = GetNumberSectors();
if (sector >= nbSectors)
{
throw new ArgumentException($"{nameof(sector)} has to be less than the total number of sector for this card {nbSectors}");
}
int nbBlocks = GetNumberBlocks(sector);
if ((KeyB is not object or { Length: not 6 }) || (KeyA is not object or { Length: not 6 }))
{
throw new ArgumentException($"You must have a key A and key B of 6 bytes long");
}
if (Data is not object)
{
Data = new byte[16];
}
byte sectorTailer = SectorToBlockNumber(sector, 3);
BlockNumber = sectorTailer;
Command = authenticateWithKeyA ? MifareCardCommand.AuthenticationA : MifareCardCommand.AuthenticationB;
var ret = RunMifareCardCommand();
if (ret < 0)
{
return false;
}
if (resetAccessBytes)
{
var triplet = EncodeDefaultSectorAndBlockTailer();
Data[6] = triplet.B6;
Data[7] = triplet.B7;
Data[8] = triplet.B8;
Data[9] = 0x00;
}
if (newKeyA.Length is 6)
{
KeyA = newKeyA.ToArray();
// Original newKeyA.CopyTo(Data.AsSpan().Slice(0, 6));
Array.Copy(newKeyA.ToArray(), Data, 6);
}
if (newKeyB.Length is 6)
{
KeyB = newKeyB.ToArray();
// newKeyB.CopyTo(Data.AsSpan().Slice(10, 6));
Array.Copy(newKeyB.ToArray(), 0, Data, 10, 6);
}
// Find the sector tailer based on the sector number and it's a safe byte cast
var success = WriteDataBlock(sectorTailer);
if (!success)
{
return false;
}
byte firstBlock = SectorToBlockNumber(sector);
// Authenticate to the rest of the blocks to format and format them
for (byte block = firstBlock == 0 ? firstBlock++ : firstBlock; block < (firstBlock + nbBlocks - 1); block++)
{
BlockNumber = block;
Command = authenticateWithKeyA ? MifareCardCommand.AuthenticationA : MifareCardCommand.AuthenticationB;
ret = RunMifareCardCommand();
if (ret < 0)
{
return false;
}
Data = new byte[16];
success = WriteDataBlock(block);
if (!success)
{
return false;
}
}
return true;
}
/// <summary>
/// Select the card. Needed if authentication or read/write failed
/// </summary>
/// <returns>True if success</returns>
public bool ReselectCard()
{
return _rfid.ReselectTarget(Target);
}
/// <summary>
/// Format the Card to NDEF
/// </summary>
/// <param name="keyB">The key B to be used for formatting, if empty, will use the default key B</param>
/// <returns>True if success</returns>
/// <remarks>All sectors are configured as NFC Forum sectors</remarks>
public bool FormatNdef(SpanByte keyB = default)
{
if (Capacity is not MifareCardCapacity.Mifare1K or MifareCardCapacity.Mifare2K or MifareCardCapacity.Mifare4K)
{
throw new ArgumentException($"Only Mifare card classic are supported with capacity of 1K, 2K and 4K");
}
int nbBlocks = GetNumberBlocks();
byte[] keyFormat = keyB.Length == 0 ? StaticDefaultKeyB : keyB.ToArray();
if (keyFormat.Length != 6)
{
throw new ArgumentException($"{nameof(keyB)} can only be empty or 6 bytes length");
}
// First write the Mifare Application Directory for the format
// All block data coming from https://www.nxp.com/docs/en/application-note/AN10787.pdf
byte[] madSectorTrailer = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x77, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
DefaultFirstBlockNdefKeyA.CopyTo(madSectorTrailer);
madSectorTrailer[9] = Capacity == MifareCardCapacity.Mifare1K ? (byte)0xC1 : (byte)0xC2;
keyFormat.CopyTo(madSectorTrailer, 10);
var authOk = AuthenticateBlockKeyB(keyFormat, 1);
Data = Mifare1KBlock1;
authOk &= WriteDataBlock(1);
authOk &= AuthenticateBlockKeyB(keyFormat, 2);
Data = Mifare1KBlock2;
authOk &= WriteDataBlock(2);
authOk &= AuthenticateBlockKeyB(keyFormat, 3);
Data = madSectorTrailer;
authOk &= WriteDataBlock(3);
if (Capacity == MifareCardCapacity.Mifare2K)
{
byte block = 16 * 4;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare2KBlock64;
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare1KBlock2; // 65 is same as 2
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare2KBlock66;
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = madSectorTrailer;
authOk &= WriteDataBlock(block);
}
else if (Capacity == MifareCardCapacity.Mifare4K)
{
byte block = 16 * 4;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare4KBlock64;
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare1KBlock2; // 65 is same as 2
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = Mifare1KBlock2; // 66 is same as 2
authOk &= WriteDataBlock(block);
block++;
authOk &= AuthenticateBlockKeyB(keyFormat, block);
Data = madSectorTrailer;
authOk &= WriteDataBlock(block);
}
// write the empty NDEF TLV in the first NFC sector
authOk &= AuthenticateBlockKeyB(keyFormat, 4);
Data = Mifare1KBlock4;
authOk &= WriteDataBlock(4);
// GBP should be 0xC1 for the MAD sectors and 0x40 for the others for a full read/write access
// We wrote the MAD sector trailers above, so we write the NFC sector trailers here
Data = new byte[] { 0, 0, 0, 0, 0, 0, 0x7F, 0x07, 0x88, 0x40, 0, 0, 0, 0, 0, 0 };
DefaultBlocksNdefKeyA.CopyTo(Data);
keyFormat.CopyTo(Data, 10);
for (byte sector = 1; sector < GetNumberSectors(); sector++)
{
if (sector != 16)
{
byte block = SectorToBlockNumber(sector, 3);
authOk &= AuthenticateBlockKeyB(keyFormat, block);
authOk &= WriteDataBlock(block);
}
}
return authOk;
}
/// <summary>
/// Write an NDEF Message
/// </summary>
/// <param name="message">The NDEF Message to write</param>
/// <param name="writeKeyA">True to write with Key A</param>
/// <returns>True if success</returns>
public bool WriteNdefMessage(NdefMessage message, bool writeKeyA = true)
{
if ((KeyB is not object or { Length: not 6 }) && (!writeKeyA))
{
throw new ArgumentException("The Key B must be 6 bytes long");
}
// We need to add 0x03 then the length on 1 or 2 bytes then the trailer 0xFE
int messageLengthBytes = message.Length > 254 ? 3 : 1;
SpanByte serializedMessage = new byte[message.Length + 2 + messageLengthBytes];
message.Serialize(serializedMessage.Slice(1 + messageLengthBytes));
serializedMessage[0] = 0x03;
if (messageLengthBytes == 1)
{
serializedMessage[1] = (byte)message.Length;
}
else
{
serializedMessage[1] = 0xFF;
serializedMessage[2] = (byte)((message.Length >> 8) & 0xFF);
serializedMessage[3] = (byte)(message.Length & 0xFF);
}
serializedMessage[serializedMessage.Length - 1] = 0xFE;
// Number of blocks to write
int nbBlocks = serializedMessage.Length / 16 + (serializedMessage.Length % 16 > 0 ? 1 : 0);
switch (Capacity)
{
default:
case MifareCardCapacity.Unknown:
case MifareCardCapacity.Mifare300:
throw new ArgumentException($"Mifare card unknown and 300 are not supported for writing");
case MifareCardCapacity.Mifare2K:
// Total blocks where we can write = 30 * 3 = 90
if (nbBlocks > 90)
{
throw new ArgumentOutOfRangeException($"NNDEF message too large, maximum {90 * 16} bytes, current size is {nbBlocks * 16}");
}
break;
case MifareCardCapacity.Mifare4K:
// Total blocks where we can write = 30 * 3 + 8 * 15 = 210
if (nbBlocks > 213)
{
throw new ArgumentOutOfRangeException($"NNDEF message too large, maximum {210 * 16} bytes, current size is {nbBlocks * 16}");
}
break;
case MifareCardCapacity.Mifare1K:
// Total blocks where we can write = 15 * 3 = 45
if (nbBlocks > 45)
{
throw new ArgumentOutOfRangeException($"NNDEF message too large, maximum {45 * 16} bytes, current size is {nbBlocks * 16}");
}
break;
}
int inc = 4;
bool ret;
for (int block = 0; block < nbBlocks; block++)
{
if (IsSectorBlock((byte)(block + inc)))
{
inc++;
}
// Skip as well sector 16 for 2K and 4K cards
if (block == 16 * 4)
{
inc += 4;