/
JCESecurityModule.java
2503 lines (2300 loc) · 98 KB
/
JCESecurityModule.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
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2022 jPOS Software SRL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.security.jceadapter;
import org.javatuples.Pair;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.core.Environment;
import org.jpos.iso.ISODate;
import org.jpos.iso.ISOException;
import org.jpos.iso.ISOUtil;
import org.jpos.q2.QClassLoader;
import org.jpos.security.*;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import org.jpos.util.SimpleMsg;
import javax.crypto.SecretKey;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.security.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
/**
* JCESecurityModule is an implementation of a security module in software.
* <p>
* It doesn't require any hardware device to work.<br>
* JCESecurityModule also implements the SMAdapter, so you can view it: either
* as a self contained security module adapter that doesn't need a security module
* or a security module that plugs directly to jpos, so doesn't need
* a separate adapter.<br>
* It relies on Java(tm) Cryptography Extension (JCE), hence its name.<br>
* JCESecurityModule relies on the JCEHandler class to do the low level JCE work.
* <p>
* WARNING: This version of JCESecurityModule is meant for testing purposes and
* NOT for life operation, since the Local Master Keys are stored in CLEAR on
* the system's disk. Comming versions of JCESecurity Module will rely on
* java.security.KeyStore for a better protection of the Local Master Keys.
*
* @author Hani Samuel Kirollos
* @author Robert Demski
* @version $Revision$ $Date$
*/
@SuppressWarnings("unchecked")
public class JCESecurityModule extends BaseSMAdapter<SecureDESKey> {
/**
* Pattern representing key type string value.
*/
private static final Pattern KEY_TYPE_PATTERN = Pattern.compile("([^:;]*)([:;])?([^:;])?([^:;])?");
/**
* Pattern for split two clear pins.
*/
private static final Pattern SPLIT_PIN_PATTERN = Pattern.compile("[ :;,/.]");
/**
* NUmber of LMK pairs
*/
private final static int LMK_PAIRS_NO = 0xe;
/**
* LMK variants appled to first byte of LMK pair
*/
private final static int[] variants = {
0x00, 0xa6, 0x5a, 0x6a, 0xde, 0x2b, 0x50, 0x74, 0x9c,0xfa
};
/**
* LMK scheme variants appiled to first byte of second key in pair
*/
private final static int[] schemeVariants = {
0x00, 0xa6, 0x5a, 0x6a, 0xde, 0x2b
};
/**
* Index of scheme variant for left LMK key for double length keys
*/
private final static int KEY_U_LEFT = 1;
/**
* Index of scheme variant for right LMK key for double length keys
*/
private final static int KEY_U_RIGHT = 2;
/**
* Index of scheme variant for left LMK key for triple length keys
*/
private final static int KEY_T_LEFT = 3;
/**
* Index of scheme variant for middle LMK key for triple length keys
*/
private final static int KEY_T_MEDIUM = 4;
/**
* Index of scheme variant for right LMK key for triple length keys
*/
private final static int KEY_T_RIGHT = 5;
private static MessageDigest SHA1_MESSAGE_DIGEST = null;
private static final byte[] _VARIANT_RIGHT_HALF = new byte[]
{
(byte) 0xC0, (byte) 0xC0, (byte) 0xC0, (byte) 0xC0,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
static {
try {
SHA1_MESSAGE_DIGEST = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException ex) {} //NOPMD: SHA-1 is a standard digest
}
/**
* Creates an uninitialized JCE Security Module, you need to setConfiguration to initialize it
*/
public JCESecurityModule () {
super();
}
/**
* @param lmkFile Local Master Keys filename of the JCE Security Module
* @throws SMException
*/
public JCESecurityModule (String lmkFile) throws SMException
{
Objects.requireNonNull(lmkFile);
init(null, lmkFile, false);
}
public JCESecurityModule (String lmkFile, String jceProviderClassName) throws SMException
{
Objects.requireNonNull(lmkFile);
init(jceProviderClassName, lmkFile, false);
}
public JCESecurityModule (Configuration cfg, Logger logger, String realm) throws ConfigurationException
{
setLogger(logger, realm);
setConfiguration(cfg);
}
/**
* Configures a JCESecurityModule
* @param cfg The following properties are read:<br>
* lmk: Local Master Keys file (The only required parameter)<br>
* jce: JCE Provider Class Name, if not provided, it defaults to: com.sun.crypto.provider.SunJCE<br>
* rebuildlmk: (true/false), rebuilds the Local Master Keys file with new keys (WARNING: old keys will be erased)<br>
* cbc-mac: Cipher Block Chaining MAC algorithm name for given JCE Provider.<br>
* Default is ISO9797ALG3MACWITHISO7816-4PADDING from BouncyCastle provider (known as Retail-MAC)<br>
* that is suitable for most of interfaces with double length MAC key<br>
* ANSI X9.19 aka ISO/IEC 9797-1 MAC algorithm 3 padding method 2 - ISO7816<br>
* ede-mac: Encrypt Decrypt Encrypt MAC algorithm name for given JCE Provider.<br>
* Default is DESEDEMAC from BouncyCastle provider<br>
* that is suitable for BASE24 with double length MAC key<br>
* ANSI X9.19<br>
* @throws ConfigurationException
*/
@Override
public void setConfiguration (Configuration cfg) throws ConfigurationException {
this.cfg = cfg;
try {
init(cfg.get("provider"), cfg.get("lmk", null), cfg.getBoolean("rebuildlmk"));
} catch (SMException e) {
throw new ConfigurationException(e);
}
}
@Override
public SecureDESKey generateKeyImpl (short keyLength, String keyType) throws SMException {
Key generatedClearKey = jceHandler.generateDESKey(keyLength);
return encryptToLMK(keyLength, keyType, generatedClearKey);
}
@Override
public SecureDESKey importKeyImpl (short keyLength, String keyType, byte[] encryptedKey,
SecureDESKey kek, boolean checkParity) throws SMException {
// decrypt encrypted key
Key clearKEY = jceHandler.decryptDESKey(keyLength, encryptedKey, decryptFromLMK(kek),
checkParity);
// Encrypt Key under LMK
return encryptToLMK(keyLength, keyType, clearKEY);
}
@Override
public byte[] exportKeyImpl (SecureDESKey key, SecureDESKey kek) throws SMException {
// get key in clear
Key clearKey = decryptFromLMK(key);
// Encrypt key under kek
return jceHandler.encryptDESKey(key.getKeyLength(), clearKey, decryptFromLMK(kek));
}
private int getKeyTypeIndex (short keyLength, String keyType) throws SMException {
int index;
if (keyType==null)
return 0;
String majorType = getMajorType(keyType);
if (!keyTypeToLMKIndex.containsKey(majorType))
throw new SMException("Unsupported key type: " + majorType);
index = keyTypeToLMKIndex.get(majorType);
index |= getVariant(keyType) << 8;
return index;
}
private static String getMajorType (String keyType) {
Matcher m = KEY_TYPE_PATTERN.matcher(keyType);
m.find();
if (m.group(1) != null)
return m.group(1);
throw new IllegalArgumentException("Missing key type");
}
private static int getVariant (String keyType) {
int variant = 0;
Matcher m = KEY_TYPE_PATTERN.matcher(keyType);
m.find();
if (m.group(3) != null)
try {
variant = Integer.valueOf(m.group(3));
} catch (NumberFormatException ex){
throw new NumberFormatException("Value "+m.group(4)+" is not valid key variant");
}
return variant;
}
private static KeyScheme getScheme (int keyLength, String keyType) {
KeyScheme scheme = KeyScheme.Z;
switch (keyLength){
case SMAdapter.LENGTH_DES:
scheme = KeyScheme.Z; break;
case SMAdapter.LENGTH_DES3_2KEY:
scheme = KeyScheme.X; break;
case SMAdapter.LENGTH_DES3_3KEY:
scheme = KeyScheme.Y; break;
}
if (keyType==null)
return scheme;
Matcher m = KEY_TYPE_PATTERN.matcher(keyType);
m.find();
if (m.group(4) != null)
try {
scheme = KeyScheme.valueOf(m.group(4));
} catch (IllegalArgumentException ex){
throw new IllegalArgumentException("Value "+m.group(4)+" is not valid key scheme");
}
return scheme;
}
@Override
public EncryptedPIN encryptPINImpl (String pin, String accountNumber) throws SMException {
byte[] clearPINBlock = calculatePINBlock(pin, FORMAT00, accountNumber);
// Encrypt
byte[] translatedPINBlock = jceHandler.encryptData(clearPINBlock, getLMK(PINLMKIndex));
return new EncryptedPIN(translatedPINBlock, FORMAT00, accountNumber, false);
}
@Override
public String decryptPINImpl (EncryptedPIN pinUnderLmk) throws SMException {
byte[] clearPINBlock = jceHandler.decryptData(pinUnderLmk.getPINBlock(),
getLMK(PINLMKIndex));
return calculatePIN(clearPINBlock, pinUnderLmk.getPINBlockFormat(), pinUnderLmk.getAccountNumber());
}
@Override
public EncryptedPIN importPINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1) throws SMException {
// read inputs
String accountNumber = pinUnderKd1.getAccountNumber();
// Use FORMAT00 for encrypting PIN under LMK
byte destinationPINBlockFormat = FORMAT00;
// get clear PIN
byte[] clearPINBlock = jceHandler.decryptData(pinUnderKd1.getPINBlock(),
decryptFromLMK(kd1));
// extract clear pin (as entered by card holder)
String pin = calculatePIN(clearPINBlock, pinUnderKd1.getPINBlockFormat(),
accountNumber);
// Format PIN Block using proprietary FORMAT00 to be encrypetd under LMK
clearPINBlock = calculatePINBlock(pin, destinationPINBlockFormat, accountNumber);
// encrypt PIN
byte[] translatedPINBlock = jceHandler.encryptData(clearPINBlock, getLMK(PINLMKIndex));
return new EncryptedPIN(translatedPINBlock, destinationPINBlockFormat,
accountNumber, false);
}
@Override
public EncryptedPIN exportPINImpl (EncryptedPIN pinUnderLmk, SecureDESKey kd2,
byte destinationPINBlockFormat) throws SMException {
String accountNumber = pinUnderLmk.getAccountNumber();
// process
// get clear PIN
byte[] clearPINBlock = jceHandler.decryptData(pinUnderLmk.getPINBlock(),
getLMK(PINLMKIndex));
// extract clear pin
String pin = calculatePIN(clearPINBlock, pinUnderLmk.getPINBlockFormat(),
accountNumber);
clearPINBlock = calculatePINBlock(pin, destinationPINBlockFormat, accountNumber);
// encrypt PIN
byte[] translatedPINBlock = jceHandler.encryptData(clearPINBlock, decryptFromLMK(kd2));
return new EncryptedPIN(translatedPINBlock, destinationPINBlockFormat,
accountNumber, false);
}
@Override
public EncryptedPIN generatePINImpl(String accountNumber, int pinLen, List<String> excludes)
throws SMException {
if (excludes==null)
excludes = Arrays.asList();
String pin;
{
Random rd = new SecureRandom();
int max = (int)Math.pow(10, Math.min(pinLen, 9));
int max2 = (int)Math.pow(10, Math.max(pinLen - 9,0));
do {
long pinl = rd.nextInt(max);
if (pinLen > 9){
pinl *= max2;
pinl += rd.nextInt(max2);
}
pin = ISOUtil.zeropad(pinl, pinLen);
} while (excludes.contains(pin));
}
return encryptPINImpl(pin, accountNumber);
}
/**
* Visa way to decimalize data block
* @param b
* @return decimalized data string
*/
private static String decimalizeVisa(byte[] b){
char[] bec = ISOUtil.hexString(b).toUpperCase().toCharArray();
char[] bhc = new char[bec.length];
int k = 0;
//Select 0-9 chars
for ( char c : bec )
if (c<'A')
bhc[k++] = c;
//Select A-F chars and map them to 0-5
char adjust = 'A'-'0';
for ( char c : bec )
if (c>='A')
bhc[k++] = (char) (c-adjust);
return new String(bhc);
}
protected Key concatKeys(SecureDESKey keyA, SecureDESKey keyB)
throws SMException {
if ( keyA!=null && keyA.getKeyLength()==SMAdapter.LENGTH_DES
&& keyB!=null && keyB.getKeyLength()==SMAdapter.LENGTH_DES) {
Key cvkAclear = decryptFromLMK(keyA);
Key cvkBclear = decryptFromLMK(keyB);
return jceHandler.formDESKey(SMAdapter.LENGTH_DES3_2KEY
,ISOUtil.concat(cvkAclear.getEncoded(), cvkBclear.getEncoded()));
}
if (keyA!=null && keyA.getKeyLength()!=SMAdapter.LENGTH_DES)
return decryptFromLMK(keyA);
if (keyB!=null && keyB.getKeyLength()!=SMAdapter.LENGTH_DES)
return decryptFromLMK(keyB);
return null;
}
protected String calculateCVV(String accountNo, Key cvk, Date expDate,
String serviceCode) throws SMException {
String ed = ISODate.formatDate(expDate, "yyMM");
return calculateCVD(accountNo, cvk, ed, serviceCode);
}
protected String calculateCVD(String accountNo, Key cvk, String expDate,
String serviceCode) throws SMException {
Key udka = jceHandler.formDESKey(SMAdapter.LENGTH_DES
,Arrays.copyOfRange(cvk.getEncoded(), 0, 8));
byte[] block = ISOUtil.hex2byte(
ISOUtil.zeropadRight(accountNo
+ expDate
+ serviceCode, 32));
byte[] ba = Arrays.copyOfRange(block, 0, 8);
byte[] bb = Arrays.copyOfRange(block, 8,16);
//Encrypt ba with udka
byte[] bc = jceHandler.encryptData(ba, udka);
byte[] bd = ISOUtil.xor(bc, bb);
//Encrypt bd Tripple DES
byte[] be = jceHandler.encryptData(bd, cvk);
return decimalizeVisa(be).substring(0,3);
}
@Override
protected String calculateCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
Date expDate, String serviceCode) throws SMException {
return calculateCVV(accountNo,concatKeys(cvkA, cvkB),expDate,serviceCode);
}
@Override
protected String calculateCVDImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
String expDate, String serviceCode) throws SMException {
return calculateCVD(accountNo, concatKeys(cvkA, cvkB), expDate, serviceCode);
}
protected void checkCAVVArgs(String upn, String authrc, String sfarc)
throws SMException {
if (upn == null)
throw new SMException("Unpredictable Number can not be null");
if (authrc == null)
throw new SMException("Authorization Result Code can not be null");
if (sfarc == null)
throw new SMException("Secend Factor Authorization Result Code"
+ " can not be null");
if (upn.length() != 4 )
throw new SMException("Length of Unpredictable Number"
+ " must be 4 but got "+upn.length());
if (authrc.length() != 1 )
throw new SMException("Length of Authorization Result Code"
+ " must be 1 but got "+authrc.length());
if (sfarc.length() != 2 )
throw new SMException("Length of Secend Factor Authorization Result"
+ " Code must be 2 but got "+sfarc.length());
}
@Override
protected String calculateCAVVImpl(String accountNo, SecureDESKey cvk, String upn,
String authrc, String sfarc) throws SMException {
checkCAVVArgs(upn, authrc,sfarc);
return calculateCVD(accountNo,concatKeys(cvk, null),upn,authrc+sfarc);
}
@Override
protected boolean verifyCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
String cvv, Date expDate, String serviceCode) throws SMException {
String result = calculateCVV(accountNo, concatKeys(cvkA, cvkB), expDate, serviceCode);
return result.equals(cvv);
}
@Override
protected boolean verifyCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
String cvv, String expDate, String serviceCode) throws SMException {
String result = calculateCVD(accountNo, concatKeys(cvkA, cvkB), expDate, serviceCode);
return result.equals(cvv);
}
@Override
protected boolean verifyCAVVImpl(String accountNo, SecureDESKey cvk, String cavv,
String upn, String authrc, String sfarc) throws SMException {
checkCAVVArgs(upn, authrc,sfarc);
String result = calculateCVD(accountNo, concatKeys(cvk, null), upn, authrc+sfarc);
return result.equals(cavv);
}
protected String calculatedCVV(String accountNo, SecureDESKey imkac,
String expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
throws SMException {
if (mkdm==null)
mkdm = MKDMethod.OPTION_A;
byte[] panpsn = formatPANPSN_dCVD(accountNo, null, mkdm);
Key mkac = deriveICCMasterKey(decryptFromLMK(imkac), panpsn);
String alteredPAN = ISOUtil.hexString(atc) + accountNo.substring(4);
return calculateCVD(alteredPAN, mkac, expDate, serviceCode);
}
@Override
protected boolean verifydCVVImpl(String accountNo, SecureDESKey imkac, String dcvv,
Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
throws SMException {
String ed = ISODate.formatDate(expDate, "yyMM");
String res = calculatedCVV(accountNo, imkac, ed,
serviceCode, atc, mkdm
);
return res.equals(dcvv);
}
@Override
protected boolean verifydCVVImpl(String accountNo, SecureDESKey imkac, String dcvv,
String expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
throws SMException {
String res = calculatedCVV(accountNo, imkac, expDate,
serviceCode, atc, mkdm
);
return res.equals(dcvv);
}
protected String calculateCVC3(SecureDESKey imkcvc3, String accountNo, String acctSeqNo,
byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm)
throws SMException {
if (mkdm==null)
mkdm = MKDMethod.OPTION_A;
byte[] panpsn = formatPANPSN_dCVD(accountNo, acctSeqNo, mkdm);
Key mkcvc3 = deriveICCMasterKey(decryptFromLMK(imkcvc3), panpsn);
byte[] ivcvc3 = data;
if (ivcvc3.length != 2)
//Compute IVCVC3
ivcvc3 = calculateIVCVC3(mkcvc3, data);
//Concatenate IVCVC3, UPN and ATC
byte[] b = ISOUtil.concat(ivcvc3, upn);
b = ISOUtil.concat(b, atc);
//Encrypt prepared blok
b = jceHandler.encryptData(b, mkcvc3);
//Format last two bytes to integer
int cvc3l = (b[6] & 0xff) << 8;
cvc3l |= b[7] & 0xff;
//Convert to string representation
return String.format("%05d",cvc3l);
}
@Override
protected boolean verifyCVC3Impl(SecureDESKey imkcvc3, String accountNo, String acctSeqNo,
byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3)
throws SMException {
String calcCVC3 = calculateCVC3(imkcvc3, accountNo, acctSeqNo,
atc, upn, data, mkdm
);
cvc3 = cvc3==null?"":cvc3;
//get some last digits
calcCVC3 = calcCVC3.substring(5-cvc3.length());
return calcCVC3.equals(cvc3);
}
private byte[] calculateIVCVC3(Key mkcvc3, byte[] data)
throws JCEHandlerException {
byte[] paddedData = paddingISO9797Method2(data);
byte[] mac = calculateMACISO9797Alg3(mkcvc3, paddedData);
return Arrays.copyOfRange(mac,6,8);
}
/**
* ISO/IEC 9797-1 padding method 2
* @param d da to be padded
* @return padded data
*/
private byte[] paddingISO9797Method2(byte[] d) {
//Padding - first byte 0x80 rest 0x00
byte[] t = new byte[d.length - d.length%8 + 8];
System.arraycopy(d, 0, t, 0, d.length);
for (int i=d.length;i<t.length;i++)
t[i] = (byte)(i==d.length?0x80:0x00);
d = t;
return d;
}
/**
* Calculate MAC according to ISO/IEC 9797-1 Alg 3
* @param key DES double length key
* @param d data to calculate MAC on it
* @return 8 byte of mac value
* @throws JCEHandlerException
*/
private byte[] calculateMACISO9797Alg3(Key key, byte[] d) throws JCEHandlerException {
Key kl = jceHandler.formDESKey(SMAdapter.LENGTH_DES
,Arrays.copyOfRange(key.getEncoded(), 0, 8));
Key kr = jceHandler.formDESKey(SMAdapter.LENGTH_DES
,Arrays.copyOfRange(key.getEncoded(), 8, 16));
if (d.length%8 != 0) {
//Padding with 0x00 bytes
byte[] t = new byte[d.length - d.length%8 + 8];
System.arraycopy(d, 0, t, 0, d.length);
d = t;
}
//MAC_CBC alg 3
byte[] y_i = ISOUtil.hex2byte("0000000000000000");
byte[] yi = new byte[8];
for ( int i=0;i<d.length;i+=8){
System.arraycopy(d, i, yi, 0, yi.length);
y_i = jceHandler.encryptData(ISOUtil.xor(yi, y_i), kl);
}
y_i = jceHandler.decryptData(y_i, kr);
y_i = jceHandler.encryptData(y_i, kl);
return y_i;
}
/**
* Prepare 8-bytes data from PAN and PAN Sequence Number.
* <p>
* Used at EMV operations: {@link #verifyARQCImpl ARQC verification},
* {@link #generateARPCImpl ARPC generation},
* {@link #generateSM_MACImpl secure message MAC generation}
* and {@link #translatePINGenerateSM_MACImpl secure message PIN translation}
*/
private static byte[] formatPANPSN(String pan, String psn, MKDMethod mkdm)
throws SMException {
switch (mkdm){
case OPTION_A:
return formatPANPSNOptionA(pan, psn);
case OPTION_B:
if ( pan.length() <= 16)
//use OPTION_A
return formatPANPSNOptionA(pan, psn);
return formatPANPSNOptionB(pan, psn);
default:
throw new SMException("Unsupported ICC Master Key derivation method");
}
}
/**
* Prepare 8-bytes data from PAN and PAN Sequence Number.
* <p>
* Used at dCVV verification {@link #verifydCVVImpl verifydCVV}
* and CVC3 {@link #verifyCVC3Impl verifyCVC3}
*/
private static byte[] formatPANPSN_dCVD(String pan, String psn, MKDMethod mkdm)
throws SMException {
switch (mkdm){
case OPTION_A:
return formatPANPSNOptionA(pan, psn);
case OPTION_B:
return formatPANPSNOptionB(pan, psn);
default:
throw new SMException("Unsupported ICC Master Key derivation method");
}
}
/**
* Format bytes representing Application PAN and
* PAN Sequence Number in BCD format.
* <p>
* Concatenate from left to right decimal digits of PAN and
* PAN Sequence Number digits. If {@code psn} is not present, it is
* replaced by a "00" digits. If the result is less than 16 digits long,
* pad it to the left with hexadecimal zeros in order to obtain an
* 16-digit number. If the Application PAN has an odd number of decimal
* digits then concatenate a "0" padding digit to the left thereby
* ensuring that the result is an even number of digits.
*
* @param pan application primary account number
* @param psn PAN Sequence Number
* @return up to 11 bytes representing Application PAN
*/
private static byte[] preparePANPSN(String pan, String psn){
if (psn == null || psn.isEmpty())
psn = "00";
String ret = pan + psn;
//convert digits to bytes and padd with "0"
//to left for ensure even number of digits
return ISOUtil.hex2byte(ret);
}
/**
* Prepare 8-bytes data from PAN and PAN Sequence Number (Option A)
* <ul>
* <li> Prepare Application PAN and PAN Sequence Number by {@see #preparePANPSN}
* <li> Select first 16 digits
* </ul>
* @param pan application primary account number
* @param psn PAN Sequence Number
* @return 8-bytes representing first 16 digits
*/
private static byte[] formatPANPSNOptionA(String pan, String psn){
if ( pan.length() < 14 )
try {
pan = ISOUtil.zeropad(pan, 14);
} catch( ISOException ex ) {} //NOPMD: ISOException condition is checked before.
byte[] b = preparePANPSN(pan, psn);
return Arrays.copyOfRange(b, b.length-8, b.length);
}
/**
* Prepare bytes data from PAN and PAN Sequence Number (Option B)
*
* <h5>Do the following:</h5>
* <ul>
* <li> Prepare Application PAN and PAN Sequence Number by {@see #preparePANPSN}
* <li> Hash the prepared result using the SHA-1 hashing algorithm
* to obtain the 20-byte hash result
* <li> Decimalize result of hasing by {@see #decimalizeVisa }
* <li> Select first 16 decimal digits
* </ul>
* @param pan application primary account number
* @param psn PAN Sequence Number
* @return 8-bytes representing first 16 decimalised digits
*/
private static byte[] formatPANPSNOptionB(String pan, String psn){
byte[] b = preparePANPSN(pan, psn);
//20-bytes sha-1 digest
byte[] r = SHA1_MESSAGE_DIGEST.digest(b);
//decimalized HEX string of digest
String rs = decimalizeVisa(r);
//return 16-bytes decimalizd digest
return ISOUtil.hex2byte(rs.substring(0,16));
}
/**
* Derive ICC Master Key from Issuer Master Key and preformated PAN/PANSeqNo
*
* Compute two 8-byte numbers:
* <li> left part is a result of Tripple-DES encription {@code panpsn}
* with {@code imk} as the key
* <li> right part is a result of Tripple-DES binary inverted
* {@code panpsn} with {@code imk} as the key
* <li> concatenate left and right parts
* <br>
* Described in EMV v4.2 Book 2, Annex A1.4.1 Master Key Derivation point 2
*
* @param imk 16-bytes Issuer Master Key
* @param panpsn preformated PAN and PAN Sequence Number
* @return derived 16-bytes ICC Master Key with adjusted DES parity
* @throws JCEHandlerException
*/
protected Key deriveICCMasterKey(Key imk, byte[] panpsn)
throws JCEHandlerException {
byte[] l = Arrays.copyOfRange(panpsn, 0, 8);
//left part of derived key
l = jceHandler.encryptData(l, imk);
byte[] r = Arrays.copyOfRange(panpsn, 0, 8);
//inverse clear right part of key
r = ISOUtil.xor(r, JCESecurityModule.fPaddingBlock);
//right part of derived key
r = jceHandler.encryptData(r,imk);
//derived key
byte[] mk = ISOUtil.concat(l,r);
//fix DES parity of key
Util.adjustDESParity(mk);
//form JCE Tripple-DES Key
return jceHandler.formDESKey(SMAdapter.LENGTH_DES3_2KEY, mk);
}
protected String calculatePVV(EncryptedPIN pinUnderLmk, Key key, int keyIdx
,List<String> excludes) throws SMException {
String pin = decryptPINImpl(pinUnderLmk);
if (excludes!=null && excludes.contains(pin))
throw new WeakPINException("Given PIN is on excludes list");
String block = pinUnderLmk.getAccountNumber().substring(1);
block += Integer.toString(keyIdx%10);
block += pin.substring(0, 4);
byte[] b = ISOUtil.hex2byte(block);
b = jceHandler.encryptData(b, key);
return decimalizeVisa(b).substring(0,4);
}
@Override
protected String calculatePVVImpl(EncryptedPIN pinUnderLmk, SecureDESKey pvkA,
SecureDESKey pvkB, int pvkIdx, List<String> excludes)
throws SMException {
Key key = concatKeys(pvkA, pvkB);
return calculatePVV(pinUnderLmk, key, pvkIdx, excludes);
}
@Override
protected String calculatePVVImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx,
List<String> excludes) throws SMException {
Key key = concatKeys(pvkA, pvkB);
EncryptedPIN pinUnderLmk = importPINImpl(pinUnderKd1, kd1);
return calculatePVV(pinUnderLmk, key, pvkIdx, excludes);
}
@Override
public boolean verifyPVVImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA,
SecureDESKey pvkB, int pvki, String pvv) throws SMException {
Key key = concatKeys(pvkA, pvkB);
EncryptedPIN pinUnderLmk = importPINImpl(pinUnderKd1, kd1);
String result = calculatePVV(pinUnderLmk, key, pvki, null);
return result.equals(pvv);
}
@Override
public EncryptedPIN translatePINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
EncryptedPIN translatedPIN;
Key clearKd1 = decryptFromLMK(kd1);
Key clearKd2 = decryptFromLMK(kd2);
translatedPIN = translatePINExt(null, pinUnderKd1, clearKd1, clearKd2
,destinationPINBlockFormat, null, PaddingMethod.MCHIP);
return translatedPIN;
}
private EncryptedPIN translatePINExt (EncryptedPIN oldPinUnderKd1, EncryptedPIN pinUnderKd1, Key kd1,
Key kd2, byte destinationPINBlockFormat, Key udk, PaddingMethod padm) throws SMException {
String accountNumber = pinUnderKd1.getAccountNumber();
// get clear PIN
byte[] clearPINBlock = jceHandler.decryptData(pinUnderKd1.getPINBlock(), kd1);
String pin = calculatePIN(clearPINBlock, pinUnderKd1.getPINBlockFormat(),
accountNumber);
// Reformat PIN Block
byte[] translatedPINBlock;
if (isVSDCPinBlockFormat(destinationPINBlockFormat)) {
String udka = ISOUtil.hexString(Arrays.copyOfRange(udk.getEncoded(), 0, 8));
if (destinationPINBlockFormat == SMAdapter.FORMAT42 ) {
byte[] oldClearPINBlock = jceHandler.decryptData(oldPinUnderKd1.getPINBlock(), kd1);
String oldPIN = calculatePIN(oldClearPINBlock, oldPinUnderKd1.getPINBlockFormat(),
accountNumber);
clearPINBlock = calculatePINBlock(pin+":"+oldPIN, destinationPINBlockFormat, udka);
} else
clearPINBlock = calculatePINBlock(pin, destinationPINBlockFormat, udka);
accountNumber = udka.substring(4);
} else {
clearPINBlock = calculatePINBlock(pin, destinationPINBlockFormat, accountNumber);
}
switch(padm){
case VSDC:
//Add VSDC pin block padding
clearPINBlock = ISOUtil.concat(new byte[]{0x08}, clearPINBlock);
clearPINBlock = paddingISO9797Method2(clearPINBlock);
break;
case CCD:
//Add CCD pin block padding
clearPINBlock = paddingISO9797Method2(clearPINBlock);
break;
default:
}
// encrypt PIN
if (padm == PaddingMethod.CCD)
translatedPINBlock = jceHandler.encryptDataCBC(clearPINBlock, kd2
,Arrays.copyOf(zeroBlock, zeroBlock.length));
else
translatedPINBlock = jceHandler.encryptData(clearPINBlock, kd2);
return new EncryptedPIN(translatedPINBlock
,destinationPINBlockFormat, accountNumber, false);
}
/**
* Derive the session key used for Application Cryptogram verification
* or for secure messaging, the diversification value is the ATC
* @param mkac unique ICC Master Key for Application Cryptogams or Secure Messaging
* @param atc ICC generated Application Transaction Counter as diversification value
* @return derived 16-bytes Session Key with adjusted DES parity
* @throws JCEHandlerException
*/
private Key deriveSK_VISA(Key mkac, byte[] atc) throws JCEHandlerException {
byte[] skl = new byte[8];
System.arraycopy(atc, atc.length-2, skl, 6, 2);
skl = ISOUtil.xor(skl, Arrays.copyOfRange(mkac.getEncoded(),0 ,8));
byte[] skr = new byte[8];
System.arraycopy(atc, atc.length-2, skr, 6, 2);
skr = ISOUtil.xor(skr, ISOUtil.hex2byte("000000000000FFFF"));
skr = ISOUtil.xor(skr, Arrays.copyOfRange(mkac.getEncoded(),8 ,16));
Util.adjustDESParity(skl);
Util.adjustDESParity(skr);
return jceHandler.formDESKey(SMAdapter.LENGTH_DES3_2KEY, ISOUtil.concat(skl,skr));
}
/**
* Common Session Key Derivation Method for secure messaging.
* <p>
* The diversification value is the <em>RAND</em>, which is ARQC
* incremeted by 1 (with overflow) after each script command
* for that same ATC value.
* Described in EMV v4.2 Book 2, Annex A1.3.1 Common Session Key
* Derivation Option for secure messaging.
*
* @param mksm unique ICC Master Key for Secure Messaging
* @param rand Application Cryptogram as diversification value
* @return derived 16-bytes Session Key with adjusted DES parity
* @throws JCEHandlerException
*/
private Key deriveCommonSK_SM(Key mksm, byte[] rand) throws JCEHandlerException {
byte[] rl = Arrays.copyOf(rand,8);
rl[2] = (byte)0xf0;
byte[] skl = jceHandler.encryptData(rl, mksm);
byte[] rr = Arrays.copyOf(rand,8);
rr[2] = (byte)0x0f;
byte[] skr = jceHandler.encryptData(rr, mksm);
Util.adjustDESParity(skl);
Util.adjustDESParity(skr);
return jceHandler.formDESKey(SMAdapter.LENGTH_DES3_2KEY, ISOUtil.concat(skl,skr));
}
/**
* Common Session Key Derivation Method for Application Cryptograms.
* <p>
* Described in EMV v4.2 Book 2, Annex A1.3.1 Common Session Key Derivation
* Option for Application Cryptograms.
*
* @param mkac unique ICC Master Key for Application Cryptogams.
* @param atc ICC generated Application Transaction Counter as diversification value.
* @return derived 16-bytes Session Key with adjusted DES parity.
* @throws JCEHandlerException
*/
private Key deriveCommonSK_AC(Key mkac, byte[] atc) throws JCEHandlerException {
byte[] r = new byte[8];
System.arraycopy(atc, atc.length-2, r, 0, 2);
return deriveCommonSK_SM(mkac, r);
}
/**
* MasterCard Proprietary Session Key Derivation (SKD) method.
* <p>
* Described in M/Chip 4 version 1.1 Security & Key Management manual
* paragraph 7 ICC Session Key Derivation.
*
* @param mkac unique ICC Master Key for Application Cryptogams
* @param atc ICC generated Application Transaction Counter as diversification value
* @param upn terminal generated random as diversification value
* @return derived 16-bytes Session Key with adjusted DES parity
* @throws JCEHandlerException
*/
private Key deriveSK_MK(Key mkac, byte[] atc, byte[] upn) throws JCEHandlerException {
byte[] r = new byte[8];
System.arraycopy(atc, atc.length-2, r, 0, 2);
System.arraycopy(upn, upn.length-4, r, 4, 4);
return deriveCommonSK_SM(mkac, r);
}
private void constraintMKDM(MKDMethod mkdm, SKDMethod skdm) throws SMException {
if (mkdm == MKDMethod.OPTION_B)
throw new SMException("Master Key Derivation Option B"
+ " is not used in practice with scheme "+skdm);
}
private void constraintARPCM(SKDMethod skdm, ARPCMethod arpcMethod) throws SMException {
if (arpcMethod == ARPCMethod.METHOD_2 )
throw new SMException("ARPC generation method 2"
+ " is not used in practice with scheme "+skdm);
}
/**
* Calculate ARQC.
* <p>
* Entry point e.g. for simulator systems
*/
protected byte[] calculateARQC(MKDMethod mkdm, SKDMethod skdm
,SecureDESKey imkac, String accountNo, String accntSeqNo, byte[] atc
,byte[] upn, byte[] transData) throws SMException {
if (mkdm==null)
mkdm = MKDMethod.OPTION_A;
byte[] panpsn = formatPANPSN(accountNo, accntSeqNo, mkdm);
Key mkac = deriveICCMasterKey(decryptFromLMK(imkac), panpsn);
Key skac = mkac;
switch(skdm){
case VSDC:
constraintMKDM(mkdm, skdm);
break;
case MCHIP:
constraintMKDM(mkdm, skdm);
skac = deriveSK_MK(mkac,atc,upn);
break;
case EMV_CSKD:
skac = deriveCommonSK_AC(mkac, atc);
break;
default:
throw new SMException("Session Key Derivation "+skdm+" not supported");
}
return calculateMACISO9797Alg3(skac, transData);
}
@Override
protected boolean verifyARQCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accountNo, String accntSeqNo, byte[] arqc, byte[] atc
,byte[] upn, byte[] transData) throws SMException {
byte[] res = calculateARQC(mkdm, skdm, imkac, accountNo, accntSeqNo
,atc, upn, transData);
return Arrays.equals(arqc, res);
}
@Override
public byte[] generateARPCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accountNo, String accntSeqNo, byte[] arqc, byte[] atc, byte[] upn
,ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
throws SMException {
if (mkdm==null)
mkdm = MKDMethod.OPTION_A;
byte[] panpsn = formatPANPSN(accountNo, accntSeqNo, mkdm);
Key mkac = deriveICCMasterKey(decryptFromLMK(imkac), panpsn);
Key skarpc = mkac;
switch(skdm){
case VSDC:
constraintMKDM(mkdm, skdm);
constraintARPCM(skdm, arpcMethod);
break;
case MCHIP: