std::string decrypt_aes256(const std::string& cipher,const std::string& key,const std::string& iv) { std::string plain; plain.resize((cipher.size()/AES_BLOCK_SIZE+1)*AES_BLOCK_SIZE); EVP_CIPHER_CTX* ctx=nullptr; try { std::string error_str="Decryption failed."; ctx=EVP_CIPHER_CTX_new(); if(key.size()!=AES256_KEY_SIZE) throw std::runtime_error(error_str); int temp_length; int temp_unaligned_length; if(ctx==nullptr) throw std::runtime_error(error_str); if(EVP_CIPHER_CTX_set_padding(ctx,1)==0) throw std::runtime_error(error_str); if(EVP_DecryptInit(ctx,EVP_aes_256_cbc(),(uint8_t*)key.data(),(uint8_t*)iv.data())==0) throw std::runtime_error(error_str); if(EVP_DecryptUpdate(ctx,(uint8_t*)plain.data(),&temp_length,(uint8_t*)cipher.data(),cipher.size())==0) throw std::runtime_error(error_str); if(EVP_DecryptFinal(ctx,(uint8_t*)plain.data()+temp_length,&temp_unaligned_length)==0) throw std::runtime_error(error_str); plain.resize(temp_length+temp_unaligned_length); } catch(...) { aes_cleanup(ctx); throw; } aes_cleanup(ctx); return plain; }
std::string encrypt_aes256(const std::string& plain,const std::string& key,const std::string& iv) { std::string cipher; cipher.resize((plain.size()/AES_BLOCK_SIZE+1)*AES_BLOCK_SIZE); EVP_CIPHER_CTX* ctx=nullptr; try { ctx=EVP_CIPHER_CTX_new(); if(key.size()!=AES256_KEY_SIZE) throw std::runtime_error("encrypt_aes256() - Given key size is invalid ("+ std::to_string(AES256_KEY_SIZE)+"bytes )."); int temp_length; int temp_unaligned_length; if(ctx==nullptr) throw std::runtime_error("encrypt_aes256() - Creating a EVP_CIPHER_CTX failed."); if(EVP_CIPHER_CTX_set_padding(ctx,1)==0) throw std::runtime_error("encrypt_aes256() - EVP_CIPHER_CTX_set_padding failed."); if(EVP_EncryptInit(ctx,EVP_aes_256_cbc(),(uint8_t*)key.data(),(uint8_t*)iv.data())==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptInit failed."); if(EVP_EncryptUpdate(ctx,(uint8_t*)cipher.data(),&temp_length,(uint8_t*)plain.data(),plain.size())==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptUpdate failed."); if(EVP_EncryptFinal(ctx,(uint8_t*)cipher.data()+temp_length,&temp_unaligned_length)==0) throw std::runtime_error("encrypt_aes256() - EVP_EncryptFinal failed."); cipher.resize(temp_length+temp_unaligned_length); } catch(...) { aes_cleanup(ctx); throw; } aes_cleanup(ctx); return cipher; }
void cleanup_crypto(crypto_ctx_t *cctx) { aes_cleanup(cctx->crypto_ctx); memset(cctx->salt, 0, 32); free(cctx->salt); free(cctx); }