0

我有以下用于解密数据的代码:

-(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;
}

由于某种原因,代码无法正确解密数据。_sesKey 是正确的,并且在调用 toIV 以强制第一组数据使用正确的 iv 之后,IV 被覆盖,并且解密不需要 AAD 数据。我已经在 android 中完成了这个(使用 bouncycastle 库),所以我知道 _sesKey 和 IV 是正确的。我不知道是否有人可以通过告诉我出了什么问题以及为什么来帮助我。

4

1 回答 1

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.

于 2014-12-02T09:51:46.660 回答