0

I've got the following code for decrypting the data:

-(NSString*)_decrypte:(NSString*)encrypted
{
    NSString *decrypted;

    NSData *enc = [[NSData alloc]initWithBase64EncodedString:encrypted options:0];
    int len = (int)[enc length];
    Byte *cipher = (Byte*)malloc(len);
    memcpy((void *)cipher, [enc bytes], len);

    Byte *iv = toIv(_ivCounter++, 16);
    for(uint i = 0; i < 16; i++)
    {
        iv[i] = 0;
    }

    int outLen, plainttext_len, dec_success, tag_len = 128 / 8;
    unsigned char *plaintext = (unsigned char*)malloc(len);
    unsigned char *tag =(unsigned char*)malloc(tag_len);
    int offset = len - (tag_len);
    for(int i = 0; i < tag_len; i++)
    {
        tag[i] = cipher[i + offset];
    }

    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void *)tag);
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL);
    EVP_DecryptInit_ex(ctx, NULL, NULL, _sesKey, iv);
    EVP_DecryptUpdate(ctx, NULL, &len, NULL, 0);
    EVP_DecryptUpdate(ctx, plaintext, &outLen, cipher, len);
    plainttext_len = outLen;
    dec_success = EVP_DecryptFinal_ex(ctx, plaintext + outLen, &outLen);
    EVP_CIPHER_CTX_free(ctx);

    decrypted = [NSString stringWithFormat:@"%s", plaintext];

    return decrypted;
}

For some reason the code doesn't decrypt the data right. The _sesKey is right and the IV is overwritten after the call to toIV to force the right iv for the first set of data and there is no AAD data needed for the decrypting. I've already done this in android(using the bouncycastle library), so I known for a fact that the _sesKey and the IV are correct. I don't know if anybody can help me by telling what goes wrong and why.

Anshuman Jasrotia
  • 3,135
  • 8
  • 48
  • 81
Terry
  • 332
  • 1
  • 15

1 Answers1

0

I found the mistake with some help, the problem is that the variable _sesKey was a pointer and during generating the key and decrypting the data, the memory the pointer was pointing to got whiped. So the _sesKey became invalid. So now a changed _sesKey to a normal byte array and now it works.

Terry
  • 332
  • 1
  • 15