| 92 | } |
| 93 | |
| 94 | int encrypt(const unsigned char *plaintext, int plaintext_len, unsigned char *aad, |
| 95 | int aad_len, const unsigned char *key, const unsigned char *iv, |
| 96 | unsigned char *ciphertext, unsigned char *tag, EVP_CIPHER_CTX* ctx) |
| 97 | { |
| 98 | |
| 99 | if (!ctx) |
| 100 | return -1; |
| 101 | |
| 102 | int len; |
| 103 | |
| 104 | int ciphertext_len; |
| 105 | |
| 106 | try { |
| 107 | |
| 108 | |
| 109 | if (1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors(); |
| 110 | |
| 111 | /* Provide any AAD data. This can be called zero or more times as |
| 112 | * required |
| 113 | */ |
| 114 | if (1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len)) |
| 115 | handleErrors(); |
| 116 | |
| 117 | /* Provide the message to be encrypted, and obtain the encrypted output. |
| 118 | * EVP_EncryptUpdate can be called multiple times if necessary |
| 119 | */ |
| 120 | if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) |
| 121 | handleErrors(); |
| 122 | ciphertext_len = len; |
| 123 | |
| 124 | /* Finalise the encryption. Normally ciphertext bytes may be written at |
| 125 | * this stage, but this does not occur in GCM mode |
| 126 | */ |
| 127 | if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors(); |
| 128 | ciphertext_len += len; |
| 129 | |
| 130 | /* Get the tag */ |
| 131 | if (tag) { |
| 132 | if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) |
| 133 | handleErrors(); |
| 134 | } |
| 135 | |
| 136 | } catch (int) { |
| 137 | ciphertext_len = -1; |
| 138 | } |
| 139 | |
| 140 | return ciphertext_len; |
| 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, |
no test coverage detected