OpenSSL3.1 C example of AES-XTS using EVP interfaces Unable to segment data for calculation

79 Views Asked by At

For AES-XTS encryption, I want to perform segmented input calculations on the data, but it has a problem.

#include <openssl/evp.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <string.h>

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

int sca_aes_xts_encrypt(const uint8_t *key, size_t klen, uint8_t *iv, const uint8_t *text, size_t len, uint8_t *out) {
    EVP_CIPHER_CTX *ctx;

    size_t ciphertext_len;

    if(!(ctx = EVP_CIPHER_CTX_new()))
            handleErrors();

    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_xts(), NULL, NULL, NULL))
            handleErrors();

    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_SET_KEY_LENGTH, klen, NULL))
            handleErrors();

    if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
            handleErrors();

    // if(1 != EVP_EncryptUpdate(ctx, out, &len, text, len))
    //         handleErrors();
    int block_size = 16;

    for(int i = 0; i < len; i += block_size) {
        int cipher_len = (len - i) >= block_size ? block_size : (len - i);
        if(1 != EVP_EncryptUpdate(ctx, out + i, &cipher_len, text + i, cipher_len))
            handleErrors();
    }

    ciphertext_len = len;
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
            handleErrors();
    ciphertext_len += len;

    return ciphertext_len;
}

The calculation result of the entire data is correct, but the result after segmentation using EVP_EncryptUpdate is wrong. Any help appreciated. Thank you.

1

There are 1 best solutions below

0
Igor R On

The XTS implementation in OpenSSL does not support streaming. That is there must only be one EVP_EncryptUpdate(3) call per EVP_EncryptInit_ex(3) call (and similarly with the “Decrypt” functions).