password manager with aes encryption
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.0KB

  1. #ifndef _DECRYPT
  2. #define _DECRYPT
  3. #include "aes.hpp"
  4. class decrypt : public aes {
  5. private:
  6. EVP_CIPHER_CTX* aesDecryptCtx;
  7. public:
  8. decrypt(std::string filename, unsigned char* aesKey=0, unsigned char* aesIV=0);
  9. decrypt(const decrypt& a);
  10. void init_all(bool initSuper=true);
  11. int aesDecrypt(unsigned char *encMsg, size_t encMsgLen, unsigned char** decMsg);
  12. ~decrypt();
  13. };
  14. decrypt::decrypt(std::string filename, unsigned char* aesKey, unsigned char* aesIV) : aes(filename) {
  15. aesDecryptCtx = EVP_CIPHER_CTX_new();
  16. //aesDecryptCtx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));
  17. if(aesDecryptCtx == NULL) {
  18. exit(FAILURE);
  19. }
  20. if(aesKey && aesIV) {
  21. setAesKey(aesKey);
  22. setAesIV(aesIV);
  23. init_all(false);
  24. }
  25. else
  26. init_all();
  27. }
  28. decrypt::decrypt(const decrypt& _a) : aes::aes() {
  29. this->clone(_a);
  30. aesDecryptCtx = EVP_CIPHER_CTX_new();
  31. if(aesDecryptCtx == NULL) {
  32. exit(FAILURE);
  33. }
  34. int res = EVP_CIPHER_CTX_copy(aesDecryptCtx, _a.aesDecryptCtx);
  35. if(!res)
  36. exit(FAILURE);
  37. }
  38. void decrypt::init_all(bool initSuper) {
  39. setExtension(".dec");
  40. if(initSuper)
  41. aes::init_all();
  42. EVP_CIPHER_CTX_init(aesDecryptCtx);
  43. }
  44. int decrypt::aesDecrypt(unsigned char *encMsg, size_t encMsgLen, unsigned char **decMsg) {
  45. size_t decLen = 0;
  46. size_t blockLen = 0;
  47. *decMsg = (unsigned char*)malloc(encMsgLen);
  48. if(*decMsg == NULL) return FAILURE;
  49. if(!EVP_DecryptInit_ex(aesDecryptCtx, EVP_aes_256_cbc(), NULL, aes::aesKey, aes::aesIV)) {
  50. return FAILURE;
  51. }
  52. if(!EVP_DecryptUpdate(aesDecryptCtx, (unsigned char*)*decMsg, (int*)&blockLen, encMsg, (int)encMsgLen)) {
  53. return FAILURE;
  54. }
  55. decLen += blockLen;
  56. if(!EVP_DecryptFinal_ex(aesDecryptCtx, (unsigned char*)*decMsg + decLen, (int*)&blockLen)) {
  57. return FAILURE;
  58. }
  59. decLen += blockLen;
  60. EVP_CIPHER_CTX_cleanup(aesDecryptCtx);
  61. return (int)decLen;
  62. }
  63. decrypt::~decrypt() {
  64. aes::clear_all();
  65. EVP_CIPHER_CTX_cleanup(aesDecryptCtx);
  66. EVP_CIPHER_CTX_free(aesDecryptCtx);
  67. }
  68. #endif