@@ -413,6 +413,71 @@ int ECCX08Class::AESEncrypt(byte IV[], byte ad[], byte pt[], byte ct[], byte tag
413
413
return 1 ;
414
414
}
415
415
416
+ int ECCX08Class::AESDecrypt (byte IV[], byte ad[], byte pt[], byte ct[], byte tag[], const uint64_t adLength, const uint64_t ctLength)
417
+ {
418
+ uint64_t maxLength = 1ull << 36 ;
419
+ if (adLength >= maxLength || ctLength >= maxLength){
420
+ return 0 ;
421
+ }
422
+
423
+ byte H[16 ] = {0x00 };
424
+ if (!AESBlockEncrypt (H)){
425
+ return 0 ;
426
+ }
427
+
428
+ byte J0[16 ] = {0x00 };
429
+ memcpy (J0, IV, 12 );
430
+ J0[15 ] = 0x01 ;
431
+
432
+ int adPad = (-adLength) % 16 ;
433
+ int ctPad = (-ctLength) % 16 ;
434
+
435
+ byte S[16 ];
436
+ uint64_t inputLength = adLength+adPad+ctLength+ctPad+16 ;
437
+ byte input[inputLength];
438
+ memcpy (input, ad, adLength);
439
+ memset (input+adLength, 0 , adPad);
440
+ memcpy (input+adLength+adPad, ct, ctLength);
441
+ memset (input+adLength+adPad+ctLength, 0 , ctPad);
442
+ // Device is little endian
443
+ // GCM specification requires big endian length representation
444
+ // Hence we reverse the byte order of adLength and ctLength
445
+ for (int i=0 ; i<8 ; i++){
446
+ input[adLength+adPad+ctLength+ctPad+i] = (adLength >> (56 -8 *i)) & 0xFF ;
447
+ input[adLength+adPad+ctLength+ctPad+8 +i] = (ctLength >> (56 -8 *i)) & 0xFF ;
448
+ }
449
+
450
+ if (!AESGHASH (H, input, S, inputLength)){
451
+ return 0 ;
452
+ }
453
+
454
+ byte tagComputed[16 ];
455
+ if (!AESGCTR (J0, S, tagComputed, 16 )){
456
+ return 0 ;
457
+ }
458
+
459
+ uint8_t equalBytes=0 ;
460
+ for (int i=0 ; i<16 ; i++){
461
+ equalBytes += (tag[i]==tagComputed[i]);
462
+ }
463
+ if (equalBytes!=16 ){
464
+ // tag mismatch
465
+ return 0 ;
466
+ }
467
+
468
+ byte counterBlock[16 ];
469
+ memcpy (counterBlock, J0, 16 );
470
+ if (!AESIncrementBlock (counterBlock)){
471
+ return 0 ;
472
+ }
473
+
474
+ if (!AESGCTR (counterBlock, ct, pt, ctLength)){
475
+ return 0 ;
476
+ }
477
+
478
+ return 1 ;
479
+ }
480
+
416
481
417
482
/* * \brief GCTR function, see
418
483
* NIST Special Publication 800-38D
0 commit comments