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