Openssl EVP "EVP_CTRL_GCM_GET_TAG" fails

993 views Asked by At

I am using Openssl EVP in C++. Somehow getting the tag failes. My Code:

int do_crypt(FILE *in, FILE *out){
    unsigned char inbuf[1024], aadbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
    int inlen, lenbuf, unused, outlen;
    EVP_CIPHER_CTX *ctx;

    unsigned char key[] = "0123456789abcdeF";
    unsigned char iv[] = "123456788765";
    unsigned char tag[16];

    ctx = EVP_CIPHER_CTX_new();
    EVP_CIPHER_CTX_init(ctx);
    EVP_CipherInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL, do_encrypt);
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(iv), NULL);

    OPENSSL_assert(EVP_CIPHER_CTX_key_length(ctx) == 16);
    OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) == 12);
    EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1);
    
    FILE * aad_f = fopen("aad.txt", "rb");
    
    for(;;){
        size_t a = fread(aadbuf, 1, 1024, aad_f);
        lenbuf = int(a);
        
        if (lenbuf <= 0) break;
        EVP_CipherUpdate(ctx, NULL, &unused, aadbuf, lenbuf);
     }
    /* Input text */
    for(;;){
        size_t a = fread(inbuf, 1, 1024, in);
        inlen = int(a);
        if (inlen <= 0) break;
        EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, inlen);
        fwrite(outbuf, 1, outlen, out);
        }
    
    EVP_CipherFinal_ex(ctx, outbuf, &outlen);
    EVP_CIPHER_CTX_free(ctx);
    fwrite(outbuf, 1, outlen, out);
    
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)){
         cout << "error get tag" << endl;
         return 0;
   }
        FILE * tag_f = fopen("tag.txt", "wb");
        fwrite(tag, 1, sizeof(tag), tag_f);
        cout << tag << endl;
    }
    return 0;
    
    }

But why? All the other the other EVP funktions do well. What do i miss? Do i have to call an other funktion? Instead of the tag, @\267* is been written to the tag.txt file.

1

There are 1 answers

0
Topaco On BEST ANSWER

There are two bugs in the code:

  • Since sizeof is used to determine the length of the IV, the 0-terminator is counted as well and the wrong length 13 is determined. Instead of sizeof, strlen must be applied, which returns the correct value 12.
  • The context is released before the tag is determined, i.e. EVP_CIPHER_CTX_free is called before EVP_CIPHER_CTX_ctrl. This order must be reversed.

With these changes the correct ciphertext and tag will be created.

Please note that the fixed key/IV pair may only be used for testing. In practice a key/IV pair may only be used once, especially for GCM.