| 53 | } |
| 54 | |
| 55 | shared_ptr<EVP_CIPHER_CTX> get_crypt_context(int ivlen, int mode) |
| 56 | { |
| 57 | EVP_CIPHER_CTX*ctx = NULL; |
| 58 | |
| 59 | try { |
| 60 | /* Create and initialise the context */ |
| 61 | if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); |
| 62 | |
| 63 | const EVP_CIPHER *cipher = NULL; |
| 64 | |
| 65 | switch (mode) { |
| 66 | |
| 67 | case AES_MODE_GCM: |
| 68 | cipher = EVP_aes_256_gcm(); |
| 69 | break; |
| 70 | default: |
| 71 | handleErrors(); |
| 72 | break; |
| 73 | } |
| 74 | |
| 75 | /* Initialise the encryption operation. */ |
| 76 | if (1 != EVP_EncryptInit_ex(ctx, cipher, NULL, NULL, NULL)) |
| 77 | handleErrors(); |
| 78 | |
| 79 | if (mode == AES_MODE_GCM && ivlen != 12) { |
| 80 | /* Set IV length. Not necessary if this is 12 bytes (96 bits) */ |
| 81 | if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL)) |
| 82 | handleErrors(); |
| 83 | } |
| 84 | |
| 85 | } catch (int) { |
| 86 | if (ctx) |
| 87 | EVP_CIPHER_CTX_free(ctx); |
| 88 | ctx = nullptr; |
| 89 | } |
| 90 | |
| 91 | return shared_ptr<EVP_CIPHER_CTX>(ctx, free_crypt_context); |
| 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, |
no test coverage detected