0
$\begingroup$

I have following simple function

uint128_t crypto_aes_prf( ECB_Mode< AES >::Encryption& e, int message)
{
    // Encrypt the input using AES
    unsigned char messageBytes[16]= {0};
    unsigned char ciphertext[16] = {0};
    std::memcpy(messageBytes, &message, sizeof(message));

    e.ProcessData(ciphertext,  messageBytes, sizeof(messageBytes));

    uint128_t result = 0;
    for (size_t i = 0; i < sizeof(ciphertext); ++i)
    {
        result = (result << 8) | static_cast<uint8_t>(ciphertext[i]);
    }

    return result;
}

Here the encryptor is initialized as follows:

std::string key = "0123456789abcdef";
CryptoPP::SecByteBlock aesKey(reinterpret_cast<const unsigned char*>(&key), 16);
CryptoPP::SecByteBlock iv(CryptoPP::AES::BLOCKSIZE);

// // Setup AES encryption
ECB_Mode< AES >::Encryption e;
e.SetKey(aesKey, CryptoPP::AES::DEFAULT_KEYLENGTH);

and then I call is using

auto c3= crypto_aes_prf(e, 65654);

Issue is that the performance is very slow, it is around 2 microseconds, more strangely when I call the function again using same encryptor then it takes only 150 nanoseconds.

I am not sure why this change in the performance based on how many times it is run?

$\endgroup$

1 Answer 1

1
$\begingroup$

Issue is that the performance is very slow, it is around 2 microseconds, more strangely when I call the function again using same encryptor then it takes only 150 nanoseconds.

Two obvious possibilities:

  • Caching effect. That is, the CPU needs to pull in quite a lot of memory (possibly code, possibly data). The first time, it's not in the cache (and so you get a lot of cache misses). The second time, it's now in the cache (and so it goes a lot faster)

  • First time setup. That is, the code runs some 'setup' logic the first time it is called (and that setup logic is not cheap). It keeps it around (because it was expensive to do); the second time, it's there, and so it goes a lot faster.

$\endgroup$
3
  • $\begingroup$ okay that makes sense but also how can I validate that AES-NI is being used? $\endgroup$
    – LWE-13
    Commented Jun 30, 2023 at 19:36
  • $\begingroup$ @LWE-13: Dunno: I don't know the innards of crypto++ $\endgroup$
    – poncho
    Commented Jun 30, 2023 at 19:59
  • 1
    $\begingroup$ Check the output assembly to see that the AES-NI instructions are used. $\endgroup$ Commented Jun 30, 2023 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.