1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! ISO 9564 format 4 PIN block encoding, encryption, decryption, and decoding.
//!
//! This module provides functionality for handling PIN blocks according to
//! ISO 9564 format 4.
//!
//! Format 4 is intended for use with AES and binds the encoded PIN field to a
//! Primary Account Number (PAN). The cryptographic operations themselves are
//! not implemented by this crate. Instead, they are delegated to a provider
//! implementing [`paysec_crypto::AesBlockCipher`].
//!
//! This allows callers to select an appropriate cryptographic backend, such as
//! a software implementation for testing or a provider backed by an HSM or
//! another cryptographic service.
//!
//! # Operations
//!
//! The module provides functionality to:
//!
//! - encode a PIN into an ISO 9564 format 4 PIN field,
//! - decode an ISO 9564 format 4 PIN field,
//! - encode a PAN into an ISO 9564 format 4 PAN field,
//! - encipher a format 4 PIN block using an AES-capable provider,
//! - decipher a format 4 PIN block using an AES-capable provider.
//!
//! The format 4 enciphering procedure is:
//!
//! 1. Encode the PIN field.
//! 2. Encode the PAN field.
//! 3. Encrypt the PIN field with AES.
//! 4. XOR the encrypted result with the PAN field.
//! 5. Encrypt the XOR result with AES.
//!
//! Deciphering performs the corresponding operations in reverse.
//!
//! # PIN Handling
//!
//! PIN values supplied for encoding and enciphering are accepted as `&str`
//! and validated before use.
//!
//! Plaintext PIN values produced by decoding or deciphering are returned as
//! [`crate::Pin`]. The `Pin` type:
//!
//! - guarantees that the value contains between 4 and 12 ASCII decimal digits,
//! - redacts its contents from debug output,
//! - zeroizes its owned string when dropped,
//! - requires explicit access through [`crate::Pin::expose_secret`] when the
//! plaintext PIN digits are needed.
//!
//! # Example
//!
//! ```
//! use paysec_crypto_soft_aes::SoftAesProvider;
//! use paysec_pinblock::{
//! decipher_pinblock_iso_4,
//! encipher_pinblock_iso_4,
//! };
//!
//! let provider = SoftAesProvider::new();
//!
//! let key = hex::decode("00112233445566778899AABBCCDDEEFF")
//! .expect("Invalid key hex");
//!
//! let pin = "1234";
//! let pan = "1234567890123456789";
//! let rnd_seed = vec![0xFF; 8];
//!
//! let encrypted_pin_block = encipher_pinblock_iso_4(
//! &provider,
//! key.as_slice(),
//! pin,
//! pan,
//! rnd_seed,
//! )
//! .expect("Failed to encipher PIN block");
//!
//! let encrypted_pin_block_hex =
//! hex::encode_upper(&encrypted_pin_block);
//!
//! assert_eq!(
//! encrypted_pin_block_hex,
//! "28B41FDDD29B743E93124BD8E32D921E"
//! );
//!
//! let decrypted_pin = decipher_pinblock_iso_4(
//! &provider,
//! key.as_slice(),
//! &encrypted_pin_block,
//! pan,
//! )
//! .expect("Failed to decipher PIN block");
//!
//! assert_eq!(
//! decrypted_pin.expose_secret(),
//! pin,
//! );
//! ```
//!
//! # Security
//!
//! This crate defines the ISO 9564 format 4 processing logic but does not
//! prescribe a concrete cryptographic implementation.
//!
//! The security properties of AES operations therefore depend on the selected
//! [`paysec_crypto::AesBlockCipher`] provider. A software provider may operate
//! directly on raw key material in process memory, while an HSM-backed
//! provider may instead operate on opaque key handles.
//!
//! Plaintext PIN values returned by decoding or deciphering are held in
//! [`crate::Pin`]. The wrapper redacts debug output and zeroizes its owned
//! string when dropped.
//!
//! Temporary plaintext PIN-field buffers created internally during enciphering
//! and deciphering are also zeroized when they leave scope.
//!
//! These protections provide defense in depth against accidental disclosure
//! and residual process-memory contents. They do not guarantee that the PIN
//! has never existed elsewhere in memory. For example, callers may retain
//! additional plaintext copies, and operating-system facilities such as swap,
//! crash dumps, or process-memory inspection are outside the scope of this
//! crate.
//!
//! The caller is also responsible for providing the random data used when
//! encoding the PIN field. This module does not generate randomness or assess
//! the entropy quality of the supplied random seed.
//!
//! Production use should employ a cryptographic provider and deployment model
//! appropriate for the applicable payment-security requirements.
use crate;
use crate::;
use AesBlockCipher;
use Zeroizing;
const ISO4_PIN_BLOCK_LENGTH: usize = 16;
const ISO4_RANDOM_SEED_LENGTH: usize = 8;
/// Encode a PIN into an ISO 9564 format 4 PIN field.
///
/// The resulting PIN field is 16 bytes long.
///
/// The first half contains:
///
/// - the format identifier,
/// - the PIN length,
/// - the PIN digits encoded as BCD,
/// - `0xA` filler nibbles.
///
/// The second half contains the first eight bytes of the supplied random seed.
///
/// # Parameters
///
/// * `pin` - ASCII-encoded PIN consisting of 4 to 12 decimal digits.
/// * `rnd_seed` - Random data used for the second half of the PIN field.
/// At least 8 bytes must be supplied.
///
/// # Returns
///
/// A 16-byte ISO 9564 format 4 PIN field.
///
/// # Errors
///
/// Returns [`PinBlockError::InvalidPin`] if `pin` does not contain between
/// 4 and 12 ASCII decimal digits.
///
/// Returns [`PinBlockError::RandomSeedTooShort`] if fewer than eight random
/// bytes are supplied.
///
/// # Security
///
/// This function accepts the PIN as a borrowed string and does not take
/// ownership of or zeroize the caller's input. The caller remains responsible
/// for the lifecycle of the supplied plaintext PIN.
/// Decode a PIN from an ISO 9564 format 4 PIN field.
///
/// The function validates the format identifier, encoded PIN length, PIN
/// digits, and filler nibbles before returning the decoded PIN.
///
/// # Parameters
///
/// * `pin_field` - Encoded ISO 9564 format 4 PIN field. It must be exactly
/// 16 bytes long.
///
/// # Returns
///
/// The decoded plaintext PIN as a [`Pin`].
///
/// The returned `Pin` redacts its contents from debug output and zeroizes its
/// owned string when dropped. Call [`Pin::expose_secret`] when explicit access
/// to the plaintext PIN digits is required.
///
/// # Errors
///
/// Returns a [`PinBlockError`] if:
///
/// - the PIN field is not exactly 16 bytes long,
/// - the control field does not identify ISO format 4,
/// - the encoded PIN length is outside the range 4 to 12,
/// - an encoded PIN digit contains an invalid BCD value,
/// - a filler nibble is not `0xA`.
/// Encode a Primary Account Number into an ISO 9564 format 4 PAN field.
///
/// The resulting PAN field is 16 bytes long and is used during format 4 PIN
/// block enciphering and deciphering.
///
/// # Parameters
///
/// * `pan` - ASCII-encoded PAN consisting of 1 to 19 decimal digits.
///
/// # Returns
///
/// A 16-byte ISO 9564 format 4 PAN field.
///
/// # Errors
///
/// Returns [`PinBlockError::InvalidPan`] if the PAN is empty, longer than
/// 19 digits, or contains a non-ASCII decimal digit.
///
/// Returns [`PinBlockError::Hex`] if hexadecimal decoding of the internally
/// constructed PAN field fails.
/// Encipher an ISO 9564 format 4 PIN block.
///
/// Cryptographic operations are delegated to the supplied
/// [`AesBlockCipher`] provider.
///
/// The provider determines how the key is represented. A software provider may
/// accept raw key bytes, while another implementation may use an opaque key
/// handle.
///
/// # Parameters
///
/// * `provider` - Cryptographic provider used for AES block encryption.
/// * `key` - Provider-specific AES key.
/// * `pin` - ASCII-encoded PIN consisting of 4 to 12 decimal digits.
/// * `pan` - ASCII-encoded PAN consisting of 1 to 19 decimal digits.
/// * `rnd_seed` - Random data used when encoding the PIN field. At least
/// 8 bytes must be supplied.
///
/// # Returns
///
/// The encrypted 16-byte PIN block as a [`Vec<u8>`].
///
/// # Errors
///
/// Returns [`PinBlockCryptoError::PinBlock`] if PIN or PAN validation or
/// encoding fails.
///
/// Returns [`PinBlockCryptoError::Crypto`] if the cryptographic provider
/// reports an AES encryption error.
///
/// # Security
///
/// The plaintext PIN is borrowed from the caller and is not owned or zeroized
/// by this function. The internally encoded plaintext PIN field is zeroized
/// when it leaves scope.
///
/// Provider-managed AES keys retain the security properties of the selected
/// cryptographic provider.
Sized> where
P: ,
/// Decipher an ISO 9564 format 4 PIN block.
///
/// Cryptographic operations are delegated to the supplied
/// [`AesBlockCipher`] provider.
///
/// The provider determines how the key is represented. A software provider may
/// accept raw key bytes, while another implementation may use an opaque key
/// handle.
///
/// # Parameters
///
/// * `provider` - Cryptographic provider used for AES block decryption.
/// * `key` - Provider-specific AES key.
/// * `pin_block` - Encrypted format 4 PIN block. It must be exactly 16 bytes.
/// * `pan` - ASCII-encoded PAN used when the PIN block was created.
///
/// # Returns
///
/// The deciphered plaintext PIN as a [`Pin`].
///
/// The returned `Pin` redacts its plaintext digits from debug output and
/// zeroizes its owned string when dropped. Call [`Pin::expose_secret`] when
/// explicit access to the PIN digits is required.
///
/// # Errors
///
/// Returns [`PinBlockCryptoError::PinBlock`] if:
///
/// - the encrypted PIN block is not exactly 16 bytes long,
/// - PAN processing fails,
/// - the recovered plaintext PIN field is malformed.
///
/// Returns [`PinBlockCryptoError::Crypto`] if the cryptographic provider
/// reports an AES decryption error.
///
/// # Security
///
/// The recovered plaintext PIN field is zeroized when it leaves scope, and
/// the decoded PIN is returned in a [`Pin`] wrapper that zeroizes its owned
/// plaintext representation when dropped.
///
/// Provider-managed AES keys retain the security properties of the selected
/// cryptographic provider.
Sized> where
P: ,