| 141 | } |
| 142 | |
| 143 | int decrypt(const unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, |
| 144 | int aad_len, unsigned char *tag, const unsigned char *key, const unsigned char *iv, |
| 145 | unsigned char *plaintext, EVP_CIPHER_CTX* ctx) |
| 146 | { |
| 147 | |
| 148 | if (!ctx) |
| 149 | return -1; |
| 150 | |
| 151 | int len; |
| 152 | int plaintext_len; |
| 153 | int ret; |
| 154 | |
| 155 | |
| 156 | |
| 157 | try { |
| 158 | |
| 159 | |
| 160 | /* Initialise Key and IV */ |
| 161 | if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors(); |
| 162 | |
| 163 | /* Provide any AAD data. This can be called zero or more times as |
| 164 | * required |
| 165 | */ |
| 166 | if (!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len)) |
| 167 | handleErrors(); |
| 168 | |
| 169 | /* Provide the message to be decrypted, and obtain the plaintext output. |
| 170 | * EVP_DecryptUpdate can be called multiple times if necessary |
| 171 | */ |
| 172 | if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) |
| 173 | handleErrors(); |
| 174 | plaintext_len = len; |
| 175 | |
| 176 | /* Set expected tag value. Works in OpenSSL 1.0.1d and later */ |
| 177 | if (tag) { |
| 178 | if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag)) |
| 179 | handleErrors(); |
| 180 | } |
| 181 | |
| 182 | /* Finalise the decryption. A positive return value indicates success, |
| 183 | * anything else is a failure - the plaintext is not trustworthy. |
| 184 | */ |
| 185 | ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len); |
| 186 | |
| 187 | } |
| 188 | catch (int) { |
| 189 | ret = -1; |
| 190 | } |
| 191 | |
| 192 | |
| 193 | |
| 194 | if (ret > 0) |
| 195 | { |
| 196 | /* Success */ |
| 197 | plaintext_len += len; |
| 198 | return plaintext_len; |
| 199 | } |
| 200 | else |
no test coverage detected