55
66#include " crypter.h"
77
8+ #include " crypto/aes.h"
89#include " script/script.h"
910#include " script/standard.h"
1011#include " util.h"
@@ -53,22 +54,14 @@ bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned
5354 return false ;
5455
5556 // max ciphertext len for a n bytes of plaintext is
56- // n + AES_BLOCK_SIZE - 1 bytes
57- int nLen = vchPlaintext.size ();
58- int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0 ;
59- vchCiphertext = std::vector<unsigned char >(nCLen);
60-
61- bool fOk = true ;
62-
63- EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new ();
64- if (fOk ) fOk = EVP_EncryptInit_ex (ctx, EVP_aes_256_cbc (), NULL , chKey, chIV) != 0 ;
65- if (fOk ) fOk = EVP_EncryptUpdate (ctx, &vchCiphertext[0 ], &nCLen, &vchPlaintext[0 ], nLen) != 0 ;
66- if (fOk ) fOk = EVP_EncryptFinal_ex (ctx, (&vchCiphertext[0 ]) + nCLen, &nFLen) != 0 ;
67- EVP_CIPHER_CTX_free (ctx);
57+ // n + AES_BLOCKSIZE bytes
58+ vchCiphertext.resize (vchPlaintext.size () + AES_BLOCKSIZE);
6859
69- if (!fOk ) return false ;
70-
71- vchCiphertext.resize (nCLen + nFLen);
60+ AES256CBCEncrypt enc (chKey, chIV, true );
61+ size_t nLen = enc.Encrypt (&vchPlaintext[0 ], vchPlaintext.size (), &vchCiphertext[0 ]);
62+ if (nLen < vchPlaintext.size ())
63+ return false ;
64+ vchCiphertext.resize (nLen);
7265 return true ;
7366}
7467
@@ -79,21 +72,12 @@ bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingM
7972
8073 // plaintext will always be equal to or lesser than length of ciphertext
8174 int nLen = vchCiphertext.size ();
82- int nPLen = nLen, nFLen = 0 ;
83-
84- vchPlaintext = CKeyingMaterial (nPLen);
85-
86- bool fOk = true ;
87-
88- EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new ();
89- if (fOk ) fOk = EVP_DecryptInit_ex (ctx, EVP_aes_256_cbc (), NULL , chKey, chIV) != 0 ;
90- if (fOk ) fOk = EVP_DecryptUpdate (ctx, &vchPlaintext[0 ], &nPLen, &vchCiphertext[0 ], nLen) != 0 ;
91- if (fOk ) fOk = EVP_DecryptFinal_ex (ctx, (&vchPlaintext[0 ]) + nPLen, &nFLen) != 0 ;
92- EVP_CIPHER_CTX_free (ctx);
93-
94- if (!fOk ) return false ;
95-
96- vchPlaintext.resize (nPLen + nFLen);
75+ vchPlaintext.resize (nLen);
76+ AES256CBCDecrypt dec (chKey, chIV, true );
77+ nLen = dec.Decrypt (&vchCiphertext[0 ], vchCiphertext.size (), &vchPlaintext[0 ]);
78+ if (nLen == 0 )
79+ return false ;
80+ vchPlaintext.resize (nLen);
9781 return true ;
9882}
9983
0 commit comments