对于 AES-GCM 加密/解密,我试过这个,但它有一个问题。
ctx = EVP_CIPHER_CTX_new();
//Get the cipher.
cipher = EVP_aes_128_gcm ();
#define GCM_IV "000000000000"
#define GCM_ADD "0000"
#define TAG_SIZE 16
#define ENC_SIZE 64
//Encrypt the data first.
//Set the cipher and context only.
retv = EVP_EncryptInit (ctx, cipher, NULL, NULL);
//Set the nonce and tag sizes.
//Set IV length. [Optional for GCM].
retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_IVLEN, strlen((const char *)GCM_IV), NULL);
//Now initialize the context with key and IV.
retv = EVP_EncryptInit (ctx, NULL, (const unsigned char *)keybuf, (const unsigned char *)GCM_IV);
//Add Additional associated data (AAD). [Optional for GCM]
retv = EVP_EncryptUpdate (ctx, NULL, (int *)&enclen, (const unsigned char *)GCM_ADD, strlen(GCM_ADD));
//Now encrypt the data.
retv = EVP_EncryptUpdate (ctx, (unsigned char *)encm, (int *)&enclen, (const unsigned char *)msg, _tcslen (msg) *sizeof(Char));
//Finalize.
retv = EVP_EncryptFinal (ctx, (unsigned char *)encm + enclen, (int *)&enclen2);
enclen += enclen2;
//Append authentication tag at the end.
retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, TAG_SIZE, (unsigned char *)encm + enclen);
//DECRYPTION PART
//Now Decryption of the data.
//Then decrypt the data.
//Set just cipher.
retv = EVP_DecryptInit(ctx, cipher, NULL, NULL);
//Set Nonce size.
retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_IVLEN, strlen((const char *)GCM_IV), NULL);
//Set Tag from the data.
retv = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_SET_TAG, TAG_SIZE, (unsigned char *)encm + enclen);
//Set key and IV (nonce).
retv = EVP_DecryptInit (ctx, NULL, (const unsigned char*)keybuf, (const unsigned char *)GCM_IV);
//Add Additional associated data (AAD).
retv = EVP_DecryptUpdate (ctx, NULL, (int *)&declen, (const unsigned char *)GCM_ADD,
strlen((const char *)GCM_ADD));
//Decrypt the data.
retv = EVP_DecryptUpdate (ctx, decm, (int *)&declen, (const unsigned char *)encm, enclen);
//Finalize.
retv = EVP_DecryptFinal (ctx, (unsigned char*)decm + declen, (int *)&declen2);
这段代码工作正常(有一些修改)。它正在加密和解密消息。问题是在解密之前修改密文时,它仍然解密文本(但是,错误)。根据我对认证加密的理解,在这种情况下,它不应该解密修改后的密文。
我哪里错了?我可以使用 OpenSSL 的 EVP 接口获得任何合适的 AES-GCM 示例吗?