001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package  org.jpos.security;
020
021import org.javatuples.Pair;
022
023import java.security.MessageDigest;
024import java.security.PublicKey;
025import java.security.spec.AlgorithmParameterSpec;
026import java.util.Date;
027import java.util.List;
028import java.util.Map;
029
030
031/**
032 * A class that implements the SMAdapter interface would act as an
033 * adapter to the real security module device (by communicating with it using
034 * its proprietary protocol).
035 *
036 * But application programmers will be communicating
037 * with the security module using this simple interface.
038 *
039 * TODO: support for EMV card/issuer RSA generation API's
040 *
041 * @author Hani S. Kirollos
042 * @author Robert Demski
043 * @version $Revision$ $Date$
044 */
045public interface SMAdapter<T> {
046    /**
047     * DES Key Length <code>LENGTH_DES</code> = 64.
048     */
049    short LENGTH_DES = 64;
050    /**
051     * Triple DES (2 keys) <code>LENGTH_DES3_2KEY</code> = 128.
052     */
053    short LENGTH_DES3_2KEY = 128;
054    /**
055     * Triple DES (3 keys) <code>LENGTH_DES3_3KEY</code> = 192.
056     */
057    short LENGTH_DES3_3KEY = 192;
058    /**
059     * ZMK: Zone Master Key is a DES (or Triple-DES) key-encryption key which is distributed
060     * manually in order that further keys can be exchanged automatically.
061     */
062    String TYPE_ZMK = "ZMK";
063
064    /**
065     * ZPK: Zone PIN Key.
066     *
067     * is a DES (or Triple-DES) data-encrypting key which is distributed
068     * automatically and is used to encrypt PINs for transfer between
069     * communicating parties (e.g. between acquirers and issuers).
070     */
071    String TYPE_ZPK = "ZPK";
072
073    /**
074     * TMK: Terminal Master Key.
075     *
076     * is a  DES (or Triple-DES) key-encrypting key which is distributed
077     * manually, or automatically under a previously installed TMK. It is
078     * used to distribute data-encrypting keys, whithin a local network,
079     * to an ATM or POS terminal or similar.
080     */
081    String TYPE_TMK = "TMK";
082
083    /**
084     * TPK: Terminal PIN Key.
085     *
086     * is a  DES (or Triple-DES) data-encrypting key which is used
087     * to encrypt PINs for transmission, within a local network,
088     * between the terminal and the terminal data acquirer.
089     */
090    String TYPE_TPK = "TPK";
091
092    /**
093     * TAK: Terminal Authentication Key.
094     *
095     * is a  DES (or Triple-DES) data-encrypting key which is used to
096     * generate and verify a Message Authentication Code (MAC) when data
097     * is transmitted, within a local network, between the terminal and
098     * the terminal data acquirer.
099     */
100    String TYPE_TAK = "TAK";
101
102    /**
103     * PVK: PIN Verification Key.
104     * is a  DES (or Triple-DES) data-encrypting key which is used to
105     * generate and verify PIN verification data and thus verify the
106     * authenticity of a PIN.
107     */
108    String TYPE_PVK = "PVK";
109
110    /**
111     * CVK: Card Verification Key.
112     *
113     * is similar for PVK but for card information instead of PIN
114     */
115    String TYPE_CVK = "CVK";
116
117    /**
118     * BDK: Base Derivation Key.
119     * is a  Triple-DES key-encryption key used to derive transaction
120     * keys in DUKPT (see ANSI X9.24)
121     */
122    String TYPE_BDK = "BDK";
123
124    /**
125     * ZAK: Zone Authentication Key.
126     *
127     * a  DES (or Triple-DES) data-encrypting key that is distributed
128     * automatically, and is used to generate and verify a Message
129     * Authentication Code (MAC) when data is transmitted between
130     * communicating parties (e.g. between acquirers and issuers)
131     */
132    String TYPE_ZAK = "ZAK";
133
134    /**
135     * MK-AC: Issuer Master Key for generating and verifying
136     * Application Cryptograms.
137     */
138    String TYPE_MK_AC = "MK-AC";
139
140    /**
141     * MK-SMI: Issuer Master Key for Secure Messaging Integrity.
142     *
143     * is a Triple-DES key which is used to generating Message
144     * Authrntication Codes (MAC) for scripts send to EMV chip cards.
145     */
146    String TYPE_MK_SMI = "MK-SMI";
147
148    /**
149     * MK-SMC: Issuer Master Key for Secure Messaging Confidentiality.
150     *
151     * is a Triple-DES data-encrypting key which is used to encrypt
152     * data (e.g. PIN block) in scripts send to EMV chip cards.
153     */
154    String TYPE_MK_SMC = "MK-SMC";
155
156    /**
157     * MK-CVC3: Issuer Master Key for generating and verifying
158     * Card Verification Code 3 (CVC3).
159     */
160    String TYPE_MK_CVC3 = "MK-CVC3";
161
162    /**
163     * MK-DAC Issuer Master Key for generating and verifying
164     * Data Authentication Codes.
165     */
166    String TYPE_MK_DAC = "MK-DAC";
167
168    /**
169     * MK-DN: Issuer Master Key for generating and verifying
170     * Dynamic Numbers.
171     */
172    String TYPE_MK_DN = "MK-DN";
173
174    /**
175     * ZEK: Zone Encryption Key.
176     */
177    String TYPE_ZEK = "ZEK";
178
179    /**
180     * DEK: Data Encryption Key.
181     */
182    String TYPE_DEK = "DEK";
183
184    /**
185     * RSA: Private Key.
186     */
187    String TYPE_RSA_SK = "RSA_SK";
188
189    /**
190     * HMAC: Hash Message Authentication Code <i>(with key usage)</i>.
191     */
192    String TYPE_HMAC   = "HMAC";
193
194    /**
195     * RSA: Public Key.
196     */
197    String TYPE_RSA_PK = "RSA_PK";
198
199    /**
200     * PIN Block Format adopted by ANSI (ANSI X9.8) and is one of
201     * two formats supported by the ISO (ISO 95641 - format 0).
202     */
203    byte FORMAT01 = (byte)01;
204
205    /**
206     * PIN Block Format 02 supports Douctel ATMs.
207     */
208    byte FORMAT02 = (byte)02;
209
210    /**
211         * PIN Block Format 03 is the Diabold Pin Block format.
212         */
213    byte FORMAT03 = (byte)03;
214
215    /**
216     * PIN Block Format 04 is the PIN block format adopted
217     * by the PLUS network.
218     */
219    byte FORMAT04 = (byte)04;
220
221    /**
222     * PIN Block Format 05 is the ISO 9564-1 Format 1 PIN Block.
223     */
224    byte FORMAT05 = (byte)05;
225
226    /**
227     * PIN Block Format 34 is the standard EMV PIN block format.
228     * Is only avaliable as output of EMV PIN change commands.
229     */
230    byte FORMAT34 = (byte)34;
231
232    /**
233     * PIN Block Format 35 is the required by Europay/MasterCard
234     * for their Pay Now & Pay Later products.
235     */
236    byte FORMAT35 = (byte)35;
237
238    /**
239     * PIN Block Format 41 is the Visa format for PIN change
240     * without using the current PIN.
241     */
242    byte FORMAT41 = (byte)41;
243
244    /**
245     * PIN Block Format 42 is the Visa format for PIN change
246     * using the current (old) PIN.
247     */
248    byte FORMAT42 = (byte)42;
249
250    /**
251     * Proprietary PIN Block format.
252     * <p>
253     * Most Security Modules use a proprietary PIN Block format
254     * when encrypting the PIN under the LMK of the Security Module
255     * hence this format (FORMAT00).
256     *
257     * <p>
258     * This is not a standard format, every Security Module would
259     * interpret FORMAT00 differently.
260     *
261     * So, no interchange would accept PIN Blocks from other interchanges
262     * using this format. It is useful only when working with PIN's inside
263     * your own interchange.
264     * </p>
265     */
266    byte FORMAT00 = (byte)00;
267
268    /**
269     * Generates a random DES Key.
270     *
271     * @param keyType type of the key to be generated (TYPE_ZMK, TYPE_TMK...etc)
272     * @param keyLength bit length of the key to be generated (LENGTH_DES, LENGTH_DES3_2KEY...)
273     * @return the random key secured by the security module<BR>
274     * @throws SMException
275     */
276    SecureDESKey generateKey(short keyLength, String keyType) throws SMException;
277
278    /**
279     * Generates a random Key.
280     *
281     * @param keySpec the specification of the key to be generated
282     *               (length, type, usage, algorithm, etc)
283     * @return the random key secured by the security module
284     * @throws SMException
285     * @see SecureKeySpec
286     */
287    SecureKey generateKey(SecureKeySpec keySpec) throws SMException;
288
289
290    /**
291     * Generates key check value.
292     *
293     * @param kd the key with untrusted or fake Key Check Value
294     * @return key check value bytes
295     * @throws SMException
296     */
297    byte[] generateKeyCheckValue(T kd) throws SMException;
298
299
300
301    /**
302     * Translate Key Scheme to more secure encription.
303     * <p>
304     * Converts an DES key encrypted using X9.17 methods to a more secure
305     * key using the variant method.
306     *
307     * @param key key to be translated to {@code destKeyScheme} scheme
308     * @param keyScheme destination key scheme
309     * @return translated key with {@code destKeyScheme} scheme
310     * @throws SMException
311     */
312    SecureDESKey translateKeyScheme(SecureDESKey key, KeyScheme keyScheme)
313      throws SMException;
314
315
316
317    /**
318     * Imports a key from encryption under a KEK (Key-Encrypting Key)
319     * to protection under the security module.
320     *
321     * @param keyLength bit length of the key to be imported (LENGTH_DES, LENGTH_DES3_2KEY...etc)
322     * @param keyType type of the key to be imported (TYPE_ZMK, TYPE_TMK...etc)
323     * @param encryptedKey key to be imported encrypted under KEK
324     * @param kek the key-encrypting key
325     * @param checkParity if true, the key is not imported unless it has adjusted parity
326     * @return imported key secured by the security module
327     * @throws SMException if the parity of the imported key is not adjusted AND checkParity = true
328     */
329    SecureDESKey importKey(short keyLength, String keyType, byte[] encryptedKey,
330                           SecureDESKey kek, boolean checkParity) throws SMException;
331
332    /**
333     * Imports a key from encryption under a KEK (Key-Encrypting Key)
334     * to protection under the security module.
335     *
336     * @param kek the key-encrypting key
337     * @param key key to be imported and encrypted under KEK
338     * @param keySpec the specification of the key to be imported. It allows
339     *        passing or change key block attributes.
340     * @param checkParity if {@code true}, the key is not imported unless it has
341     *        adjusted parity
342     * @return imported key secured by the security module
343     * @throws SMException e.g: if the parity of the imported key is not adjusted
344     *         and {@code checkParity} is {@code true}
345     */
346    SecureKey importKey(SecureKey kek, SecureKey key, SecureKeySpec keySpec, boolean checkParity)
347            throws SMException;
348
349
350    /**
351     * Exports secure key to encryption under a KEK (Key-Encrypting Key).
352     * @param key the secure key to be exported
353     * @param kek the key-encrypting key
354     * @return the exported key (key encrypted under kek)
355     * @throws SMException
356     */
357    byte[] exportKey(SecureDESKey key, SecureDESKey kek) throws SMException;
358
359    /**
360     * Exports secure key to encryption under a KEK (Key-Encrypting Key).
361     *
362     * @param kek the key-encrypting key
363     * @param key the secure key to be exported
364     * @param keySpec the specification of the key to be exported. It allows
365     *        passing or change key block attributes.
366     * @return the exported key (key encrypted under kek)
367     * @throws SMException
368     */
369    SecureKey exportKey(SecureKey kek, SecureKey key, SecureKeySpec keySpec)
370            throws SMException;
371
372    /**
373     * Encrypts a clear pin under LMK.
374     *
375     * <p>CAUTION: The use of clear pin presents a significant security risk
376     * @param pin clear pin as entered by card holder
377     * @param accountNumber account number, including BIN and the check digit
378     * @return PIN under LMK
379     * @throws SMException
380     */
381    EncryptedPIN encryptPIN(String pin, String accountNumber) throws SMException;
382
383    /**
384     * Encrypts a clear pin under LMK.
385     *
386     * <p>CAUTION: The use of clear pin presents a significant security risk
387     * @param pin clear pin as entered by cardholder
388     * @param accountNumber if <code>extract</code> is false then account number, including BIN and the check digit
389     *        or if parameter <code>extract</code> is true then 12 right-most digits of the account number, excluding the check digit
390     * @param extract true to extract 12 right-most digits off the account number
391     * @return PIN under LMK
392     * @throws SMException
393     */
394    EncryptedPIN encryptPIN(String pin, String accountNumber, boolean extract) throws SMException;
395
396    /**
397     * Encrypts a clear PIN under PEK.
398     *
399     * <p>CAUTION: The use of clear PIN presents a significant security risk.
400     * @param pin Clear PIN as entered by cardholder.
401     * @param accountNumber account number, including BIN and the check digit.
402     * @param pek PIN encryption key.
403     * @return Return PIN under PEK.
404     * @throws SMException
405     */
406    EncryptedPIN encryptPIN(String pin, String accountNumber, T pek) throws SMException;
407
408    /**
409     * Decrypts an Encrypted PIN (under LMK).
410     * <p>CAUTION: The use of clear pin presents a significant security risk
411     * @param pinUnderLmk
412     * @return clear pin as entered by card holder
413     * @throws SMException
414     */
415    String decryptPIN(EncryptedPIN pinUnderLmk) throws SMException;
416
417    /**
418     * Imports a PIN from encryption under KD (Data Key)
419     * to encryption under LMK.
420     *
421     * @param pinUnderKd1 the encrypted PIN
422     * @param kd1 Data Key under which the pin is encrypted
423     * @return pin encrypted under LMK
424     * @throws SMException
425     */
426    EncryptedPIN importPIN(EncryptedPIN pinUnderKd1, T kd1) throws SMException;
427
428
429
430    /**
431     * Translates a PIN from encrytion under KD1 to encryption under KD2.
432     *
433     * @param pinUnderKd1 pin encrypted under KD1
434     * @param kd1 Data Key (also called session key) under which the pin is encrypted
435     * @param kd2 the destination Data Key 2 under which the pin will be encrypted
436     * @param destinationPINBlockFormat the PIN Block Format of the exported encrypted PIN
437     * @return pin encrypted under KD2
438     * @throws SMException
439     */
440    EncryptedPIN translatePIN(EncryptedPIN pinUnderKd1, T kd1,
441                              T kd2, byte destinationPINBlockFormat) throws SMException;
442
443
444
445    /**
446     * Imports a PIN from encryption under a transaction key to encryption
447     * under LMK.
448     *
449     * <p>The transaction key is derived from the Key Serial Number and the Base Derivation Key using DUKPT (Derived Unique Key per Transaction). See ANSI X9.24 for more information.
450     * @deprecated Use signature that specifies tdes flag.
451     * @param pinUnderDuk pin encrypted under a transaction key
452     * @param ksn Key Serial Number (also called Key Name, in ANSI X9.24) needed to derive the transaction key
453     * @param bdk Base Derivation Key, used to derive the transaction key underwhich the pin is encrypted
454     * @return pin encrypted under LMK
455     * @throws SMException
456     */
457    @Deprecated
458    EncryptedPIN importPIN(EncryptedPIN pinUnderDuk, KeySerialNumber ksn, T bdk)
459            throws SMException;
460
461    /**
462     * Imports a PIN from encryption under a transaction key to encryption
463     * under LMK.
464     *
465     * <p>The transaction key is derived from the Key Serial Number and the Base Derivation Key using DUKPT (Derived Unique Key per Transaction). See ANSI X9.24 for more information.
466     * @param pinUnderDuk pin encrypted under a transaction key
467     * @param ksn Key Serial Number (also called Key Name, in ANSI X9.24) needed to derive the transaction key
468     * @param bdk Base Derivation Key, used to derive the transaction key underwhich the pin is encrypted
469     * @param tdes Use Triple DES to calculate derived transaction key.
470     * @return pin encrypted under LMK
471     * @throws SMException
472     */
473    EncryptedPIN importPIN(EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
474                           T bdk, boolean tdes) throws SMException;
475
476
477
478    /**
479     * Translates a PIN from encryption under a transaction key to
480     * encryption under a KD (Data Key).
481     *
482     * <p>The transaction key is derived from the Key Serial Number and the Base Derivation Key using DUKPT (Derived Unique Key per Transaction). See ANSI X9.24 for more information.
483     * @deprecated Use signature that specifies tdes flag.
484     * @param pinUnderDuk pin encrypted under a DUKPT transaction key
485     * @param ksn Key Serial Number (also called Key Name, in ANSI X9.24) needed to derive the transaction key
486     * @param bdk Base Derivation Key, used to derive the transaction key underwhich the pin is encrypted
487     * @param kd2 the destination Data Key (also called session key) under which the pin will be encrypted
488     * @param destinationPINBlockFormat the PIN Block Format of the translated encrypted PIN
489     * @return pin encrypted under kd2
490     * @throws SMException
491     */
492    @Deprecated
493    EncryptedPIN translatePIN(EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
494                              T bdk, T kd2, byte destinationPINBlockFormat) throws SMException;
495
496
497    /**
498     * Translates a PIN from encryption under a transaction key to
499     * encryption under a KD (Data Key).
500     *
501     * <p>The transaction key is derived from the Key Serial Number and the Base Derivation Key using DUKPT (Derived Unique Key per Transaction). See ANSI X9.24 for more information.
502     * @param pinUnderDuk pin encrypted under a DUKPT transaction key
503     * @param ksn Key Serial Number (also called Key Name, in ANSI X9.24) needed to derive the transaction key
504     * @param bdk Base Derivation Key, used to derive the transaction key underwhich the pin is encrypted
505     * @param kd2 the destination Data Key (also called session key) under which the pin will be encrypted
506     * @param destinationPINBlockFormat the PIN Block Format of the translated encrypted PIN
507     * @param tdes Use Triple DES to calculate derived transaction key.
508     * @return pin encrypted under kd2
509     * @throws SMException
510     */
511    EncryptedPIN translatePIN(EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
512                              T bdk, T kd2, byte destinationPINBlockFormat, boolean tdes) throws SMException;
513
514
515
516    /**
517     * Exports a PIN from encryption under LMK to encryption under a KD
518     * (Data Key).
519     *
520     * @param pinUnderLmk pin encrypted under LMK
521     * @param kd2 the destination data key (also called session key) under which the pin will be encrypted
522     * @param destinationPINBlockFormat the PIN Block Format of the exported encrypted PIN
523     * @return pin encrypted under kd2
524     * @throws SMException
525     */
526    EncryptedPIN exportPIN(EncryptedPIN pinUnderLmk, T kd2, byte destinationPINBlockFormat) throws SMException;
527
528
529
530    /**
531     * Generate random pin under LMK
532     *
533     * @param accountNumber The 12 right-most digits of the account number excluding the check digit
534     * @param pinLen length of the pin, usually in range 4-12.
535     *               Value 0 means that default length is assumed by HSM (usually 4)
536     * @return generated PIN under LMK
537     * @throws SMException
538     */
539    EncryptedPIN generatePIN(String accountNumber, int pinLen)
540             throws SMException;
541
542
543
544    /**
545     * Generate random pin under LMK with exclude list
546     *
547     * @param accountNumber The 12 right-most digits of the account number excluding the check digit
548     * @param pinLen length of the pin, usually in range 4-12.
549     *               Value 0 means that default length is assumed by HSM (usually 4)
550     * @param excludes list of pins which won't be generated.
551     *               Each pin has to be <code>pinLen</code> length
552     * @return generated PIN under LMK
553     * @throws SMException
554     */
555    EncryptedPIN generatePIN(String accountNumber, int pinLen, List<String> excludes)
556            throws SMException;
557
558    /**
559     * Print PIN or PIN and solicitation data to the HSM configured printer.
560     * <p>If {@code kd1} includes an encrypted PIN block then is first imported,
561     * Also template is updated if needed in HSM storage. Then the PIN and
562     * solicitation data are included into the template and result are
563     * printed to the HSM attached printer.
564     *
565     * @param accountNo The 12 right-most digits of the account number excluding the check digit.
566     * @param pinUnderKd1 pin block under Key Data 1
567     * @param kd1 Data Key 1 ZPK, TPK may be null if {@code pinUnderKd1} contains PIN under LMK
568     * @param template template text (PCL, PostScript or other) for PIN Mailer printer.
569     *                 Its format depends on used HSM. This template should
570     *                 includes placeholders tags (e.g. in format ${tag})
571     *                 indicationg place where coresponding value or PIN should
572     *                 be inserted. Tags values are passed in {@code fields}
573     *                 map argument except PIN which is passed in argument {@code pinUnderKd1}.
574     * @param fields map of tags values representing solicitation data to include
575     *               in template. null if no solicitation data are passed
576     * @throws SMException
577     */
578    void printPIN(String accountNo, EncryptedPIN pinUnderKd1, T kd1
579      , String template, Map<String, String> fields) throws SMException;
580
581
582    /**
583     * Calculate PVV (VISA PIN Verification Value of PIN under LMK)
584     * with exclude list
585     *
586     * <p>NOTE: {@code pvkA} and {@code pvkB} should be single length keys
587     * but at least one of them may be double length key
588     *
589     * @param pinUnderLmk PIN under LMK
590     * @param pvkA first key PVK in PVK pair
591     * @param pvkB second key PVK in PVK pair
592     * @param pvkIdx index of the PVK, in range 0-6, if not present 0 is assumed
593     * @return PVV (VISA PIN Verification Value)
594     * @throws SMException if PIN is on exclude list {@link WeakPINException} is thrown
595     */
596    String calculatePVV(EncryptedPIN pinUnderLmk, T pvkA, T pvkB, int pvkIdx)
597            throws SMException;
598
599
600    /**
601     * Calculate PVV (VISA PIN Verification Value of PIN under LMK)
602     *
603     * <p>NOTE: {@code pvkA} and {@code pvkB} should be single length keys
604     * but at least one of them may be double length key
605     *
606     * @param pinUnderLmk PIN under LMK
607     * @param pvkA first key PVK in PVK pair
608     * @param pvkB second key PVK in PVK pair
609     * @param pvkIdx index of the PVK, in range 0-6, if not present 0 is assumed
610     * @param excludes list of pins which won't be generated.
611     *               Each pin has to be <code>pinLen</code> length
612     * @return PVV (VISA PIN Verification Value)
613     * @throws SMException
614     */
615    String calculatePVV(EncryptedPIN pinUnderLmk, T pvkA, T pvkB, int pvkIdx,
616                        List<String> excludes) throws SMException;
617
618
619    /**
620     * Calculate PVV (VISA PIN Verification Value of customer selected PIN)
621     *
622     * <p>NOTE: {@code pvkA} and {@code pvkB} should be single length keys
623     * but at least one of them may be double length key
624     *
625     * @param pinUnderKd1 the encrypted PIN
626     * @param kd1 Data Key under which the pin is encrypted
627     * @param pvkA first key PVK in PVK pair
628     * @param pvkB second key PVK in PVK pair
629     * @param pvkIdx index of the PVK, in range 0-6, if not present 0 is assumed
630     * @return PVV (VISA PIN Verification Value)
631     * @throws SMException
632     */
633    String calculatePVV(EncryptedPIN pinUnderKd1, T kd1, T pvkA, T pvkB, int pvkIdx)
634            throws SMException;
635
636
637    /**
638     * Calculate PVV (VISA PIN Verification Value of customer selected PIN)
639     *
640     * <p>NOTE: {@code pvkA} and {@code pvkB} should be single length keys
641     * but at least one of them may be double length key
642     *
643     * @param pinUnderKd1 the encrypted PIN
644     * @param kd1 Data Key under which the pin is encrypted
645     * @param pvkA first key PVK in PVK pair
646     * @param pvkB second key PVK in PVK pair
647     * @param pvkIdx index of the PVK, in range 0-6, if not present 0 is assumed
648     * @param excludes list of pins which won't be generated.
649     *               Each pin has to be <code>pinLen</code> length
650     * @return PVV (VISA PIN Verification Value)
651     * @throws WeakPINException if passed PIN is on {@code excludes} list
652     * @throws SMException
653     */
654    String calculatePVV(EncryptedPIN pinUnderKd1, T kd1, T pvkA, T pvkB, int pvkIdx,
655                        List<String> excludes) throws SMException;
656
657
658    /**
659     * Verify PVV (VISA PIN Verification Value of an LMK encrypted PIN)
660     *
661     * <p>NOTE: {@code pvkA} and {@code pvkB} should be single
662     * length keys but at least one of them may be double length key
663     *
664     * @param pinUnderKd1 pin block under {@code kd1}
665     * @param kd1 Data Key (also called session key) under which the pin is encrypted (ZPK or TPK)
666     * @param pvkA first PVK in PVK pair
667     * @param pvkB second PVK in PVK pair
668     * @param pvki index of the PVK, in range 0-6, if not present 0 is assumed
669     * @param pvv (VISA PIN Verification Value)
670     * @return true if pin is valid false if not
671     * @throws SMException
672     */
673    boolean verifyPVV(EncryptedPIN pinUnderKd1, T kd1, T pvkA,
674                      T pvkB, int pvki, String pvv) throws SMException;
675
676
677    /**
678     * Calculate an PIN Offset using the IBM 3624 method
679     *
680     * <p>Using that method is not recomendated. PVV method is prefrred,
681     * but it may be need in some legacy systms
682     * @param pinUnderLmk PIN under LMK
683     * @param pvk        accepts single, double, triple size key length.
684     *                   Single key length is recomendated
685     * @param decTab     decimalisation table. Accepts plain text and encrypted
686     *                   decimalisation table depending to HSM configuration
687     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
688     *                   characters and the character N, which indicates to the HSM where
689     *                   to insert the last 5 digits of the account number. Usualy it consists
690     *                   the first digits of the card number
691     * @param minPinLen  pin minimal length
692     * @return IBM PIN Offset
693     * @throws SMException
694     */
695    String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, T pvk,
696                                 String decTab, String pinValData,
697                                 int minPinLen) throws SMException;
698
699
700
701    /**
702     * Calculate an PIN Offset using the IBM 3624 method
703     *
704     * <p>Using that method is not recomendated. PVV method is prefrred,
705     * but it may be need in some legacy systms
706     * @param pinUnderLmk PIN under LMK
707     * @param pvk        accepts single, double, triple size key length.
708     *                   Single key length is recomendated
709     * @param decTab     decimalisation table. Accepts plain text and encrypted
710     *                   decimalisation table depending to HSM configuration
711     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
712     *                   characters and the character N, which indicates to the HSM where
713     *                   to insert the last 5 digits of the account number. Usualy it consists
714     *                   the first digits of the card number
715     * @param minPinLen  pin minimal length
716     * @param excludes list of pins which won't be generated.
717     *               Each pin has to be <code>pinLen</code> length
718     * @return IBM PIN Offset
719     * @throws WeakPINException if passed PIN is on {@code excludes} list
720     * @throws SMException
721     */
722    String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, T pvk,
723                                 String decTab, String pinValData, int minPinLen,
724                                 List<String> excludes) throws SMException;
725
726
727
728    /**
729     * Calculate an PIN Offset using the IBM 3624 method of customer selected PIN
730     *
731     * <p>Using that method is not recomendated. PVV method is prefrred,
732     * but it may be need in some legacy systms
733     * @param pinUnderKd1 the encrypted PIN
734     * @param kd1 Data Key under which the pin is encrypted
735     * @param pvk        accepts single, double, triple size key length.
736     *                   Single key length is recomendated
737     * @param decTab     decimalisation table. Accepts plain text and encrypted
738     *                   decimalisation table depending to HSM configuration
739     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
740     *                   characters and the character N, which indicates to the HSM where
741     *                   to insert the last 5 digits of the account number. Usualy it consists
742     *                   the first digits of the card number
743     * @param minPinLen  pin minimal length
744     * @return IBM PIN Offset
745     * @throws SMException
746     */
747    String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, T kd1,
748                                 T pvk, String decTab, String pinValData,
749                                 int minPinLen) throws SMException;
750
751
752
753    /**
754     * Calculate an PIN Offset using the IBM 3624 method of customer selected PIN
755     *
756     * <p>Using that method is not recomendated. PVV method is prefrred,
757     * but it may be need in some legacy systms
758     * @param pinUnderKd1 the encrypted PIN
759     * @param kd1 Data Key under which the pin is encrypted
760     * @param pvk        accepts single, double, triple size key length.
761     *                   Single key length is recomendated
762     * @param decTab     decimalisation table. Accepts plain text and encrypted
763     *                   decimalisation table depending to HSM configuration
764     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
765     *                   characters and the character N, which indicates to the HSM where
766     *                   to insert the last 5 digits of the account number. Usualy it consists
767     *                   the first digits of the card number
768     * @param minPinLen  pin minimal length
769     * @param excludes list of pins which won't be generated.
770     *               Each pin has to be <code>pinLen</code> length
771     * @return IBM PIN Offset
772     * @throws WeakPINException if passed PIN is on {@code excludes} list
773     * @throws SMException
774     */
775    String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, T kd1,
776                                 T pvk, String decTab, String pinValData,
777                                 int minPinLen, List<String> excludes) throws SMException;
778
779
780
781    /**
782     * Verify an PIN Offset using the IBM 3624 method
783     *
784     * @param pinUnderKd1 pin block under {@code kd1}
785     * @param kd1        Data Key (also called session key) under which the pin is encrypted (ZPK or TPK)
786     * @param pvk        accepts single, double, triple size key length.
787     *                   Single key length is recomendated
788     * @param offset     IBM PIN Offset
789     * @param decTab     decimalisation table. Accepts plain text and encrypted
790     *                   decimalisation table depending to HSM configuration
791     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
792     *                   characters and the character N, which indicates to the HSM where
793     *                   to insert the last 5 digits of the account number. Usualy it consists
794     *                   the first digits of the card number
795     * @param minPinLen  min pin length
796     * @return true if pin offset is valid false if not
797     * @throws SMException
798     */
799    boolean verifyIBMPINOffset(EncryptedPIN pinUnderKd1, T kd1, T pvk,
800                               String offset, String decTab, String pinValData,
801                               int minPinLen) throws SMException;
802
803
804
805    /**
806     * Derive a PIN Using the IBM 3624 method
807     *
808     * <p>That method derive pin from pin offset (not exacly that same but working).
809     * Therefore that metod is not recomendated. It is similar to obtain pin
810     * from encrypted pinblock, but require (encrypted) decimalisation table
811     * handling is more complicated and returned pin may differ from pin what user has selected 
812     * It may be uable e.g. in migration from pin offset method to PVV method
813     * @param accountNo  the 12 right-most digits of the account number excluding the check digit
814     * @param pvk        accepts single, double, triple size key length.
815     *                   Single key length is recomendated
816     * @param decTab     decimalisation table. Accepts plain text and encrypted
817     *                   decimalisation table depending to HSM configuration
818     * @param pinValData pin validation data. User-defined data consisting of hexadecimal
819     *                   characters and the character N, which indicates to the HSM where
820     *                   to insert the last 5 digits of the account number. Usualy it consists
821     *                   the first digits of the card number
822     * @param minPinLen  min pin length
823     * @param offset     IBM PIN Offset
824     * @return           PIN under LMK
825     * @throws SMException
826     */
827    EncryptedPIN deriveIBMPIN(String accountNo, T pvk
828      , String decTab, String pinValData, int minPinLen
829      , String offset) throws SMException;
830
831
832
833    /**
834     * Calaculate a Card Verification Code/Value.
835     *
836     * <p>NOTE: {@code cvkA} and {@code cvkB} should be single
837     * length keys but at least one of them may be double length key
838     *
839     * @param accountNo The account number including BIN and the check digit
840     * @param cvkA        the first CVK in CVK pair
841     * @param cvkB        the second CVK in CVK pair
842     * @param expDate     the card expiration date
843     * @param serviceCode the card service code
844     *        Service code should be:
845     *        <ul>
846     *          <li>the value which will be placed onto card's magnetic stripe for encoding CVV1/CVC1</li>
847     *          <li>"000" for printing CVV2/CVC2 on card's signature stripe</li>
848     *          <li>"999" for inclusion iCVV/Chip CVC on EMV chip card</li>
849     *        </ul>
850     * @return Card Verification Code/Value
851     * @throws SMException
852     * @deprecated Issuers do not always follow the recommended 'yyMM' format.
853     * Using the {@code java.util.Date} prevents from format manipulating to
854     * solve problem. Use {@link #calculateCVD} with string version of {@code expDate}
855     */
856    @Deprecated
857    String calculateCVV(String accountNo, T cvkA, T cvkB,
858                        Date expDate, String serviceCode) throws SMException;
859
860
861
862    /**
863     * Calaculate a Card Verification Digit (Code/Value).
864     *
865     * <p>NOTE: {@code cvkA} and {@code cvkB} should be single
866     * length keys but at least one of them may be double length key
867     *
868     * @param accountNo The account number including BIN and the check digit
869     * @param cvkA        the first CVK in CVK pair
870     * @param cvkB        the second CVK in CVK pair
871     * @param expDate     the card expiration date
872     * @param serviceCode the card service code
873     *        Service code should be:
874     *        <ul>
875     *          <li>the value which will be placed onto card's magnetic stripe for encoding CVV1/CVC1</li>
876     *          <li>"000" for printing CVV2/CVC2 on card's signature stripe</li>
877     *          <li>"999" for inclusion iCVV/Chip CVC on EMV chip card</li>
878     *        </ul>
879     * @return Card Verification Digit (Code/Value)
880     * @throws SMException
881     */
882    String calculateCVD(String accountNo, T cvkA, T cvkB,
883                        String expDate, String serviceCode) throws SMException;
884
885
886
887    /**
888     * Calaculate a 3-D Secure CAVV/AAV.
889     *
890     * <ul>
891     * <li>Visa uses CAVV (Cardholder Authentication Verification Value)</li>
892     * <li>MasterCard uses AAV (Accountholder Authentication Value)</li>
893     * </ul>
894     * <p>NOTE: Algorithm used to calculation CAVV/AAV is same as for CVV/CVC
895     *          calculation. Only has been changed meaning of parameters
896     *          {@code expDate} and {@code serviceCode}.
897     *
898     * @param accountNo   the account number including BIN and the check digit.
899     * @param cvk         the key used to CVV/CVC generation
900     * @param upn         the unpredictable number. Calculated value based
901     *                    on Transaction Identifier (xid) from PAReq.
902     *                    A 4 decimal digits value must be supplied.
903     * @param authrc      the Authentication Results Code. A value based on
904     *                    the Transaction Status (status) that will be used in
905     *                    PARes. A 1 decimal digit value must be supplied.
906     * @param sfarc       the Second Factor Authentication Results Code.
907     *                    A value based on the result of second factor authentication.
908     *                    A 2 decimal digits value must be suppiled.
909     * @return Cardholder Authentication Verification Value/Accountholder
910     *         Authentication Value
911     * @throws SMException
912     */
913    String calculateCAVV(String accountNo, T cvk, String upn,
914                         String authrc, String sfarc) throws SMException;
915
916    /**
917     * Verify a Card Verification Code/Value.
918     *
919     * <p>NOTE: {@code cvkA} and {@code cvkB} should be single
920     * length keys but at least one of them may be double length key
921     *
922     * @param accountNo The account number including BIN and the check digit
923     * @param cvkA the first CVK in CVK pair
924     * @param cvkB the second CVK in CVK pair
925     * @param cvv Card Verification Code/Value
926     * @param expDate the card expiration date
927     * @param serviceCode the card service code
928     *        Service code should be:
929     *        <ul>
930     *         <li>taken from card's magnetic stripe for verifing CVV1/CVC1</li>
931     *         <li>"000" for verifing CVV2/CVC2 printed on card's signature stripe</li>
932     *         <li>"999" for verifing iCVV/Chip CVC included on EMV chip card</li>
933     *        </ul>
934     * @return true if CVV/CVC is valid or false if not
935     * @throws SMException
936     * @deprecated Issuers do not always follow the recommended 'yyMM' format.
937     * Using the {@code java.util.Date} prevents from format manipulating to
938     * solve problem. Use {@link #verifyCVD} with string version of {@code expDate}
939     */
940    @Deprecated
941    boolean verifyCVV(String accountNo, T cvkA, T cvkB,
942                      String cvv, Date expDate, String serviceCode) throws SMException;
943
944
945    /**
946     * Verify a Card Verification Digit (Code/Value).
947     *
948     * <p>NOTE: {@code cvkA} and {@code cvkB} should be single
949     * length keys but at least one of them may be double length key
950     *
951     * @param accountNo The account number including BIN and the check digit
952     * @param cvkA the first CVK in CVK pair
953     * @param cvkB the second CVK in CVK pair
954     * @param cvv Card Verification Code/Value
955     * @param expDate the card expiration date
956     * @param serviceCode the card service code
957     *        Service code should be:
958     *        <ul>
959     *         <li>taken from card's magnetic stripe for verifing CVV1/CVC1</li>
960     *         <li>"000" for verifing CVV2/CVC2 printed on card's signature stripe</li>
961     *         <li>"999" for verifing iCVV/Chip CVC included on EMV chip card</li>
962     *        </ul>
963     * @return {@code true} if CVV/CVC is valid or {@code false} otherwise
964     * @throws SMException
965     */
966    boolean verifyCVD(String accountNo, T cvkA, T cvkB,
967                      String cvv, String expDate, String serviceCode) throws SMException;
968
969
970    /**
971     * Verify a 3-D Secure CAVV/AAV.
972     *
973     * <ul>
974     * <li>Visa uses CAVV (Cardholder Authentication Verification Value)</li>
975     * <li>MasterCard uses AAV (Accountholder Authentication Value)</li>
976     * </ul>
977     * <p>NOTE: Algorithm used to verification CAVV/AAV is same as for CVV/CVC
978     *          verification. Only has been changed meaning of parameters
979     *          {@code expDate} and {@code serviceCode}.
980     *
981     * @param accountNo   the account number including BIN and the check digit.
982     * @param cvk         the key used to CVV/CVC generation
983     * @param cavv        the Cardholder Authentication Verification Value
984     *                    or Accountholder Authentication Value.
985     * @param upn         the unpredictable number. Calculated value based
986     *                    on Transaction Identifier (xid) from PAReq.
987     *                    A 4 decimal digits value must be supplied.
988     * @param authrc      the Authentication Results Code. A value based on
989     *                    the Transaction Status (status) that will be used in
990     *                    PARes. A 1 decimal digit value must be supplied.
991     * @param sfarc       the Second Factor Authentication Results Code.
992     *                    A value based on the result of second factor authentication.
993     *                    A 2 decimal digits value must be suppiled.
994     * @return true if CAVV/AAV is valid or false if not
995     * @throws SMException
996     */
997    boolean verifyCAVV(String accountNo, T cvk, String cavv,
998                       String upn, String authrc, String sfarc) throws SMException;
999
1000
1001    /**
1002     * Verify a Dynamic Card Verification Value (dCVV).
1003     *
1004     * <p>The EMV "Track 2 Equivalent Data", provided in the authorisation
1005     * message and originating from the contactless smart card, is the source
1006     * for the following data elements used in this function:
1007     * <li> {@code accountNo}
1008     * <li> {@code expDate}
1009     * <li> {@code serviceCode}
1010     * <li> {@code atc}
1011     * <li> {@code dCVV}
1012     *
1013     * @param accountNo The account number including BIN and the check digit
1014     * @param imkac the issuer master key for generating and verifying Application Cryptograms
1015     * @param dcvv dynamic Card Verification Value
1016     * @param expDate the card expiration date
1017     * @param serviceCode the card service code
1018     * @param atc application transactin counter. This is used for ICC Master
1019     *        Key derivation. A 2 byte value must be supplied.
1020     * @param mkdm ICC Master Key Derivation Method. If {@code null} specified
1021     *        is assumed.
1022     * @return {@code true} if {@code dcvv} is valid, or {@code false} if not
1023     * @throws SMException
1024     * @deprecated Issuers do not always follow the recommended 'yyMM' format.
1025     * Using the {@code java.util.Date} prevents from format manipulating to
1026     * solve problem. Use {@link #verifydCVV} with string version of {@code expDate}
1027     */
1028    @Deprecated
1029    boolean verifydCVV(String accountNo, T imkac, String dcvv,
1030                       Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
1031                     throws SMException;
1032
1033    /**
1034     * Verify a Dynamic Card Verification Value (dCVV).
1035     * <p>
1036     * The EMV "Track 2 Equivalent Data", provided in the authorisation
1037     * message and originating from the contactless smart card, is the source
1038     * for the following data elements used in this function:
1039     * <ul>
1040     *   <li> {@code accountNo}
1041     *   <li> {@code expDate}
1042     *   <li> {@code serviceCode}
1043     *   <li> {@code atc}
1044     *   <li> {@code dCVV}
1045     * </ul>
1046     *
1047     * @param accountNo The account number including BIN and the check digit
1048     * @param imkac the issuer master key for generating and verifying Application Cryptograms
1049     * @param dcvv dynamic Card Verification Value
1050     * @param expDate the card expiration date
1051     * @param serviceCode the card service code
1052     * @param atc application transactin counter. This is used for ICC Master
1053     *        Key derivation. A 2 byte value must be supplied.
1054     * @param mkdm ICC Master Key Derivation Method. If {@code null} specified
1055     *        is assumed.
1056     * @return {@code true} if {@code dcvv} is valid, or {@code false} if not
1057     * @throws SMException
1058     */
1059    boolean verifydCVV(String accountNo, T imkac, String dcvv,
1060                       String expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
1061                     throws SMException;
1062
1063
1064    /**
1065     * Verify a Dynamic Card Verification Code 3 (CVC3)
1066     * <p>
1067     * The EMV "Track 2 Equivalent Data", provided in the authorisation
1068     * message and originating from the contactless smart card, is the source
1069     * for the following data elements used in this function:
1070     * <ul>
1071     *   <li> {@code accountNo}
1072     *   <li> {@code expDate}
1073     *   <li> {@code serviceCode}
1074     *   <li> {@code atc}
1075     *   <li> {@code unpredictable number}
1076     *   <li> {@code cvc3}
1077     * </ul>
1078     *
1079     * @param imkcvc3 the issuer master key for generating and verifying CVC3
1080     * @param accountNo The account number including BIN and the check digit
1081     * @param acctSeqNo account sequence number, 2 decimal digits
1082     * @param atc application transactin counter. This is used for CVC3
1083     *        calculation. A 2 byte value must be supplied.
1084     * @param upn  unpredictable number. This is used for CVC3 calculation
1085     *        A 4 byte value must be supplied.
1086     * @param data Static Track Data or when this data length is less or equal 2 IVCVC3
1087     *        <ul>
1088     *        <li>Static Track 1 or 2 Data. From the the issuer is dependent on
1089     *            how to obtain it from the EMV "Track 2 Equivalent Data",
1090     *            provided in the authorisation message and originating from
1091     *            the contactless smart card. Usually variable part of
1092     *            Discreditionary Data are replased by some static value.
1093     *        <li>precomputed Initial Vector for <tt>CVC3</tt> calculation
1094     *            <tt>(IVCVC3)</tt> which is a <tt>MAC</tt> calculated over
1095     *            the static part of Track1 or Track2 data using the key derived
1096     *            from <tt>MK-CVC3</tt>.
1097     *        </ul>
1098     * @param mkdm ICC Master Key Derivation Method. If {@code null} specified
1099     *        is assumed.
1100     * @param cvc3 dynamic Card Verification Code 3. Should contain 5 decimal
1101     *        digits. Max value is {@code "65535"} (decimal representation
1102     *        of 2 byte value). Is possible to pass shorter cvc3 value e.g.
1103     *        {@code "789"} matches with calcuated CVC3 {@code "04789"}
1104     * @return true if cvc3 is valid false if not
1105     * @throws SMException
1106     */
1107    boolean verifyCVC3(T imkcvc3, String accountNo, String acctSeqNo,
1108                       byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3)
1109                     throws SMException;
1110
1111
1112
1113    /**
1114     * Verify Application Cryptogram (ARQC or TC/AAC)
1115     * <ul>
1116     * <li>Authorization Request Cryptogram (ARQC) - Online authorization
1117     * <li>Transaction certificate (TC) - Offline approval
1118     * <li>Application Authentication Cryptogram (AAC) - Offline decline
1119     * </ul>
1120     *
1121     * @param mkdm ICC Master Key Derivation Method. For {@code skdm} equals
1122     *        {@link SKDMethod#VSDC} and {@link SKDMethod#MCHIP} this parameter
1123     *        is ignored and {@link MKDMethod#OPTION_A} is always used.
1124     * @param skdm Session Key Derivation Method
1125     * @param imkac the issuer master key for generating and verifying Application Cryptograms
1126     * @param accountNo account number including BIN and check digit
1127     * @param acctSeqNo account sequence number, 2 decimal digits
1128     * @param arqc ARQC/TC/AAC. A 8 byte value must be supplied.
1129     * @param atc application transactin counter. This is used for Session
1130     *        Key Generation. A 2 byte value must be supplied.
1131     *        For {@code skdm} equals {@link SKDMethod#VSDC} is not used.
1132     * @param upn unpredictable number. This is used for Session Key Generation
1133     *        A 4 byte value must be supplied. For {@code skdm} equals
1134     *        {@link SKDMethod#VSDC} is not used.
1135     * @param txnData transaction data. Transaction data elements and them
1136     *        order is dependend to proper cryptogram version. If the data
1137     *        supplied is a multiple of 8 bytes, no extra padding is added.
1138     *        If it is not a multiple of 8 bytes, additional zero padding is added.
1139     *        <b>If alternative padding methods are required, it have to be
1140     *        applied before</b>.
1141     * @return true if ARQC/TC/AAC is passed or false if not
1142     * @throws SMException
1143     */
1144    boolean verifyARQC(MKDMethod mkdm, SKDMethod skdm, T imkac
1145      , String accountNo, String acctSeqNo, byte[] arqc, byte[] atc
1146      , byte[] upn, byte[] txnData) throws SMException;
1147
1148
1149
1150    /**
1151     * Genarate Authorisation Response Cryptogram (ARPC)
1152     *
1153     * @param mkdm ICC Master Key Derivation Method. For {@code skdm} equals
1154     *        {@link SKDMethod#VSDC} and {@link SKDMethod#MCHIP} this parameter
1155     *        is ignored and {@link MKDMethod#OPTION_A} is always used.
1156     * @param skdm Session Key Derivation Method
1157     * @param imkac the issuer master key for generating and verifying Application Cryptograms
1158     * @param accoutNo account number including BIN and check digit
1159     * @param acctSeqNo account sequence number, 2 decimal digits
1160     * @param arqc ARQC/TC/AAC. A 8 byte value must be supplied.
1161     * @param atc application transactin counter. This is used for Session
1162     *        Key Generation. A 2 byte value must be supplied.
1163     *        For {@code skdm} equals {@link SKDMethod#VSDC} is not used.
1164     * @param upn unpredictable number. This is used for Session Key Generation
1165     *        A 4 byte value must be supplied. For {@code skdm} equals
1166     *        {@link SKDMethod#VSDC} is not used.
1167     * @param arpcMethod ARPC calculating method. For {@code skdm} equals
1168     *        {@link SKDMethod#VSDC}, {@link SKDMethod#MCHIP},
1169     *        {@link SKDMethod#AEPIS_V40} only {@link ARPCMethod#METHOD_1} is valid
1170     * @param arc the Authorisation Response Code. A 2 byte value must be supplied.
1171     *        For {@code arpcMethod} equals {@link ARPCMethod#METHOD_2} it is
1172     *        csu - Card Status Update. Then a 4 byte value must be supplied.
1173     * @param propAuthData Proprietary Authentication Data. Up to 8 bytes.
1174     *        Contains optional issuer data for transmission to the card in
1175     *        the Issuer Authentication Data of an online transaction.
1176     *        It may by used only for {@code arpcMethod} equals
1177     *        {@link ARPCMethod#METHOD_2} in other case is ignored.
1178     * @return calculated 8 bytes ARPC or if {@code arpcMethod} equals
1179     *        {@link ARPCMethod#METHOD_2} 4 bytes ARPC
1180     * @throws SMException
1181     */
1182    byte[] generateARPC(MKDMethod mkdm, SKDMethod skdm, T imkac
1183      , String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn
1184      , ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
1185            throws SMException;
1186
1187
1188
1189    /**
1190     * Verify Application Cryptogram (ARQC or TC/AAC) and Genarate
1191     * Authorisation Response Cryptogram (ARPC)
1192     * <ul>
1193     * <li>Authorization Request Cryptogram (ARQC) - Online authorization
1194     * <li>Transaction certificate (TC) - Offline approval
1195     * <li>Application Authentication Cryptogram (AAC) - Offline decline
1196     * </ul>
1197     * @param mkdm ICC Master Key Derivation Method. For {@code skdm} equals
1198     *        {@link SKDMethod#VSDC} and {@link SKDMethod#MCHIP} this parameter
1199     *        is ignored and {@link MKDMethod#OPTION_A} is always used.
1200     * @param skdm Session Key Derivation Method
1201     * @param imkac the issuer master key for generating and verifying Application Cryptograms
1202     * @param accountNo account number including BIN and check digit
1203     * @param acctSeqNo account sequence number, 2 decimal digits
1204     * @param arqc ARQC/TC/AAC. A 8 byte value must be supplied.
1205     * @param atc application transactin counter. This is used for Session
1206     *        Key Generation. A 2 byte value must be supplied.
1207     *        For {@code skdm} equals {@link SKDMethod#VSDC} is not used.
1208     * @param upn unpredictable number. This is used for Session Key Generation
1209     *        A 4 byte value must be supplied. For {@code skdm} equals
1210     *        {@link SKDMethod#VSDC} is not used.
1211     * @param txnData transaction data. Transaction data elements and them
1212     *        order is dependend to proper cryptogram version. If the data
1213     *        supplied is a multiple of 8 bytes, no extra padding is added.
1214     *        If it is not a multiple of 8 bytes, additional zero padding is added.
1215     *        <b>If alternative padding methods are required, it have to be
1216     *        applied before</b>.
1217     * @param arpcMethod ARPC calculating method. For {@code skdm} equals
1218     *        {@link SKDMethod#VSDC}, {@link SKDMethod#MCHIP},
1219     *        {@link SKDMethod#AEPIS_V40} only {@link ARPCMethod#METHOD_1} is valid
1220     * @param arc the Authorisation Response Code. A 2 byte value must be supplied.
1221     *        For {@code arpcMethod} equals {@link ARPCMethod#METHOD_2} it is
1222     *        csu - Card Status Update. Then a 4 byte value must be supplied.
1223     * @param propAuthData Proprietary Authentication Data. Up to 8 bytes.
1224     *        Contains optional issuer data for transmission to the card in
1225     *        the Issuer Authentication Data of an online transaction.
1226     *        It may by used only for {@code arpcMethod} equals
1227     *        {@link ARPCMethod#METHOD_2} in other case is ignored.
1228     * @return if ARQC/TC/AAC verification passed then calculated 8 bytes ARPC
1229     *         or for {@code arpcMethod} equals {@link ARPCMethod#METHOD_2}
1230     *         4 bytes ARPC, null in other case
1231     * @throws SMException
1232     */
1233    byte[] verifyARQCGenerateARPC(MKDMethod mkdm, SKDMethod skdm, T imkac
1234      , String accountNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn
1235      , byte[] txnData, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
1236            throws SMException;
1237
1238
1239    /**
1240     * Generate Secure Message MAC over suppiled message data
1241     * <p>
1242     * This method is used by issuer to generate MAC over message data send
1243     * from the issuer back to the card
1244     *
1245     * @param mkdm ICC Master Key Derivation Method. For {@code skdm} equals
1246     *        {@link SKDMethod#VSDC} and {@link SKDMethod#MCHIP} this parameter
1247     *        is ignored and {@link MKDMethod#OPTION_A} is always used.
1248     * @param skdm Session Key Derivation Method
1249     * @param imksmi the issuer master key for Secure Messaging Integrity
1250     * @param accountNo account number including BIN and check digit
1251     * @param acctSeqNo account sequence number, 2 decimal digits
1252     * @param atc application transactin counter. This is used for Session
1253     *        Key Generation. A 2 byte value must be supplied.
1254     *        For {@code skdm} equals {@link SKDMethod#VSDC} is not used.
1255     *        Second usage is as part of data which will be macked
1256     * @param arqc ARQC/TC/AAC. A 8 byte value must be supplied.
1257     *        For {@code skdm} equals {@link SKDMethod#MCHIP} RAND should
1258     *        be suppiled. RAND is ARQC incremeted by 1 (with overflow) after
1259     *        each script command for that same ATC value
1260     * @param data for which MAC will be generated. Should contain
1261     *        APDU command e.g. PIN Unblock, Application block/unblock
1262     *        with some additional application dependent data
1263     * @return generated 8 bytes MAC
1264     * @throws SMException
1265     */
1266    byte[] generateSM_MAC(MKDMethod mkdm, SKDMethod skdm
1267      , T imksmi, String accountNo, String acctSeqNo
1268      , byte[] atc, byte[] arqc, byte[] data) throws SMException;
1269
1270
1271
1272    /**
1273     * Translate PIN and generate MAC over suppiled message data
1274     * <p>
1275     * This method is used by issuer to:
1276     * <ul>
1277     * <li>translate standard ATM PIN block format encrypted under zone
1278     * or terminal key {@code kd1} to an application specific PIN block
1279     * format, encrypted under a confidentiality session key, derived from
1280     * {@code imksmc}
1281     * <li>generate MAC over suppiled message {@code data} and translated
1282     * PIN block
1283     * </ul>
1284     * @param mkdm ICC Master Key Derivation Method. For {@code skdm} equals
1285     *        {@link SKDMethod#VSDC} and {@link SKDMethod#MCHIP} this parameter
1286     *        is ignored and {@link MKDMethod#OPTION_A} is always used.
1287     * @param skdm Session Key Derivation Method
1288     * @param padm padding method. If null {@code padm} is derived as follow:
1289     *    <blockquote>
1290     *    <table>
1291     *      <thead>
1292     *        <tr><th>{@code skdm} value</th><th>derived {@code padm} value</th></tr>
1293     *      </thead>
1294     *      <tbody>
1295     *        <tr><td>{@link SKDMethod#VSDC}</td><td>{@link PaddingMethod#VSDC}</td></tr>
1296     *        <tr><td>{@link SKDMethod#MCHIP}</td><td>{@link PaddingMethod#MCHIP}</td></tr>
1297     *        <tr><td>{@link SKDMethod#EMV_CSKD}</td><td>{@link PaddingMethod#CCD}</td></tr>
1298     *      </tbody>
1299     *    </table>
1300     *    Other variations require to explicite pass {@code padm} value
1301     *    </blockquote>
1302     * @param imksmi the issuer master key for Secure Messaging Integrity
1303     * @param accountNo account number including BIN and check digit
1304     * @param acctSeqNo account sequence number, 2 decimal digits
1305     * @param atc application transactin counter. This is used for Session
1306     *        Key Generation. A 2 byte value must be supplied.
1307     *        For {@code skdm} equals {@link SKDMethod#VSDC} is not used.
1308     *        Second usage is as part of data which will be macked
1309     * @param arqc ARQC/TC/AAC. A 8 byte value must be supplied.
1310     *        For {@code skdm} equals {@link SKDMethod#MCHIP} RAND should
1311     *        be suppiled. RAND is ARQC incremeted by 1 (with overflow) after
1312     *        each script command for that same ATC value
1313     * @param data for which MAC will be generated. Should contain APDU
1314     *        command PIN Change with some additional application dependent data
1315     * @param currentPIN encrypted under {@code kd1} current PIN. Used when
1316     *        {@code destinationPINBlockFormat} equals {@link SMAdapter#FORMAT42}
1317     * @param newPIN encrypted under {@code kd1} new PIN.
1318     * @param kd1 Data Key (also called transport key) under which the source pin is encrypted
1319     * @param imksmc the issuer master key for Secure Messaging Confidentiality
1320     * @param imkac the issuer master key for generating and verifying
1321     *        Application Cryptograms. Used when {@code destinationPINBlockFormat} equals
1322     *        {@link SMAdapter#FORMAT41} or {@link SMAdapter#FORMAT42} in other cases is ignored
1323     * @param destinationPINBlockFormat the PIN Block Format of the translated encrypted PIN
1324     *        <dl>
1325     *          <dt><b>Allowed values:</b>
1326     *          <dd>{@link SMAdapter#FORMAT34} Standard EMV PIN Block
1327     *          <dd>{@link SMAdapter#FORMAT35} Europay/Mastercard
1328     *          <dd>{@link SMAdapter#FORMAT41} Visa/Amex format without using Current PIN
1329     *          <dd>{@link SMAdapter#FORMAT42} Visa/Amex format using Current PIN
1330     *        </dl>
1331     * @return Pair of values, encrypted PIN and 8 bytes MAC
1332     * @throws SMException
1333     */
1334    Pair<EncryptedPIN,byte[]> translatePINGenerateSM_MAC(MKDMethod mkdm
1335      , SKDMethod skdm, PaddingMethod padm, T imksmi
1336      , String accountNo, String acctSeqNo, byte[] atc, byte[] arqc
1337      , byte[] data, EncryptedPIN currentPIN, EncryptedPIN newPIN
1338      , T kd1, T imksmc, T imkac
1339      , byte destinationPINBlockFormat) throws SMException;
1340
1341
1342
1343    /**
1344     * Encrypt Data Block.
1345     *
1346     * @param cipherMode block cipher mode.
1347     * @param kd DEK or ZEK key used to encrypt data.
1348     * @param data data to be encrypted. If the data is not a multiple of
1349     *        8 bytes, padding have to be applied before.
1350     * @param iv initial vector. Its length must be equal to the length
1351     *        of cipher block (8 bytes for DES, 3DES ciphers). After operation
1352     *        will contain new iv value. Not used for {@link CipherMode#ECB}.
1353     * @return encrypted data. In {@code iv} array refference new value of
1354     *        initial vector value will be placed.
1355     * @throws SMException
1356     */
1357    byte[] encryptData(CipherMode cipherMode, SecureDESKey kd
1358      , byte[] data, byte[] iv) throws SMException;
1359
1360
1361
1362    /**
1363     * Decrypt Data Block.
1364     *
1365     * @param cipherMode block cipher mode.
1366     * @param kd DEK or ZEK key used to decrypt data.
1367     * @param data data to be decrypted.
1368     * @param iv initial vector. Its length must be equal to the length
1369     *        of cipher block (8 bytes for DES, 3DES ciphers). After operation
1370     *        will contain new iv value. Not used for {@link CipherMode#ECB}.
1371     * @return decrypted data. In {@code iv} array refference new value of
1372     *        initial vector value will be placed.
1373     * @throws SMException
1374     */
1375    byte[] decryptData(CipherMode cipherMode, SecureDESKey kd
1376      , byte[] data, byte[] iv) throws SMException;
1377
1378
1379
1380    /**
1381     * Generates CBC-MAC (Cipher Block Chaining Message Authentication Code)
1382     * for some data.
1383     *
1384     * @param data the data to be MACed
1385     * @param kd the key used for MACing
1386     * @return the MAC
1387     * @throws SMException
1388     */
1389    byte[] generateCBC_MAC(byte[] data, T kd) throws SMException;
1390
1391    /**
1392     * Generates EDE-MAC (Encrypt Decrypt Encrypt Message Message Authentication Code)
1393     * for some data.
1394     *
1395     * @param data the data to be MACed
1396     * @param kd the key used for MACing
1397     * @return the MAC
1398     * @throws SMException
1399     */
1400    byte[] generateEDE_MAC(byte[] data, T kd) throws SMException;
1401
1402    /**
1403     * Translate key from encryption under the LMK held in key change storage
1404     * to encryption under a new LMK.
1405     *
1406     * @param kd the key encrypted under old LMK
1407     * @return key encrypted under the new LMK
1408     * @throws SMException
1409     */
1410    SecureDESKey translateKeyFromOldLMK(SecureDESKey kd) throws SMException;
1411
1412
1413    /**
1414     * Translate key from encryption under the LMK held in key change storage
1415     * to encryption under a new LMK.
1416     *
1417     * @param key the key encrypted under old LMK
1418     * @param keySpec the specification of the key to be translated. It allows
1419     *        passing new key block attributes.
1420     * @return key encrypted under the new LMK
1421     * @throws SMException
1422     */
1423    SecureKey translateKeyFromOldLMK(SecureKey key, SecureKeySpec keySpec) throws SMException;
1424
1425
1426    /**
1427     * Generate a public/private key pair.
1428     *
1429     * @param spec algorithm specific parameters, e.g. algorithm, key size,
1430     *        public key exponent.
1431     * @return key pair generated according to passed parameters
1432     * @throws SMException
1433     */
1434    Pair<PublicKey, SecurePrivateKey> generateKeyPair(AlgorithmParameterSpec spec)
1435      throws SMException;
1436
1437
1438    /**
1439     * Generate a public/private key pair.
1440     *
1441     * @param keySpec the specification of the key to be generated. It allows
1442     *        passing key algorithm type, size and key block attributes.
1443     *        NOTE: For pass an extra key usage of the RSA key, possible is use
1444     *        e.g. {@code keySpec.setVariant()} or {@code keySpec.setReserved()}
1445     * @return key pair generated according to passed parameters
1446     * @throws SMException
1447     */
1448    Pair<PublicKey, SecureKey> generateKeyPair(SecureKeySpec keySpec) throws SMException;
1449
1450
1451    /**
1452     * Calculate signature of Data Block.
1453     *
1454     * @param hash identifier of the hash algorithm used to hash passed data.
1455     * @param privateKey private key used to compute data signature.
1456     * @param data data to be signed.
1457     * @return signature of passed data.
1458     * @throws SMException
1459     */
1460    byte[] calculateSignature(MessageDigest hash, SecureKey privateKey
1461            ,byte[] data) throws SMException;
1462
1463
1464    /**
1465     * Encrypts clear Data Block with specified cipher.
1466     * <p>
1467     * NOTE: This is a more general version of the
1468     * {@link #encryptData(CipherMode, SecureDESKey, byte[], byte[])}
1469     *
1470     * @param encKey the data encryption key e.g:
1471     *        <ul>
1472     *          <li>when RSA public key encapsulated in {@code SecurePrivateKey}
1473     *          <li>when DES/TDES DEK {@code SecureDESKey}
1474     *        </ul>
1475     * @param data clear data block to encrypt
1476     * @param algspec algorithm specification or {@code null} if not required.
1477     *        Used to pass additional algorithm parameters e.g:
1478     *        {@code OAEPParameterSpec} or custom extension of
1479     *        {@code AlgorithmParameterSpec} to pass symetric cipher mode ECB, CBC
1480     * @param iv the inital vector or {@code null} if not used <i>(e.g: RSA
1481     *        cipher or ECB mode)</i>. If used, after operation will contain new
1482     *        {@code iv} value.
1483     * @return encrypted data block
1484     * @throws SMException
1485     */
1486    byte[] encryptData(SecureKey encKey, byte[] data
1487            , AlgorithmParameterSpec algspec, byte[] iv) throws SMException;
1488
1489
1490    /**
1491     * Decrypts encrypted Data Block with specified cipher.
1492     * <p>
1493     * NOTE: This is a more general version of the
1494     * {@link #decryptData(CipherMode, SecureDESKey, byte[], byte[])}
1495     *
1496     * @param decKey the data decryption key e.g:
1497     *        <ul>
1498     *          <li>when RSA private key encapsulated in {@code SecurePrivateKey}
1499     *          <li>when DES/TDES DEK {@code SecureDESKey}
1500     *        </ul>
1501     * @param data encrypted data block to decrypt
1502     * @param algspec algorithm specification or {@code null} if not required.
1503     *        Used to pass additional algorithm parameters e.g:
1504     *        {@code OAEPParameterSpec} or custom extension of
1505     *        {@code AlgorithmParameterSpec} to pass symetric cipher mode ECB, CBC
1506     * @param iv the inital vector or {@code null} if not used <i>(e.g: RSA
1507     *        cipher or ECB mode)</i>. If used, after operation will contain new
1508     *        {@code iv} value.
1509     * @return decrypted data block
1510     * @throws SMException
1511     */
1512    byte[] decryptData(SecureKey decKey, byte[] data
1513            , AlgorithmParameterSpec algspec, byte[] iv) throws SMException;
1514
1515
1516    /**
1517     * Erase the key change storage area of memory
1518     *
1519     * It is recommended that this command is used after keys stored
1520     * by the Host have been translated from old to new LMKs.
1521     *
1522     * @throws SMException
1523     */
1524    void eraseOldLMK() throws SMException;
1525
1526    /**
1527     * Encrypt Data
1528     * @param bdk base derivation key
1529     * @param clearText clear Text
1530     * @return cyphertext
1531     */
1532    byte[] dataEncrypt(T bdk, byte[] clearText) throws SMException;
1533
1534    /**
1535     * Decrypt Data
1536     * @param bdk base derivation key
1537     * @param cypherText clear Text
1538     * @return cleartext
1539     */
1540    byte[] dataDecrypt(T bdk, byte[] cypherText) throws SMException;
1541
1542    /**
1543     * Forms a key from 3 clear components and returns it encrypted under its corresponding LMK
1544     * The corresponding LMK is determined from the keyType
1545     * @param keyLength e.g. LENGTH_DES, LENGTH_DES3_2, LENGTH_DES3_3, ..
1546     * @param keyType possible values are those defined in the SecurityModule inteface. e.g., ZMK, TMK,...
1547     * @param clearComponent up to three HexStrings containing key components
1548     * @return forms an SecureDESKey from two clear components
1549     * @throws SMException
1550     */
1551    SecureDESKey formKEYfromClearComponents(short keyLength, String keyType, String... clearComponent) throws SMException;
1552
1553    /**
1554     * Generates a random clear key component.
1555     * @param keyLength
1556     * @return clear key componenet
1557     * @throws SMException
1558     */
1559    default String generateClearKeyComponent(short keyLength) throws SMException {
1560        throw new SMException("Operation not supported in: " + this.getClass().getName());
1561    }
1562
1563}