-
Notifications
You must be signed in to change notification settings - Fork 1
/
Slimduet.java
2005 lines (1663 loc) · 71.2 KB
/
Slimduet.java
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
/**
MIT License
Copyright (c) [2022] [TAISYS TECHNOLOGIES CO., LTD.]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.taisys.Slimduet.Applet;
import javacard.framework.*;
import javacard.security.*;
import javacardx.crypto.*;
import uicc.toolkit.*;
import uicc.access.FileView;
import uicc.access.UICCSystem;
import uicc.access.UICCException;
import org.globalplatform.*;
public class Slimduet extends Applet implements ToolkitInterface, ToolkitConstants, AppletEvent, MultiSelectable {
private static short appletVersion = (short)0x0001;
private static byte testVersion = (byte)0xFF;
// Wallet Command
private final byte INS_QUERY_CARD_INFOR = (byte)0xE0;
private final byte INS_CREATE_WALLET_USER = (byte)0xE1;
private final byte INS_GET_CHILD_PUBLIC_KEY = (byte)0xE3;
private final byte INS_SIGN_TRANSFER = (byte)0xE4;
private final byte INS_SYNCH_WALLET_INFOR = (byte)0xE5;
private final static short SW_HD_USER_NO_EXIST = (short)0x6982;
private final static short SW_HD_WALLET_EXIST = (short)0x6986;
private final static short SW_HD_USER_OVERSIZE = (short)0x6987;
private final static short SW_USER_CANCEL = (short)0x6985;
private final static short SW_DATA_INVALID = (short)0x6A84;
private final static short SW_SIGN_VERIFYING = (short)0x698A;
private final static short SW_VERIFY_FAILD = (short)0x698D;
private final static short SW_LANGUAGE_NO_EXIST = (short)0x698C;
private final static short SW_PIN_LOCK = (short)0x698E;
private final static short SW_PUK_LOCK = (short)0x6995;
private final static short SW_STATUS_NO_ERROR = (short)0x9000;
private final static short SW_STK_BUSY = (short)0x9300;
public final static short HD_USER_NUM_MAX = 1;
public final static short HASH_NUM_SIZE = 10;
public final static short MNEMONIC_SIZE = 12;
public final static short USER_ID_SIZE = 16;
public final static short CHAIN_CODE_SIZE = 32;
public final static short KEY_SECRET_SIZE = 32;
public final static short HASH_VALUE_SIZE = 32;
public final static short COMPLETE_USER_PATH_SIZE = 20;
private final static byte [] MNEMONIC_WORD = {'m', 'n', 'e', 'm', 'o', 'n', 'i', 'c'};
private final static byte [] BITCOIN_SEED = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
private final static short[] ALPHABE_INDEX = {(short)0x0000, (short)0x04C8, (short)0x08E5, (short)0x0F6F, (short)0x135F, (short)0x16E3, (short)0x1A9D, (short)0x1D49, (short)0x1F89, (short)0x2178, (short)0x222C, (short)0x22E0, (short)0x258C, (short)0x293D, (short)0x2AAE, (short)0x2C9D, (short)0x3141, (short)0x3189, (short)0x355E, (short)0x3E1F, (short)0x4260, (short)0x439B, (short)0x4539, (short)0x47A6, (short)0x47A6, (short)0x47DC, (short)0x47F7};
// FID
private final static short FID_DF_BIP = (short)0x7381;
private final static short FID_EF_CARD_ID = (short)0x1B10;
private final static short FID_EF_BIP_IP = (short)0x42B1;
private final static short FID_EF_BIP_Port = (short)0x42B2;
private final static short FID_DF_COLDWALLET = (short)0x7382;
private final static short FID_EF_MENU_MNEMONICWORD = (short)0x1F8A;
private final static short FID_EF_MenuWording1 = (short)0x1F9A;
private final static short FID_EF_MenuWording2 = (short)0x1F9B;
private final static short FID_EF_MenuWording3 = (short)0x1F9C;
private final static short FID_EF_MenuWording4 = (short)0x1F9D;
private final static short[] FID_EF_MENU_WORDING = {FID_EF_MenuWording1, FID_EF_MenuWording2, FID_EF_MenuWording3, FID_EF_MenuWording4};
private final static byte[] DCS = {(byte)0x04, (byte)0x08, (byte)0x08, (byte)0x08};
private byte menuLanguage; // 0 = English ; 1 = Traditional Chinese ; 2 = Simplified Chinese ; 3 = Japanese
// Device information
private final static short SIZE_ICCID = (short)33; // ICCID
private final static short SIZE_VER = (short)65; // applet version
private final static short SIZE_CARD_TYPE = (short)4;
private final static short SIZE_RESERVE = (short)3;
private final static short OFFSET_ICCID = (short)0;
private final static short OFFSET_VER = OFFSET_ICCID + SIZE_ICCID;
private final static short OFFSET_CARD_TYPE = OFFSET_VER + SIZE_VER;
private final static short OFFSET_RESERVE = OFFSET_CARD_TYPE + SIZE_CARD_TYPE;
private byte[] devInfo;
// PIN/PUK
private final static short MAX_PIN_LEN = (short)8;
private final static short MIN_PIN_LEN = (short)4;
private final static short MAX_PUK_LEN = (short)8;
private final static short PIN_ATTEMPT_NUM = (short)5;
private final static short PUK_ATTEMPT_NUM = (short)6;
private OwnerPIN pin;
private OwnerPIN puk;
private short pinTryCount;
private short unlockTryCount;
private boolean isUnBlockedWithPuk = false;
// BIP Http message
private final static byte[] checkKeyChange = {(byte)'k', (byte)'e', (byte)'y', (byte)'c', (byte)'h', (byte)'a', (byte)'n', (byte)'g', (byte)'e', (byte)'_', (byte)'o', (byte)'k' };
private final static byte[] BIP_HTTP_HEAD = {(byte)'P', (byte)'O', (byte)'S', (byte)'T', (byte)' ', (byte)'/', (byte)' ',(byte)'H', (byte)'T', (byte)'T', (byte)'P', (byte)'/',
(byte)'1', (byte)'.', (byte)'1', (byte)0x0D, (byte)0x0A, (byte)'H', (byte)'o', (byte)'s', (byte)'t', (byte)':', (byte)' '};
private final static byte[] BIP_HTTP_CONTENT1 = {(byte)0x0D, (byte)0x0A, (byte)'U', (byte)'s', (byte)'e', (byte)'r', (byte)'-', (byte)'A', (byte)'g', (byte)'e', (byte)'n', (byte)'t',
(byte)':', (byte)' ', (byte)'t', (byte)'a', (byte)'i', (byte)'s', (byte)'y', (byte)'s', (byte)'_', (byte)'c', (byte)'a', (byte)'r',
(byte)'d', (byte)'/', (byte)'1', (byte)'.', (byte)'0', (byte)0x0D, (byte)0x0A, (byte)'C', (byte)'o', (byte)'n',(byte)'t', (byte)'e',
(byte)'n', (byte)'t', (byte)'-', (byte)'L', (byte)'e', (byte)'n', (byte)'g', (byte)'t', (byte)'h', (byte)':'};
private final static byte[] BIP_HTTP_CONTENT = {(byte)0x0D, (byte)0x0A, (byte)'C', (byte)'o', (byte)'o', (byte)'k', (byte)'i', (byte)'e', (byte)':', (byte)' ', };
private final static byte[] BIP_HTTP_END = {(byte)0x0D, (byte)0x0A, (byte)0x0D, (byte)0x0A };
// BIP key
private final static byte[] MasterSessionKey = {(byte)0x54, (byte)0x68, (byte)0x61, (byte)0x74, (byte)0x73, (byte)0x20, (byte)0x6D, (byte)0x79, (byte)0x20, (byte)0x4B,
(byte)0x75, (byte)0x6E, (byte)0x67, (byte)0x20, (byte)0x46, (byte)0x75, (byte)0x54, (byte)0x68, (byte)0x61, (byte)0x74,
(byte)0x73, (byte)0x20, (byte)0x6D, (byte)0x79, (byte)0x20, (byte)0x4B, (byte)0x75, (byte)0x6E, (byte)0x67, (byte)0x20,
(byte)0x46, (byte)0x75 };
private boolean isProcessingBIP = false;
private boolean isBipRspReady = false;
private boolean isNoService; // Record the previous state service status ,used to decide whether to refresh
private boolean isBETag = true;
private short preToken;
private short currentSerialNum;
private short channel_data_length;
private short ipAndPortRecNum;
private byte channel;
private byte waitDataDownloadTimes;
private byte connectiveStatus; // s = Short connection ; l = long connection ; k = key change
private byte bipPauseCounter;
private byte localStatus; // Record current local status , 0 = Normal service ; 1 = limited service ; 2 = No service
// Proactive tag
private final static byte BEARER_DESCRIPTION_TAG = (byte)0xB5;
private final static byte BUFFER_SIZE_TAG = (byte)0xB9;
private final static byte UICC_TERMINAL_TRANSPORT_LEVEL_TAG = (byte)0xBC;
private final static byte OTHER_DATA_DESTINATION_ADDRESS_TAG = (byte)0xBE;
private final static byte CHANNEL_DATA_TAG = (byte)0xB6;
private final static byte CHANNEL_DATA_LENGTH_TAG = (byte)0xB7;
//====Temporary Buffer
private final static short SIZE_BUFFER_RAM = (short)256;
private final static short SIZE_BUFFER_LARGE = (short)256;
private final static short SIZE_BUFFER_SMALL = (short)64;
private final static short SIZE_RSP_BUFFER = (short)512;
private final static short SIZE_BUFFER_INPUT = (short)16;
private final static short SIZE_PACKET_BUFFER = (short)512;
private final static short SIZE_BUFFER_CHANNEL_DATA = (short)768;
private final static short SIZE_BUFFER_CHANNEL_CIPHERDATA = (short)1024;
private final static short SIZE_DEVICE_INFO = (short)106;
private byte[] largeTmpBuf; // Temporary buffer
private byte[] smallTmpBuf; // Temporary buffer
private byte[] tmpRAM; // Temporary RAM buffer
private byte[] inputBuf; // Use to store input data from user
private byte[] tempBuf; // Temporary buffer
private byte[] BIP_channel_data; // tag channel_data
private byte[] BIP_channel_cipherData; // tag channel_cipherData
private short[] mnemonicCode;
private HMACKey key;
private Signature prf;
private ECPublicKey publicKey;
private ECPrivateKey privateKey;
private Signature signature;
private RandomData random;
private HDUser R;
private HDUser C;
private byte preSignStatus;
private byte hashNum;
private byte signVerifyStatus;
private ToolkitRegistry reg;
// process command
private byte cla;
private byte ins;
private byte P1;
private byte P2;
private short Lc;
private short sw;
private boolean rspReady = false;
private FileView uiccFileView;
private Slimduet(byte[] bArray, short bOffset, byte bLength) {
// Temporary buffer
tmpRAM = JCSystem.makeTransientByteArray(SIZE_BUFFER_RAM, JCSystem.CLEAR_ON_RESET);
tempBuf = JCSystem.makeTransientByteArray((short) 660, JCSystem.CLEAR_ON_RESET);
largeTmpBuf = JCSystem.makeTransientByteArray(SIZE_BUFFER_LARGE, JCSystem.CLEAR_ON_RESET);
BIP_channel_data = JCSystem.makeTransientByteArray(SIZE_BUFFER_CHANNEL_DATA, JCSystem.CLEAR_ON_RESET);
BIP_channel_cipherData = JCSystem.makeTransientByteArray(SIZE_BUFFER_CHANNEL_CIPHERDATA, JCSystem.CLEAR_ON_RESET);
smallTmpBuf = new byte[SIZE_BUFFER_SMALL];
inputBuf = new byte[SIZE_BUFFER_INPUT];
mnemonicCode = new short[MNEMONIC_SIZE];
devInfo = new byte[SIZE_DEVICE_INFO];
SECP256k1.init();
random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
key = (HMACKey) KeyBuilder.buildKey(KeyBuilder.TYPE_HMAC_TRANSIENT_RESET, KeyBuilder.LENGTH_HMAC_SHA_512_BLOCK_128, false);
prf = Signature.getInstance((byte)Signature.ALG_HMAC_SHA_512, true);
signature = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false);
publicKey = (ECPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false);
privateKey = (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false);
SECP256k1.setCurveParameters(publicKey);
SECP256k1.setCurveParameters(privateKey);
pin = new OwnerPIN((byte)PIN_ATTEMPT_NUM, (byte)MAX_PIN_LEN);
puk = new OwnerPIN((byte)PUK_ATTEMPT_NUM, (byte)MAX_PUK_LEN);
pinTryCount = PIN_ATTEMPT_NUM;
unlockTryCount = PUK_ATTEMPT_NUM;
menuLanguage = (byte)0;
hashNum = (byte)0;
channel_data_length = (short)0;
ipAndPortRecNum = (short)0xFF;
channel = (byte)0xFF;
waitDataDownloadTimes = (byte)0;
R = null;
C = null;
// Register the new applet instance to the JCRE
if (bArray[bOffset] == (byte)0)
register();
else
register(bArray, (short)(bOffset+1), bArray[bOffset]); // Register this applet
// get reference
reg = ToolkitRegistrySystem.getEntry();
uiccFileView = UICCSystem.getTheUICCView(JCSystem.CLEAR_ON_RESET);
// Register event
reg.setEvent(EVENT_FIRST_COMMAND_AFTER_ATR);
reg.setEvent(EVENT_EVENT_DOWNLOAD_DATA_AVAILABLE);
reg.setEvent(EVENT_EVENT_DOWNLOAD_LOCATION_STATUS);
reg.setEvent(EVENT_PROFILE_DOWNLOAD);
reg.requestPollInterval((short)30); // Receive Status command every 30 seconds
}
public static void install(byte[] bArray, short bOffset, byte bLength) throws ISOException {
// Create Java SIM toolkit applet
Slimduet applet = new Slimduet(bArray, bOffset, bLength);
}
/* process applet command
* @param apdu
*/
public void process(APDU apdu) throws ISOException {
// Pass selecting AID APDU
if (selectingApplet() == true)
return;
byte[] apduBuf = apdu.getBuffer();
SecureChannel SC = GPSystem.getSecureChannel();
switch((short)(Util.getShort(apduBuf, (short)0)&(short)0xFCFF)) {
case (short)0x8050: // INITIALIZE UPDATE
case (short)0x8482: // EXTERNAL AUTHENTICATION
Lc = SC.processSecurity(apdu);
if (Lc >= (short)0)
apdu.setOutgoingAndSend((short)5, Lc);
return;
case (short)0x80E2: // STORE DATA
case (short)0x84E2:
if (SC.getSecurityLevel() == (short)0)
ISOException.throwIt((short)0x6985);
Lc = SC.unwrap(apduBuf, (short)0, (short)(5 + apdu.setIncomingAndReceive()));
Lc -= (short)5;
sw = processStoredData(apduBuf, (short)0, Lc);
ISOException.throwIt(sw);
return;
}
}
public boolean select(boolean appInstAlreadyActive) {
return true;
}
public void deselect(boolean appInstStillActive) {
}
public void uninstall() {
SECP256k1.cleanAllField();
// Release unused previous objects
JCSystem.requestObjectDeletion();
}
/** Toolkit **/
public void processToolkit(short event) throws ToolkitException {
switch(event) {
case EVENT_FIRST_COMMAND_AFTER_ATR:
init();
break;
case EVENT_PROFILE_DOWNLOAD:
bipPauseCounter += (byte)2;
break;
case EVENT_EVENT_DOWNLOAD_LOCATION_STATUS:
checkCurrentService();
break;
case EVENT_EVENT_DOWNLOAD_DATA_AVAILABLE:
if (bipPauseCounter != (byte)0) {
return;
}
if (channel != (byte)0xFF) { // Open channel success
byte status = (byte)0xFF;
short apduStatus = (short)0;
if (BIP_receiveData() == (byte)0) { // Receive data success
status = BIP_processData(BIP_channel_data, (short)0);
/* status:
* 0 : close channel
* 1 : long polling & don't close channel
* 2 : long pooling & close channel
* 3 : long polling & pross data & close channel
* 4 : server request key change
*/
switch(status) {
case (byte)0:
BIP_closeChannel();
break;
case (byte)1:
break;
case (byte)2:
BIP_closeChannel();
BIP_openChannel();
if (channel != (byte)0xFF) { // Open channel success
BIP_createData((byte)'l');
BIP_sendData();
isProcessingBIP = true;
}
break;
case (byte)3:
BIP_closeChannel();
// proess APDU command
apduStatus = processCMD(BIP_channel_data, (short)((short)smallTmpBuf[0] & 0x00FF));
if (!rspReady)
Lc = (short)0;
// add apdu status word after the response
Util.setShort(BIP_channel_data, Lc, apduStatus);
Lc += (short)2;
BIP_createData((byte)'r');
connectiveStatus = (byte)'r';
BIP_openChannel();
if (channel != (byte)0xFF) { // Open channel success
BIP_sendData();
isProcessingBIP = true;
}
isBipRspReady = false;
break;
case (byte)4:
BIP_closeChannel();
BIP_openChannel();
if (channel != (byte)0xFF) { // Open channel success
BIP_createData((byte)'k');
BIP_sendData();
isProcessingBIP = true;
}
break;
default:
break;
}
}
else {// Receive data fail
BIP_closeChannel();
}
waitDataDownloadTimes = (byte)0;
}
break;
case EVENT_STATUS_COMMAND:
if (isProcessingBIP || isBipRspReady || bipPauseCounter != (byte)0) {
//Close channel after waiting for two status
if (++waitDataDownloadTimes >= (byte)2) {
BIP_closeChannel();
waitDataDownloadTimes = (byte)0;
isBipRspReady = false;
}
if (bipPauseCounter > (byte)0)
bipPauseCounter--;
}
else {
if (localStatus != (byte)2) {
BIP_openChannel();
if (channel != (byte)0xFF) { // Open channel success
if(connectiveStatus != (byte)'r') BIP_createData(connectiveStatus);
BIP_sendData();
isProcessingBIP = true;
}
}
}
break;
}
}
private void init() {
// Temporary Buffer
Util.arrayFillNonAtomic(largeTmpBuf, (short)0, SIZE_BUFFER_LARGE, (byte)0xFF);
Util.arrayFillNonAtomic(smallTmpBuf, (short)0, SIZE_BUFFER_SMALL, (byte)0xFF);
Util.arrayFillNonAtomic(tmpRAM, (short)0, SIZE_BUFFER_RAM, (byte)0xFF);
Util.arrayFillNonAtomic(inputBuf, (short)0, SIZE_BUFFER_INPUT, (byte)0xFF);
// BIP
channel = (byte)0xFF;
isProcessingBIP = false;
isBipRspReady = false;
connectiveStatus = (byte)'k';
bipPauseCounter = (byte)0;
isBETag = true;
rspReady = false;
getDevInfo();
}
private short processStoredData(byte[] apduBuf, short ofs, short apduLen) {
byte pinLength = apduBuf[(short)(ofs + ISO7816.OFFSET_CDATA)];
byte pukLength = apduBuf[(short)(ofs + ISO7816.OFFSET_CDATA + pinLength)];
pin.update(apduBuf, (short)(ofs + ISO7816.OFFSET_CDATA + 1), pinLength);
puk.update(apduBuf, (short)(ofs + ISO7816.OFFSET_CDATA + pinLength + 1), pukLength);
return SW_STATUS_NO_ERROR;
}
private short processCMD(byte[] apduBuf, short offset) {
cla = apduBuf[(short)(offset+ISO7816.OFFSET_CLA)];
ins = apduBuf[(short)(offset+ISO7816.OFFSET_INS)];
P1 = apduBuf[(short)(offset+ISO7816.OFFSET_P1)];
P2 = apduBuf[(short)(offset+ISO7816.OFFSET_P2)];
Lc = (short)(apduBuf[(short)(offset+ISO7816.OFFSET_LC)] & 0xFF);
sw = ISO7816.SW_NO_ERROR;
rspReady = false;
boolean isWalletCmd = true;
switch(ins) {
case INS_QUERY_CARD_INFOR:// E0
if ((cla & (byte)0xFC) != (byte)0x80)
return ISO7816.SW_CLA_NOT_SUPPORTED;
sw = queryWalletInfo(apduBuf, offset, Lc);
break;
case INS_CREATE_WALLET_USER: // E1
if ((cla & (byte)0xFC) != (byte)0x80)
return ISO7816.SW_CLA_NOT_SUPPORTED;
sw = manageWalletsUser(apduBuf, offset, Lc);
break;
case INS_GET_CHILD_PUBLIC_KEY: //E3
if ((cla & (byte)0xFC) != (byte)0x80)
return ISO7816.SW_CLA_NOT_SUPPORTED;
sw = getChildPublicKey(apduBuf, offset, Lc);
break;
case INS_SIGN_TRANSFER: // E4
if ((cla & (byte)0xFC) != (byte)0x80)
return ISO7816.SW_CLA_NOT_SUPPORTED;
sw = signData(apduBuf, offset, Lc);
break;
case INS_SYNCH_WALLET_INFOR: //E5
if ((cla & (byte)0xFC) != (byte)0x80)
return ISO7816.SW_CLA_NOT_SUPPORTED;
sw = synchWalletInfo(apduBuf, offset, Lc);
break;
default:
isWalletCmd = false;
break;
}
if (isWalletCmd) {
if((sw & (short) 0x6F00) == (short) 0x6100) {
Lc = (short)(sw & (short)0xFF);
if (Lc == (short)0)
Lc = (short) 0x100;
sw = SW_STATUS_NO_ERROR;
rspReady = true;
}
return sw;
}
switch(ins) {
case (byte)0x10: // GetDevInfo
// check P1 & P2
if (P1!=(byte)0 || P2!=(byte)0)
return ISO7816.SW_INCORRECT_P1P2;
if (Lc == (short)0) { // Get devInfo length
return (short)(ISO7816.SW_CORRECT_LENGTH_00 | SIZE_DEVICE_INFO);
}
else {
// check length
if (Lc != SIZE_DEVICE_INFO)
return (short)(ISO7816.SW_CORRECT_LENGTH_00 | SIZE_DEVICE_INFO);
Util.arrayFillNonAtomic(apduBuf, (short)0, Lc, (byte)0); // Clean output buffer
Util.arrayCopyNonAtomic(devInfo, (short)0, apduBuf, (short)0, SIZE_DEVICE_INFO);
rspReady = true;
}
return sw;
default:
sw = ISO7816.SW_COMMAND_NOT_ALLOWED;
break;
}
return sw;
}
private void sendDisplayText(byte qualifier, byte dcs, byte[] buffer, short offset, short length) throws ToolkitException{
try{
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
prohandler.initDisplayText(qualifier, dcs, buffer, offset, length);
prohandler.send();
}catch(ToolkitException e){
if(e.getReason() == ToolkitException.HANDLER_NOT_AVAILABLE)
ToolkitException.throwIt(ToolkitException.HANDLER_NOT_AVAILABLE);
}
}
public short getInput(byte qualifier, byte dcs ,byte[] displayMsg, short displayMsgLen, short inputMinLen, short inputMaxLen, byte[] textBuf, short textBufOfs) throws ToolkitException{
try{
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
ProactiveResponseHandler proRspHandler = ProactiveResponseHandlerSystem.getTheHandler();
byte inputRes = (byte)0;
if(dcs != (byte)0)
prohandler.initGetInput(qualifier, dcs, displayMsg, (short)0, displayMsgLen, inputMinLen, inputMaxLen);
else
prohandler.initGetInput(qualifier, displayMsg[0], displayMsg, (short)1, (short)(displayMsgLen-1), inputMinLen, inputMaxLen);
prohandler.send();
inputMinLen = proRspHandler.copyTextString(textBuf, textBufOfs);
inputMinLen--; // Subtract string ending byte '/0'
}catch(ToolkitException e){
switch(e.getReason()){
case ToolkitException.HANDLER_NOT_AVAILABLE:
ToolkitException.throwIt(ToolkitException.HANDLER_NOT_AVAILABLE);
break;
case ToolkitException.UNAVAILABLE_ELEMENT:
ToolkitException.throwIt(ToolkitException.UNAVAILABLE_ELEMENT);
break;
}
}
return inputMinLen;
}
private short getWording(byte[] itemData, short itemOfs, short itemNum, short DF, short EF) {
if(uiccFileView == null)
uiccFileView = UICCSystem.getTheUICCView(JCSystem.CLEAR_ON_RESET);
short cnt = (short)0;
short tmpOfs = (short)0;
short tmpLength = (short)0;
uiccFileView.select((short)0x3F00);
uiccFileView.select(DF);
uiccFileView.select(EF);
for (cnt=(short)0; cnt<itemNum; cnt++) {
uiccFileView.readBinary(tmpOfs, itemData, itemOfs, (short)1);
tmpLength = (short)(itemData[itemOfs] & 0xFF);
tmpOfs += (short)(tmpLength + 1);
}
uiccFileView.readBinary(tmpOfs, itemData, itemOfs, (short)1);
tmpLength = (short)(itemData[itemOfs] & 0xFF);
uiccFileView.readBinary((short)(tmpOfs+1), itemData, itemOfs, (short)tmpLength);
return tmpLength;
}
private void getLinearFixedFileItem(short recNum, byte[] bArray, short DF, short EF, short length) {
if(uiccFileView == null)
uiccFileView = UICCSystem.getTheUICCView(JCSystem.CLEAR_ON_RESET);
uiccFileView.select(DF);
uiccFileView.select(EF);
uiccFileView.readRecord(recNum, (byte)0x04, (short)0, bArray, (short)0, length);
}
/** Device
DEVICE_INFO (106) {
ICCID[33] // ICCID
VER[65] // applet version
CARD_TYPE[4] // 00 00 06 00
PIN_STATUS[1] // PIN status (0: unmodified, 1: modified)
RESERVE[3] // 00 00 00
}
*/
private void getDevInfo() {
Util.arrayFillNonAtomic(devInfo, (short)0, SIZE_DEVICE_INFO, (byte)0x00);
if (uiccFileView == null)
uiccFileView = UICCSystem.getTheUICCView(JCSystem.CLEAR_ON_RESET);
// bip id
short length = getCardID(tmpRAM);
if (tmpRAM[0] != (byte)0) {
Util.arrayCopyNonAtomic(tmpRAM, (short)0, devInfo, (short)(OFFSET_ICCID+1), length);
devInfo[OFFSET_ICCID] = (byte)length;
}
// version
Util.setShort(tmpRAM, (short)0, appletVersion);
simomeTool.convertHexToAscii(tmpRAM, (short)0, devInfo, (short)(OFFSET_VER+1), (short)2);
devInfo[OFFSET_VER] = (byte)4;
if (testVersion != (byte)0xFF) {
devInfo[(short)(OFFSET_VER+5)] = (byte)' ';
devInfo[(short)(OFFSET_VER+6)] = (byte)'T';
devInfo[(short)(OFFSET_VER+7)] = (byte)'e';
devInfo[(short)(OFFSET_VER+8)] = (byte)'s';
devInfo[(short)(OFFSET_VER+9)] = (byte)'t';
devInfo[(short)(OFFSET_VER+10)] = testVersion;
devInfo[OFFSET_VER] = (byte)10;
}
// card type
Util.setShort(devInfo, (short)(OFFSET_CARD_TYPE+2), (short)0x0987);
// reserve
}
private short getCardID(byte[] bArray) {
short i, j;
short length = (short)0;
if(uiccFileView == null)
uiccFileView = UICCSystem.getTheUICCView(JCSystem.CLEAR_ON_RESET);
try {
uiccFileView.select((short)0x3F00);
uiccFileView.select(FID_DF_BIP);
uiccFileView.select(FID_EF_CARD_ID);
uiccFileView.readBinary((short)0, bArray, (short)0, (short)1);
length = (short)(bArray[0] & 0xFF);
uiccFileView.readBinary((short)1, bArray, (short)(length * 2), length);
length *= (short)2;
for (i=length, j=(short)0; j<length; i++, j+=2) {
bArray[j] = (byte)((bArray[i] & 0x0F) + 0x30);
bArray[(short)(j+1)] = (byte)((byte)((byte)(bArray[i] >> 4) & 0x0F) + 0x30);
}
}
catch (UICCException u) {
Util.arrayFillNonAtomic(bArray, (short)0, (short)16, (byte)0);
}
return length;
}
private void getTerminalImei(byte[] outputBuff, short outputOffset) {
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
byte generalRes = (byte)0xFF;
prohandler.init(PRO_CMD_PROVIDE_LOCAL_INFORMATION, (byte)0x01, DEV_ID_TERMINAL);
prohandler.send();
ProactiveResponseHandler proRspHandler = ProactiveResponseHandlerSystem.getTheHandler();
generalRes = proRspHandler.getGeneralResult();
if (generalRes == (byte)0x00) { // Success
proRspHandler.findAndCopyValue(TAG_IMEI, outputBuff, outputOffset);
}
}
private void sendRefresh() {
isNoService = false;
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
prohandler.init(PRO_CMD_REFRESH, (byte)0x04, DEV_ID_TERMINAL);
prohandler.send();
}
private void checkCurrentService() {
EnvelopeHandler envhandler = EnvelopeHandlerSystem.getTheHandler();
envhandler.findAndCopyValue(TAG_LOCATION_STATUS, smallTmpBuf, (short)5);
localStatus = smallTmpBuf[5];
if (localStatus == (byte)2)
isNoService = true;
}
private void BIP_openChannel() {
// If channel does not close yet, then close it before open.
if (channel != (byte)0xFF)
BIP_closeChannel();
if (bipPauseCounter != (byte)0)
return;
short port;
short i = (short)1;
short current_rec = (ipAndPortRecNum <= (short)3 && ipAndPortRecNum > (short)0)? ipAndPortRecNum : (short)1;
byte generalRes = (byte)0xFF;
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
do {
Util.arrayFillNonAtomic(tmpRAM, (short)4, (short)4, (byte)0xFF); //indiate emptyAddress
tmpRAM[8] = (byte)0xBE;
tmpRAM[9] = (byte)0x00;
getLinearFixedFileItem(current_rec, tmpRAM, FID_DF_BIP, FID_EF_BIP_Port, (short)2);
port = Util.getShort(tmpRAM, (short)0);
getLinearFixedFileItem(current_rec, tmpRAM, FID_DF_BIP, FID_EF_BIP_IP, (short)4);
if (Util.arrayCompare(tmpRAM, (short)0, tmpRAM, (short)4, (short)4) != 0) {
prohandler.init(PRO_CMD_OPEN_CHANNEL, (byte)0x03, DEV_ID_TERMINAL);
prohandler.appendTLV(BEARER_DESCRIPTION_TAG, (byte)0x03); // Default bearer
prohandler.appendTLV(BUFFER_SIZE_TAG, (short)0x05DC);
if (isBETag) // iPhone12 can't use tag "BE"
prohandler.appendArray(tmpRAM, (short)8, (short)2); // Add "BE 00"
prohandler.appendTLV(UICC_TERMINAL_TRANSPORT_LEVEL_TAG, (byte)0x02, port); // TCP, port number
prohandler.appendTLV(OTHER_DATA_DESTINATION_ADDRESS_TAG, (byte)0x21, tmpRAM, (short)0, (short)4);
prohandler.send();
ProactiveResponseHandler proRspHandler = ProactiveResponseHandlerSystem.getTheHandler();
generalRes = proRspHandler.getGeneralResult();
if(generalRes == RES_ERROR_CMD_BEYOND_TERMINAL_CAPAB){
isBETag = !isBETag;
prohandler.init(PRO_CMD_OPEN_CHANNEL, (byte)0x03, DEV_ID_TERMINAL);
prohandler.appendTLV(BEARER_DESCRIPTION_TAG, (byte)0x03); // Default bearer
prohandler.appendTLV(BUFFER_SIZE_TAG, (short)0x05DC);
if(isBETag)
prohandler.appendArray(tmpRAM, (short)8, (short)2); // Add "BE 00"
prohandler.appendTLV(UICC_TERMINAL_TRANSPORT_LEVEL_TAG, (byte)0x02, port); // TCP, port number
prohandler.appendTLV(OTHER_DATA_DESTINATION_ADDRESS_TAG, (byte)0x21, tmpRAM, (short)0, (short)4);
prohandler.send();
generalRes = proRspHandler.getGeneralResult();
}
if(generalRes < (byte)0x0A) { // Success
channel = proRspHandler.getChannelIdentifier();
ipAndPortRecNum = current_rec;
return;
}
else if (generalRes == RES_ERROR_BEARER_INDEPENDENT_PROTOCOL_ERROR && localStatus != (byte)2 && isNoService) {
sendRefresh();
}
}
current_rec = (current_rec == (short)3) ? (short)1 : current_rec++;
i++;
} while(i <= (short)3);
}
private void BIP_closeChannel() {
if (channel == (byte)0xFF)
return;
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
prohandler.initCloseChannel((byte)(0x20+channel));
prohandler.send();
}
private void BIP_sendData() {
short ofs = (short)0;
short length = channel_data_length;
tmpRAM[0] = CHANNEL_DATA_TAG;
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
while (length >= (short)0x00F0) {
prohandler.init(PRO_CMD_SEND_DATA, (byte)0x01, (byte)(0x20+channel));
Util.setShort(tmpRAM, (short)1, (short)0x81F0);
Util.arrayCopyNonAtomic(BIP_channel_cipherData, ofs, tmpRAM, (short)3, (short)0x00F0);
prohandler.appendArray(tmpRAM, (short)0, (short)0x00F3);
prohandler.send();
ofs += (short)0x00F0;
length -= (short)0x00F0;
}
if (length > (short)0x007F) {
prohandler.init(PRO_CMD_SEND_DATA, (byte)0x01, (byte)(0x20+channel));
tmpRAM[1] = (byte)0x81;
tmpRAM[2] = (byte)length;
Util.arrayCopyNonAtomic(BIP_channel_cipherData, ofs, tmpRAM, (short)3, length);
prohandler.appendArray(tmpRAM, (short)0, (short)(length + 3));
prohandler.send();
}
else if (length > (short)0) {
prohandler.init(PRO_CMD_SEND_DATA, (byte)0x01, (byte)(0x20+channel));
tmpRAM[1] = (byte)length;
Util.arrayCopyNonAtomic(BIP_channel_cipherData, ofs, tmpRAM, (short)2, length);
prohandler.appendArray(tmpRAM, (short)0, (short)(length + 2));
prohandler.send();
}
if(connectiveStatus == (byte)'r') connectiveStatus = (byte)'l';
}
private byte BIP_receiveData() {
if(bipPauseCounter != (byte)0)
return (byte)1;
short len = (short)0;
short cnt = (short)0;
short totalLength = (short)0;
byte generalRes = (byte)0xFF;
byte flag = (short)0;
ProactiveHandler prohandler = ProactiveHandlerSystem.getTheHandler();
ProactiveResponseHandler proRspHandler;
EnvelopeHandler envhandler = EnvelopeHandlerSystem.getTheHandler();
envhandler.findAndCopyValue(TAG_CHANNEL_DATA_LENGTH, smallTmpBuf, (short)0);
while (smallTmpBuf[0] != (byte)0x00) { // Still have data
prohandler.init(PRO_CMD_RECEIVE_DATA, (byte)0, (byte)(0x20+channel));
prohandler.appendTLV(CHANNEL_DATA_LENGTH_TAG, smallTmpBuf[0]);
prohandler.send();
proRspHandler = ProactiveResponseHandlerSystem.getTheHandler();
generalRes = proRspHandler.getGeneralResult();
if (generalRes < (byte)0x20) {
if (flag == (byte)0) {
proRspHandler.findAndCopyValue(TAG_CHANNEL_DATA_LENGTH, smallTmpBuf, (short)0);
len = proRspHandler.findAndCopyValue(TAG_CHANNEL_DATA, largeTmpBuf, (short)0);
for (cnt=(short)0; cnt<len; cnt++) {
if (largeTmpBuf[cnt]==(byte)0x0D && largeTmpBuf[(short)(cnt+1)]==(byte)0x0A && largeTmpBuf[(short)(cnt+2)]==(byte)0x0D && largeTmpBuf[(short)(cnt+3)]==(byte)0x0A) {
// Skip 0D 0A 0D 0A
if (cnt != (short)0) {
//skip second 0D 0A 0D 0A
cnt += (short)8;
len -= cnt;
}
else {
cnt += (short)4;
len -= cnt;
}
Util.arrayCopyNonAtomic(largeTmpBuf, (short)(cnt+4), BIP_channel_data, (short)0, len);
totalLength = len;
flag = (byte)1;
break;
}
}
}
else {
len = proRspHandler.copyChannelData(BIP_channel_data, (short)totalLength, (short)((short)smallTmpBuf[0] & 0x00FF));
proRspHandler.findAndCopyValue(TAG_CHANNEL_DATA_LENGTH, smallTmpBuf, (short)0);
}
}
else
return 1;
}
return (byte)0;
}
private void BIP_createData(byte connective) {
short tagLen = (short)0;
short bufOfs = (short)0;
short responseDataLen = (short)0;
if (connective == (byte)'r') {
responseDataLen = Lc;
responseDataLen = simomeTool.convertHexToBase64Url(BIP_channel_data,(short)0, responseDataLen, BIP_channel_cipherData, (short)0);
}
// connectiveStatus
BIP_channel_data[bufOfs++] = (byte)connective;
tagLen++;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
// token
random.generateData(tmpRAM, (short)0, (short)4);
preToken = Util.getShort(tmpRAM, (short)0);
simomeTool.convertHexToAscii(tmpRAM, (short)0, BIP_channel_data, bufOfs, (short)2);
bufOfs += (short)4;
tagLen += (short)4;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
switch(connective) {
case's':
case'l':
// pogarm
BIP_channel_data[bufOfs++] = (byte)0x01;
tagLen++;
// You can do encryption here
Util.arrayCopyNonAtomic(BIP_channel_data, (short)0, BIP_channel_cipherData, (short)0, tagLen);
// conver to Base64Url
tagLen = simomeTool.convertHexToBase64Url(BIP_channel_cipherData,(short)0, tagLen, BIP_channel_data, (short)0);
responseDataLen = tagLen;
break;
case'r':
// pogarm
BIP_channel_data[bufOfs++] = (byte)0x01;
tagLen++;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
// serial number
Util.setShort(tmpRAM, (short)0, currentSerialNum);
simomeTool.convertHexToAscii(tmpRAM, (short)0, BIP_channel_data, bufOfs, (short)2);
bufOfs += (short)4;
tagLen += (short)4;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
// response data
Util.arrayCopyNonAtomic(BIP_channel_cipherData, (short)0, BIP_channel_data, bufOfs, responseDataLen);
bufOfs += responseDataLen;
tagLen += responseDataLen;
// TODO : You can do encryption here
Util.arrayCopyNonAtomic(BIP_channel_data, (short)0, BIP_channel_cipherData, (short)0, tagLen);
// conver to Base64Url
tagLen = simomeTool.convertHexToBase64Url(BIP_channel_cipherData,(short)0, tagLen, BIP_channel_data, (short)0);
responseDataLen = tagLen;
break;
case'k':
// get seesion key
responseDataLen = simomeTool.convertHexToBase64Url(MasterSessionKey,(short)0, (short)MasterSessionKey.length, BIP_channel_data, bufOfs);
bufOfs += responseDataLen;
tagLen += responseDataLen;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
// IMEI
getTerminalImei(tmpRAM,(short)0);
simomeTool.convertHexToAscii(tmpRAM, (short)0, BIP_channel_data, bufOfs, (short)8);
bufOfs += (short)16;
tagLen += (short)16;
BIP_channel_data[bufOfs++] = (byte)'/';
tagLen++;
//TODO : You can do encryption here
Util.arrayCopyNonAtomic(BIP_channel_data, (short)0, BIP_channel_cipherData, (short)0, tagLen);
// conver to Base64Url
tagLen = simomeTool.convertHexToBase64Url(BIP_channel_cipherData,(short)0, tagLen, BIP_channel_data, (short)0);
responseDataLen = tagLen;
break;
}