123{
125 if (cipher == NULL) {
127 return 0;
128 }
129 uint32_t data_len;
130 memcpy(&data_len, ciphertext, sizeof(uint32_t));
131 assert ((size_t) ciphertext_len >= data_len + sizeof(uint32_t) + 16 + sizeof(uint32_t));
132 ciphertext += sizeof(uint32_t);
133 const unsigned char *iv = (const unsigned char *) ciphertext;
134 ciphertext += 16;
135 ciphertext_len -= 20;
136
137 CHECK(EVP_CipherInit(decrypt->
ctx, cipher, decrypt->
key_hash, iv, 0),
"Unable to initialize cipher");
138 CHECK(EVP_CIPHER_CTX_ctrl(decrypt->
ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL),
"set IV len");
139
140 int out_len = 0;
143 if (aad && aad_len > 0) {
144 if (!EVP_DecryptUpdate(decrypt->
ctx, NULL, &out_len, (
void *) aad, aad_len)) {
146 }
147 }
148 }
149 CHECK(EVP_CipherUpdate(decrypt->
ctx, (
unsigned char *) plaintext, &out_len, (
const unsigned char *) ciphertext, ciphertext_len),
"EVP_CipherUpdate");
150 int total_len = out_len;
152 CHECK(EVP_CIPHER_CTX_ctrl(decrypt->
ctx, EVP_CTRL_GCM_SET_TAG,
GCM_TAG_LEN, (
void *) (ciphertext + ciphertext_len)),
"GCM set tag");
153 }
154 CHECK(EVP_CipherFinal(decrypt->
ctx, (
unsigned char *) plaintext + out_len, &out_len),
"EVP_CipherFinal");
155 total_len += out_len;
156
158 uint32_t expected_crc = 0;
159 assert((size_t) total_len >= data_len + sizeof expected_crc);
160 memcpy(&expected_crc, plaintext + data_len, sizeof expected_crc);
161 uint32_t crc =
crc32buf(aad, aad_len);
163 if (crc != expected_crc) {
165 return 0;
166 }
167 }
168
169 return data_len;
170}
uint32_t crc32buf(const char *buf, size_t len)
uint32_t crc32buf_with_oldcrc(const char *buf, size_t len, uint32_t oldcrc)
#define LOG_LEVEL_WARNING
less severe errors
#define CHECK(action, errmsg)
const EVP_CIPHER *(* get_cipher)(void)
unsigned char key_hash[16]