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.

77 lines
1.8KB

  1. #ifndef _CRYPT
  2. #define _CRYPT
  3. #include "aes.hpp"
  4. class crypt : public aes {
  5. private:
  6. EVP_CIPHER_CTX* aesEncryptCtx;
  7. public:
  8. crypt(std::string filename);
  9. crypt(const crypt& a);
  10. void init_all();
  11. int aesEncrypt(const unsigned char *msg, size_t msgLen, unsigned char **encMsg);
  12. ~crypt();
  13. };
  14. crypt::crypt(std::string filename) : aes(filename) {
  15. aesEncryptCtx = EVP_CIPHER_CTX_new();
  16. //aesEncryptCtx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));
  17. if(aesEncryptCtx == NULL) {
  18. exit(FAILURE);
  19. }
  20. init_all();
  21. }
  22. crypt::crypt(const crypt& _a) : aes::aes() {
  23. this->clone(_a);
  24. aesEncryptCtx = EVP_CIPHER_CTX_new();
  25. //aesEncryptCtx = (EVP_CIPHER_CTX*)malloc(sizeof(EVP_CIPHER_CTX));
  26. if(aesEncryptCtx == NULL) {
  27. exit(FAILURE);
  28. }
  29. int res = EVP_CIPHER_CTX_copy(aesEncryptCtx, _a.aesEncryptCtx);
  30. if(!res)
  31. exit(FAILURE);
  32. }
  33. void crypt::init_all() {
  34. setExtension(".enc");
  35. aes::init_all();
  36. EVP_CIPHER_CTX_init(aesEncryptCtx);
  37. }
  38. int crypt::aesEncrypt(const unsigned char *msg, size_t msgLen, unsigned char **encMsg) {
  39. size_t blockLen = 0;
  40. size_t encMsgLen = 0;
  41. *encMsg = (unsigned char*)malloc(msgLen + AES_BLOCK_SIZE);
  42. if(encMsg == NULL) return FAILURE;
  43. if(!EVP_EncryptInit_ex(aesEncryptCtx, EVP_aes_256_cbc(), NULL, aes::aesKey, aes::aesIV)) {
  44. return FAILURE;
  45. }
  46. if(!EVP_EncryptUpdate(aesEncryptCtx, *encMsg, (int*)&blockLen, (unsigned char*)msg, msgLen)) {
  47. return FAILURE;
  48. }
  49. encMsgLen += blockLen;
  50. if(!EVP_EncryptFinal_ex(aesEncryptCtx, *encMsg + encMsgLen, (int*)&blockLen)) {
  51. return FAILURE;
  52. }
  53. return encMsgLen + blockLen;
  54. }
  55. crypt::~crypt() {
  56. aes::clear_all();
  57. EVP_CIPHER_CTX_cleanup(aesEncryptCtx);
  58. EVP_CIPHER_CTX_free(aesEncryptCtx);
  59. //free(aesEncryptCtx);
  60. }
  61. #endif