Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */
| 642 | |
| 643 | /* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */ |
| 644 | void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length) |
| 645 | { |
| 646 | uint8_t buffer[AES_BLOCKLEN]; |
| 647 | |
| 648 | size_t i; |
| 649 | int bi; |
| 650 | for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) |
| 651 | { |
| 652 | if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */ |
| 653 | { |
| 654 | |
| 655 | memcpy(buffer, ctx->Iv, AES_BLOCKLEN); |
| 656 | Cipher((state_t*)buffer,ctx->RoundKey); |
| 657 | |
| 658 | /* Increment Iv and handle overflow */ |
| 659 | for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) |
| 660 | { |
| 661 | /* inc will overflow */ |
| 662 | if (ctx->Iv[bi] == 255) |
| 663 | { |
| 664 | ctx->Iv[bi] = 0; |
| 665 | continue; |
| 666 | } |
| 667 | ctx->Iv[bi] += 1; |
| 668 | break; |
| 669 | } |
| 670 | bi = 0; |
| 671 | } |
| 672 | |
| 673 | buf[i] = (buf[i] ^ buffer[bi]); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | #endif // #if defined(CTR) && (CTR == 1) |
| 678 |