forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UltralightCard.cs
1035 lines (943 loc) · 40.2 KB
/
UltralightCard.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 System.Buffers.Binary;
using Iot.Device.Ndef;
#if DEBUG
using Microsoft.Extensions.Logging;
using nanoFramework.Logging;
#endif
namespace Iot.Device.Card.Ultralight
{
/// <summary>
/// A Ultralight card class
/// </summary>
public class UltralightCard
{
/// <summary>
/// Default password used for write and read
/// </summary>
public static readonly byte[] DefaultPassword = new byte[4] { 0xFF, 0xFF, 0xFF, 0xFF };
// This is the actual RFID reader
private readonly CardTransceiver _rfid;
#if DEBUG
private readonly ILogger _logger;
#endif
private byte[] _pack;
private byte _endAddress;
/// <summary>
/// The tag number detected by the reader, only 1 or 2
/// </summary>
public byte Target { get; set; }
/// <summary>
/// The NDEF capacity in bytes
/// </summary>
public int NdefCapacity { get; internal set; }
/// <summary>
/// The type of card
/// </summary>
public UltralightCardType UltralightCardType { get; internal 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>
/// The command to execute on the card
/// </summary>
public UltralightCommand Command { get; set; }
/// <summary>
/// The counter to read or increment
/// </summary>
public byte Counter { get; set; }
/// <summary>
/// Authentication key
/// </summary>
public byte[] AuthenticationKey { get; set; } = DefaultPassword;
/// <summary>
/// UUID is the Serial Number, called MAC sometimes
/// </summary>
public byte[]? SerialNumber { get; set; }
/// <summary>
/// Check if this is a Ultralight card type
/// </summary>
/// <param name="ATQA">The ATQA</param>
/// <param name="SAK">The SAK</param>
/// <returns>True if this is an Ultralight</returns>
public static bool IsUltralightCard(ushort ATQA, byte SAK) => (ATQA == 0x0044) && (SAK == 0);
/// <summary>
/// Constructor for Ultralight
/// </summary>
/// <param name="rfid">A card transceiver class</param>
/// <param name="target">The target number as some card readers attribute one</param>
public UltralightCard(CardTransceiver rfid, byte target)
{
#if DEBUG
_logger = this.GetCurrentClassLogger();
#endif
_rfid = rfid;
Target = target;
// Try to get the version, if not sucessful than it's one of the early model or C
// See https://stackmirror.com/questions/37002498
GetVersion();
if ((Data != null) && (Data.Length == 8))
{
if ((Data[2] == 0x04) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0B))
{
NdefCapacity = 48;
UltralightCardType = UltralightCardType.UltralightNtag210;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0E))
{
NdefCapacity = 128;
UltralightCardType = UltralightCardType.UltralightNtag212;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0F))
{
NdefCapacity = 144;
UltralightCardType = UltralightCardType.UltralightNtag213;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x04) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0F))
{
NdefCapacity = 144;
UltralightCardType = UltralightCardType.UltralightNtag213F;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x11))
{
NdefCapacity = 504;
UltralightCardType = UltralightCardType.UltralightNtag215;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x13))
{
NdefCapacity = 888;
UltralightCardType = UltralightCardType.UltralightNtag216;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x04) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x13))
{
NdefCapacity = 888;
UltralightCardType = UltralightCardType.UltralightNtag216F;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x01) && (Data[6] == 0x13))
{
NdefCapacity = 888;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H1101;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x05) && (Data[4] == 0x02) && (Data[5] == 0x01) && (Data[6] == 0x13))
{
NdefCapacity = 888;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H1101W0;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x05) && (Data[4] == 0x02) && (Data[5] == 0x02) && (Data[6] == 0x13))
{
NdefCapacity = 888;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H2111W0;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x01) && (Data[6] == 0x15))
{
NdefCapacity = 1912;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H2101;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x05) && (Data[4] == 0x02) && (Data[5] == 0x01) && (Data[6] == 0x15))
{
NdefCapacity = 1912;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H1201W0;
}
else if ((Data[2] == 0x04) && (Data[3] == 0x05) && (Data[4] == 0x02) && (Data[5] == 0x02) && (Data[6] == 0x15))
{
NdefCapacity = 1912;
UltralightCardType = UltralightCardType.UltralightNtagI2cNT3H2211W0;
}
else if ((Data[2] == 0x03) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0B))
{
NdefCapacity = 48;
UltralightCardType = UltralightCardType.UltralightEV1MF0UL1101;
}
else if ((Data[2] == 0x03) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0B))
{
NdefCapacity = 48;
UltralightCardType = UltralightCardType.UltralightEV1MF0ULH1101;
}
else if ((Data[2] == 0x03) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0E))
{
NdefCapacity = 128;
UltralightCardType = UltralightCardType.UltralightEV1MF0UL2101;
}
else if ((Data[2] == 0x03) && (Data[3] == 0x02) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0E))
{
NdefCapacity = 128;
UltralightCardType = UltralightCardType.UltralightEV1MF0ULH2101;
}
else if ((Data[2] == 0x21) && (Data[3] == 0x01) && (Data[4] == 0x01) && (Data[5] == 0x00) && (Data[6] == 0x0E))
{
NdefCapacity = 128;
UltralightCardType = UltralightCardType.UltralightNtag203;
}
else
{
NdefCapacity = 1 << (Data[6] >> 1);
}
}
else
{
// Check if AuthenticationPart1 returns something
Command = UltralightCommand.ThreeDsAuthenticationPart1;
var res = RunUltralightCommand();
if (res > 0)
{
NdefCapacity = 144;
UltralightCardType = UltralightCardType.UltralightC;
}
else
{
// Then it's either a Ultralight or 203. Read block 41
Command = UltralightCommand.Read16Bytes;
res = RunUltralightCommand();
if (res > 0)
{
NdefCapacity = 137;
UltralightCardType = UltralightCardType.UltralightNtag203;
}
else
{
NdefCapacity = 144;
UltralightCardType = UltralightCardType.MifareUltralight;
}
}
}
}
/// <summary>
/// Get the version data
/// </summary>
/// <returns>Empty byte array if error, otherwise a 8 bytes array</returns>
public byte[] GetVersion()
{
Command = UltralightCommand.GetVersion;
var res = RunUltralightCommand();
if ((res == 8) && (Data is object))
{
return Data;
}
return new byte[0];
}
/// <summary>
/// Read at once multiple pages blocks of 4 bytes
/// </summary>
/// <param name="startPage">The start block</param>
/// <param name="endPage">The end block</param>
/// <returns>A buffer with the read bytes</returns>
public byte[] ReadFast(byte startPage, byte endPage)
{
BlockNumber = startPage < endPage ? startPage : endPage;
_endAddress = startPage > endPage ? startPage : endPage;
Command = UltralightCommand.ReadFast;
var ret = RunUltralightCommand();
return ret > 0 ? Data! : new byte[0];
}
/// <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 RunUltralightCommand()
{
byte[] dataOut = new byte[0];
bool awaitingData = false;
if (Command == UltralightCommand.Read16Bytes)
{
awaitingData = true;
dataOut = new byte[16];
}
else if (Command == UltralightCommand.ReadSignature)
{
awaitingData = true;
dataOut = new byte[32];
}
else if (Command == UltralightCommand.PasswordAuthentication)
{
awaitingData = true;
dataOut = new byte[2];
}
else if (Command == UltralightCommand.ReadFast)
{
awaitingData = true;
if ((_endAddress - BlockNumber) < 0)
{
throw new ArgumentException("For fast read, last block has to be more than first block");
}
dataOut = new byte[(_endAddress - BlockNumber + 1) * 4];
}
else if (Command == UltralightCommand.GetVersion)
{
awaitingData = true;
dataOut = new byte[8];
}
else if ((Command == UltralightCommand.ThreeDsAuthenticationPart1) || (Command == UltralightCommand.ThreeDsAuthenticationPart2))
{
awaitingData = true;
dataOut = new byte[9];
}
else if (Command == UltralightCommand.ReadCounter)
{
awaitingData = true;
dataOut = new byte[3];
}
var ret = _rfid.Transceive(Target, Serialize(), dataOut);
#if DEBUG
_logger.LogDebug($"{nameof(UltralightCommand)}: {Command}, Target: {Target}, Data: {BitConverter.ToString(Serialize())}, Success: {ret}, Dataout: {BitConverter.ToString(dataOut)}");
#endif
if ((ret > 0) && awaitingData)
{
Data = dataOut;
}
return ret;
}
/// <summary>
/// Check if a page is read only
/// </summary>
/// <param name="page">The page number</param>
/// <returns>True is read only</returns>
public bool IsPageReadOnly(byte page)
{
// Note: to improve this method, a caching mechanism can be put in place
// In general, this is used to check if something is password protected and not in
// an intense way
if (page <= 0x02)
{
return true;
}
// Read block 2
// byte 2
// bit 0 = page 03
// bit 1 = page 04-09
// bit 2 = page 0A-0F
// bit 3 = 03 as well
// bit 4 = 4
// bit 8 = 7
// Byte 3
// bit 0 = 8
// bit 7 = 15
// warning byte2 bit0, 1 and 2 are write once, once status changed, can't be changes again
if ((page >= 0x3) && page <= 0x7)
{
SpanByte toSend = new byte[2] { (byte)UltralightCommand.Read16Bytes, 2 };
SpanByte dataOut = new byte[16];
_rfid.Transceive(Target, toSend, dataOut);
return (dataOut[2] & (0b0000_0001 << page)) == (0b0000_0001 << page);
}
else if ((page >= 0x08) && (page <= 0x0F))
{
SpanByte toSend = new byte[2] { (byte)UltralightCommand.Read16Bytes, 2 };
SpanByte dataOut = new byte[16];
_rfid.Transceive(Target, toSend, dataOut);
return (dataOut[3] & (0b0000_0001 << (page - 8))) == (0b0000_0001 << (page - 8));
}
else
{
SpanByte toSend = new byte[2] { (byte)UltralightCommand.Read16Bytes, 0x28 };
SpanByte dataOut = new byte[16];
switch (UltralightCardType)
{
case UltralightCardType.UltralightNtag203:
// Read 0x24
toSend[1] = 0x24;
_rfid.Transceive(Target, toSend, dataOut);
// byte 0, 1 and 2 are used , 2 pages lock with specific cases
if ((page >= 16) && (page <= 31))
{
var inc = (page - 16) / 2;
return (dataOut[0] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
else if ((page >= 32) && (page <= 35))
{
var inc = (page - 32) / 2;
return (dataOut[1] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
return true;
case UltralightCardType.UltralightNtag213:
case UltralightCardType.UltralightNtag213F:
case UltralightCardType.UltralightNtag212:
// Read 0x28
_rfid.Transceive(Target, toSend, dataOut);
// byte 0, 1 and 2 are used , 2 pages lock with specific cases
if ((page >= 16) && (page <= 31))
{
var inc = (page - 16) / 2;
return (dataOut[0] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
else if ((page >= 32) && (page <= 39))
{
var inc = (page - 32) / 2;
return (dataOut[1] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
return true;
case UltralightCardType.UltralightNtag215:
// Read 0x82
toSend[1] = 0x82;
_rfid.Transceive(Target, toSend, dataOut);
// byte 0 and 16 pages blocks
if ((page >= 16) && (page <= 129))
{
var inc = (page - 16) / 16;
return (dataOut[0] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
return true;
case UltralightCardType.UltralightNtag216:
case UltralightCardType.UltralightNtag216F:
case UltralightCardType.UltralightNtagI2cNT3H1101:
case UltralightCardType.UltralightNtagI2cNT3H1101W0:
// Read 0xE2
toSend[1] = 0xE2;
_rfid.Transceive(Target, toSend, dataOut);
// byte 0 and 1 for 16 pages blocks
if ((page >= 16) && (page <= 143))
{
var inc = (page - 16) / 16;
return (dataOut[0] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
else if ((page >= 144) && (page <= 225))
{
var inc = (page - 144) / 16;
return (dataOut[1] & (0b0000_0001 << inc)) == (0b0000_0001 << inc);
}
return true;
case UltralightCardType.Unknown:
default:
// safe side...
return true;
}
}
}
/// <summary>
/// Get the number of blocks for a specific sector
/// </summary>
public int NumberBlocks => UltralightCardType switch
{
UltralightCardType.UltralightNtag210 => 16,
UltralightCardType.UltralightNtag212 => 45,
UltralightCardType.UltralightNtag213 => 45,
UltralightCardType.UltralightNtag213F => 45,
UltralightCardType.UltralightNtag215 => 135,
UltralightCardType.UltralightNtag216 => 231,
UltralightCardType.UltralightNtag216F => 231,
UltralightCardType.UltralightEV1MF0UL1101 => 20,
UltralightCardType.UltralightEV1MF0ULH1101 => 20,
UltralightCardType.UltralightEV1MF0UL2101 => 41,
UltralightCardType.UltralightEV1MF0ULH2101 => 41,
UltralightCardType.UltralightNtagI2cNT3H1101 => 231,
UltralightCardType.UltralightNtagI2cNT3H1101W0 => 231,
UltralightCardType.UltralightNtagI2cNT3H2111W0 => 476 + 9,
UltralightCardType.UltralightNtagI2cNT3H2101 => 476 + 9,
UltralightCardType.UltralightNtagI2cNT3H1201W0 => 476 + 9,
UltralightCardType.UltralightNtagI2cNT3H2211W0 => 255 * 4,
UltralightCardType.UltralightC => 36,
UltralightCardType.UltralightNtag203 => 41,
UltralightCardType.MifareUltralight => 48,
_ or UltralightCardType.Unknown => 0,
};
/// <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>
/// Write an NDEF Message
/// </summary>
/// <param name="message">The NDEF Message to write</param>
/// <returns>True if success</returns>
public bool WriteNdefMessage(NdefMessage message)
{
const int BlockSize = 4;
// We need to add 0x03 then the length on 1 or 2 bytes then the trailer 0xFE
int messageLengthBytes = message.Length > 254 ? 3 : 1;
if (messageLengthBytes > NdefCapacity)
{
return false;
}
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;
// Blocks are 4 bytes
int nbBlocks = serializedMessage.Length / BlockSize + (serializedMessage.Length % BlockSize > 0 ? 1 : 0);
int inc = 4;
for (int block = 0; block < nbBlocks; block++)
{
BlockNumber = (byte)(inc + block); // Safe cast, never higher than 255
Command = UltralightCommand.Write4Bytes;
if (block * BlockSize + BlockSize <= serializedMessage.Length)
{
Data = serializedMessage.Slice(block * BlockSize, BlockSize).ToArray();
}
else
{
Data = new byte[BlockSize];
serializedMessage.Slice(block * BlockSize).CopyTo(Data);
}
var res = RunUltralightCommand();
if (res < 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Check if the card formated to NDEF
/// </summary>
/// <returns>True if NDEF formated</returns>
/// <remarks>It will only check the first 2 block of the first sector and that the GPB is set properly</remarks>
public bool IsFormattedNdef()
{
BlockNumber = 3;
Command = UltralightCommand.Read16Bytes;
var res = RunUltralightCommand();
if (res < 0)
{
return false;
}
if ((Data![0] != 0xE1) || (Data[1] != 0x10))
{
return false;
}
if ((Data[4] == 0x01) && (Data[5] == 0x03) && (Data[6] == 0xA0) && (Data[7] == 0x0C))
{
return true;
}
else if ((Data[4] == 0x03))
{
return true;
}
return false;
}
/// <summary>
/// Format the Card to NDEF
/// </summary>
/// <param name="authenticationKey">An authentication key if authentication is required.</param>
/// <returns>True if success</returns>
public bool FormatNdef(SpanByte authenticationKey = default)
{
// NDEF formatting is starting on page 3:
// E1 10 CP 00
// 03 00 FE 00
// Early NTAG should be formated a bit differently but this is enough
// CP = NdefCapacity / 8
if (authenticationKey.Length > 0)
{
var authOK = ProcessAuthentication(authenticationKey);
if (!authOK)
{
return false;
}
}
// Block 3 can only be bitwise modified
// Once the logic is set to 1, it cannot be set back to 0
// So read it first and check if the E1 and 10 are correct and skip the write
// If it is.
BlockNumber = 3;
Command = UltralightCommand.Read16Bytes;
var res = RunUltralightCommand();
if (res > 0)
{
if ((Data![0] != 0xE1) || (Data[1] != 0x10))
{
Command = UltralightCommand.Write4Bytes;
Data = new byte[4] { 0xE1, 0x10, (byte)(NdefCapacity / 8), 0x00 };
res = RunUltralightCommand();
if (res <= 0)
{
return false;
}
}
}
else
{
return false;
}
BlockNumber++;
Data![0] = 0x03; // NDEF start marker
Data[1] = 0x00; // Length of message
Data[2] = 0xFE; // NDEF end marker
Data[3] = 0x00; // Empty
res = RunUltralightCommand();
if (res <= 0)
{
return false;
}
return true;
}
/// <summary>
/// Try to read a NDEF Message from a Mifare card
/// </summary>
/// <param name="message">The NDEF message</param>
/// <returns>True if success</returns>
public bool TryReadNdefMessage(out NdefMessage message)
{
const int BlockSize = 16;
message = new NdefMessage();
// Read page 4
BlockNumber = 4;
Command = UltralightCommand.Read16Bytes;
var res = RunUltralightCommand();
if (res <= 0)
{
return false;
}
// Check if it's the old formating and skip it
// 01:03:A0:0C
int slice = 0;
if ((Data![0] == 0x01) && (Data[1] == 0x03) && (Data[2] == 0xA0) && (Data[3] == 0x0C))
{
slice = 4;
}
var doublet = NdefMessage.GetStartSizeNdef(new SpanByte(Data, slice, Data.Length - slice));
int start = doublet.Start;
int size = doublet.Size;
if ((start < 0) || (size < 0))
{
return false;
}
// calculate the size to read
int blocksToRead = (size + start) / BlockSize + ((size + start) % BlockSize != 0 ? 1 : 0);
// We would have to read more available data than the capacity
if ((NdefCapacity + 12) <= blocksToRead * BlockSize)
{
return false;
}
SpanByte card = new byte[(blocksToRead + slice / 4) * BlockSize];
new SpanByte(Data, slice, Data.Length - slice).CopyTo(card);
byte idxCard = 1;
// Decrease by 1 block if we skip first page
int block = 8;
while (idxCard < (blocksToRead + slice / 4))
{
BlockNumber = (byte)block; // Safe cast as never more than 255
Command = UltralightCommand.Read16Bytes;
res = RunUltralightCommand();
if (res <= 0)
{
return false;
}
new SpanByte(Data).CopyTo(card.Slice(idxCard * BlockSize - slice));
idxCard++;
// Here, we read 4 blocks of 4, so 16 blocks
block += 4;
}
var ndef = NdefMessage.ExtractMessage(card);
try
{
message = new NdefMessage(ndef);
}
catch (Exception)
{
// Catching all exceptions as quite a lot can happen
// This is checking if a message is valid or not
return false;
}
return true;
}
/// <summary>
/// Process authentication
/// </summary>
/// <param name="authenticationKkey">An authentication key</param>
/// <returns>True if success</returns>
/// <remarks>Depending on the type of authentication, the process will be done transparently</remarks>
public bool ProcessAuthentication(SpanByte authenticationKkey)
{
if (UltralightCardType == UltralightCardType.UltralightC)
{
// Not yet implemented, need to implement with 3DS
throw new NotImplementedException();
}
if (authenticationKkey.Length != 4)
{
throw new ArgumentException($"Password can only be 4 bytes long");
}
AuthenticationKey = authenticationKkey.ToArray();
Command = UltralightCommand.PasswordAuthentication;
var res = RunUltralightCommand();
if (res < 0)
{
return false;
}
_pack = new byte[2];
Data!.CopyTo(_pack, 0);
return true;
}
/// <summary>
/// Get the counter value
/// </summary>
/// <param name="counter">A valid counter value, can vary depending on the card. 0xFF will ignore the value and use the one set in Counter</param>
/// <returns>The counter value or -1 if any error</returns>
public int GetCounter(byte counter = 0xFF)
{
Command = UltralightCommand.ReadCounter;
Counter = counter != 0xFF ? counter : Counter;
var res = RunUltralightCommand();
if (res < 0)
{
return -1;
}
return Data![0] + (Data[1] << 8) + (Data[2] << 16);
}
/// <summary>
/// Increase a counter by a specified amount
/// </summary>
/// <param name="counter">A valid counter value, can vary depending on the card. 0xFF will ignore the value and use the one set in Counter</param>
/// <param name="increment">The amount to increment the counter. If negative, it will use the value of Data</param>
/// <returns>True if success</returns>
public bool IncreaseCounter(byte counter = 0xFF, int increment = -1)
{
Command = UltralightCommand.IncreaseCounter;
Counter = counter != 0xFF ? counter : Counter;
if (increment >= 0)
{
Data = new byte[4];
BinaryPrimitives.WriteInt32LittleEndian(Data, increment);
}
var ret = RunUltralightCommand();
return ret >= 0;
}
/// <summary>
/// Perform a write using the 16 bytes present in Data on a specific block
/// </summary>
/// <param name="block">The block number to write</param>
/// <returns>True if success</returns>
/// <remarks>You will need to be authenticated properly before</remarks>
public bool WriteDataBlock(byte block)
{
if (_pack == null)
{
var authOK = ProcessAuthentication(AuthenticationKey);
if (!authOK)
{
return false;
}
}
BlockNumber = block;
Command = UltralightCommand.Write4Bytes;
var ret = RunUltralightCommand();
return ret >= 0;
}
/// <summary>
/// Get the chip signature
/// </summary>
/// <returns>The signature or an empty array</returns>
public byte[] GetSignature()
{
Command = UltralightCommand.ReadSignature;
var res = RunUltralightCommand();
if (res > 0)
{
return Data!;
}
return new byte[0];
}
/// <summary>
/// Try to get the configuration
/// </summary>
/// <param name="configuration">The detailed configuration</param>
/// <returns></returns>
public bool TryGetConfiguration(out Configuration configuration)
{
configuration = new();
// Read the last 4 blocks
BlockNumber = (byte)(NumberBlocks - 4); // Safe cast as never more than 255
if (UltralightCardType is UltralightCardType.UltralightNtagI2cNT3H1101 or UltralightCardType.UltralightNtagI2cNT3H1101W0 or UltralightCardType.UltralightNtagI2cNT3H2111W0
or UltralightCardType.UltralightNtagI2cNT3H2101 or UltralightCardType.UltralightNtagI2cNT3H1201W0 or UltralightCardType.UltralightNtagI2cNT3H2211W0)
{
BlockNumber--;
}
else if (UltralightCardType is UltralightCardType.UltralightC)
{
// There is no configuration for this card
return false;
}
Command = UltralightCommand.Read16Bytes;
var res = RunUltralightCommand();
if (res < 0)
{
return false;
}
configuration.Mirror.MirrorType = (MirrorType)(Data![0] >> 6);
configuration.Mirror.Position = (byte)((Data[0] >> 4) & 0b0000_0011);
configuration.IsStrongModulation = ((Data[0] >> 2) & 1) == 1;
configuration.Mirror.Page = Data[2];
configuration.Authentication.AuthenticationPageRequirement = Data[3];
configuration.Authentication.IsReadWriteAuthenticationRequired = ((Data[4] >> 7) & 1) == 1;
configuration.Authentication.IsWritingLocked = ((Data[4] >> 6) & 1) == 1;
configuration.IsSleepEnabled = ((Data[0] >> 3) & 1) == 1;
configuration.FieldDetectPin = (FieldDetectPin)(Data[0] & 0b0000_0011);
configuration.NfcCounter.IsEnabled = ((Data[4] >> 4) & 1) == 1;
configuration.NfcCounter.IsPasswordProtected = ((Data[4] >> 3) & 1) == 1;
configuration.Authentication.MaximumNumberOfPossibleTries = (byte)(Data[4] & 0b0000_0111);
return true;
}
/// <summary>
/// Write the configuration
/// </summary>
/// <param name="configuration">The configuration to write</param>
/// <returns>True if success</returns>
/// <remarks>An authentication has to happen and will use the credentials stored</remarks>
public bool WriteConfiguration(Configuration configuration)
{
if (UltralightCardType is UltralightCardType.UltralightC)
{
// There is no configuration for this card
return false;
}
var res = ProcessAuthentication(AuthenticationKey);
if (!res)
{
return false;
}
var serialized = configuration.Serialize();
BlockNumber = (byte)(NumberBlocks - 4);
if (UltralightCardType is UltralightCardType.UltralightNtagI2cNT3H1101 or UltralightCardType.UltralightNtagI2cNT3H1101W0 or UltralightCardType.UltralightNtagI2cNT3H2111W0
or UltralightCardType.UltralightNtagI2cNT3H2101 or UltralightCardType.UltralightNtagI2cNT3H1201W0 or UltralightCardType.UltralightNtagI2cNT3H2211W0)
{
// Those are using different configurations, Configuration registers and session registers
BlockNumber--;
}
Data = new byte[4];
new SpanByte(serialized, 0, 4).CopyTo(Data);
Command = UltralightCommand.Write4Bytes;
var ret = RunUltralightCommand();
if (ret < 0)
{
return false;
}
BlockNumber++;
new SpanByte(serialized, 4, 4).CopyTo(Data);
Command = UltralightCommand.Write4Bytes;
ret = RunUltralightCommand();
if (ret < 0)
{
return false;
}
return true;
}
/// <summary>
/// Set the password, the AuthenticationKey is used as the old password
/// </summary>
/// <param name="newAuthenticationKkey">The new authentication key</param>
/// <returns>True if success</returns>
public bool SetPassword(SpanByte newAuthenticationKkey)
{
if (_pack == null)
{
var res = ProcessAuthentication(AuthenticationKey);
if (!res)
{
return false;
}
}
BlockNumber = (byte)(NumberBlocks - 4); // Safe cast as never more than 255
if (UltralightCardType is UltralightCardType.UltralightNtagI2cNT3H1101 or UltralightCardType.UltralightNtagI2cNT3H1101W0 or UltralightCardType.UltralightNtagI2cNT3H2111W0
or UltralightCardType.UltralightNtagI2cNT3H2101 or UltralightCardType.UltralightNtagI2cNT3H1201W0 or UltralightCardType.UltralightNtagI2cNT3H2211W0)
{
BlockNumber--;
}
else if (UltralightCardType is UltralightCardType.UltralightC)
{
// Not implemented, this require special operations
throw new NotImplementedException();
}
if (newAuthenticationKkey.Length != 4)
{
throw new ArgumentException($"Password can only be 4 bytes long");
}
Data = newAuthenticationKkey.ToArray();
Command = UltralightCommand.Write4Bytes;
var ret = RunUltralightCommand();
if (ret < 0)
{
return false;
}
return ProcessAuthentication(newAuthenticationKkey);
}
private byte[] Serialize()
{
byte[]? ser = null;
switch (Command)
{
case UltralightCommand.GetVersion:
ser = new byte[1] { (byte)Command };
break;
case UltralightCommand.Read16Bytes:
ser = new byte[2] { (byte)Command, BlockNumber };
break;
case UltralightCommand.ReadFast:
// We're using the current block as start block and _endAddress as end block
ser = new byte[3] { (byte)Command, BlockNumber, _endAddress };
break;
case UltralightCommand.WriteCompatible:
case UltralightCommand.Write4Bytes:
if (Data is null)
{
throw new ArgumentException($"Card is not configured for writing.");
}
ser = new byte[2 + Data.Length];
ser[0] = (byte)Command;
ser[1] = BlockNumber;
if (Data.Length > 0)
{
Data.CopyTo(ser, 2);
}
break;
case UltralightCommand.ReadCounter:
ser = new byte[2] { (byte)Command, Counter };
break;
case UltralightCommand.IncreaseCounter:
if (Data is null)
{
throw new ArgumentException($"Card is not configured for counter increase.");
}
ser = new byte[6];
ser[0] = (byte)Command;