| 224 | } |
| 225 | |
| 226 | unsigned aes_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, |
| 227 | unsigned char *iv, unsigned char *plaintext) |
| 228 | { |
| 229 | evp_cipher_ctx ctx( EVP_CIPHER_CTX_new() ); |
| 230 | int len = 0; |
| 231 | unsigned plaintext_len = 0; |
| 232 | |
| 233 | /* Create and initialise the context */ |
| 234 | if(!ctx) |
| 235 | { |
| 236 | FC_THROW_EXCEPTION( aes_exception, "error allocating evp cipher context", |
| 237 | ("s", ERR_error_string( ERR_get_error(), nullptr) ) ); |
| 238 | } |
| 239 | |
| 240 | /* Initialise the decryption operation. IMPORTANT - ensure you use a key |
| 241 | * * and IV size appropriate for your cipher |
| 242 | * * In this example we are using 256 bit AES (i.e. a 256 bit key). The |
| 243 | * * IV size for *most* modes is the same as the block size. For AES this |
| 244 | * * is 128 bits */ |
| 245 | if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) |
| 246 | { |
| 247 | FC_THROW_EXCEPTION( aes_exception, "error during aes 256 cbc decrypt init", |
| 248 | ("s", ERR_error_string( ERR_get_error(), nullptr) ) ); |
| 249 | } |
| 250 | |
| 251 | /* Provide the message to be decrypted, and obtain the plaintext output. |
| 252 | * * EVP_DecryptUpdate can be called multiple times if necessary |
| 253 | * */ |
| 254 | if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) |
| 255 | { |
| 256 | FC_THROW_EXCEPTION( aes_exception, "error during aes 256 cbc decrypt update", |
| 257 | ("s", ERR_error_string( ERR_get_error(), nullptr) ) ); |
| 258 | } |
| 259 | |
| 260 | plaintext_len = len; |
| 261 | |
| 262 | /* Finalise the decryption. Further plaintext bytes may be written at |
| 263 | * * this stage. |
| 264 | * */ |
| 265 | if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) |
| 266 | { |
| 267 | FC_THROW_EXCEPTION( aes_exception, "error during aes 256 cbc decrypt final", |
| 268 | ("s", ERR_error_string( ERR_get_error(), nullptr) ) ); |
| 269 | } |
| 270 | plaintext_len += len; |
| 271 | |
| 272 | return plaintext_len; |
| 273 | } |
| 274 | |
| 275 | unsigned aes_cfb_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, |
| 276 | unsigned char *iv, unsigned char *plaintext) |