@@ -830,10 +830,15 @@ CipherBase::UpdateResult CipherBase::Update(
830830 len);
831831
832832 CHECK_LE (static_cast <size_t >(buf_len), (*out)->ByteLength ());
833- if (buf_len == 0 )
833+ if (buf_len == 0 ) {
834834 *out = ArrayBuffer::NewBackingStore (env ()->isolate (), 0 );
835- else
836- *out = BackingStore::Reallocate (env ()->isolate (), std::move (*out), buf_len);
835+ } else if (static_cast <size_t >(buf_len) != (*out)->ByteLength ()) {
836+ std::unique_ptr<BackingStore> old_out = std::move (*out);
837+ *out = ArrayBuffer::NewBackingStore (env ()->isolate (), buf_len);
838+ memcpy (static_cast <char *>((*out)->Data ()),
839+ static_cast <char *>(old_out->Data ()),
840+ buf_len);
841+ }
837842
838843 // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
839844 // invalid. In that case, remember the error and throw in final().
@@ -921,11 +926,14 @@ bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
921926 &out_len) == 1 ;
922927
923928 CHECK_LE (static_cast <size_t >(out_len), (*out)->ByteLength ());
924- if (out_len > 0 ) {
925- *out =
926- BackingStore::Reallocate (env ()->isolate (), std::move (*out), out_len);
927- } else {
929+ if (out_len == 0 ) {
928930 *out = ArrayBuffer::NewBackingStore (env ()->isolate (), 0 );
931+ } else if (static_cast <size_t >(out_len) != (*out)->ByteLength ()) {
932+ std::unique_ptr<BackingStore> old_out = std::move (*out);
933+ *out = ArrayBuffer::NewBackingStore (env ()->isolate (), out_len);
934+ memcpy (static_cast <char *>((*out)->Data ()),
935+ static_cast <char *>(old_out->Data ()),
936+ out_len);
929937 }
930938
931939 if (ok && kind_ == kCipher && IsAuthenticatedMode ()) {
@@ -1025,10 +1033,15 @@ bool PublicKeyCipher::Cipher(
10251033 }
10261034
10271035 CHECK_LE (out_len, (*out)->ByteLength ());
1028- if (out_len > 0 )
1029- *out = BackingStore::Reallocate (env->isolate (), std::move (*out), out_len);
1030- else
1036+ if (out_len == 0 ) {
10311037 *out = ArrayBuffer::NewBackingStore (env->isolate (), 0 );
1038+ } else if (out_len != (*out)->ByteLength ()) {
1039+ std::unique_ptr<BackingStore> old_out = std::move (*out);
1040+ *out = ArrayBuffer::NewBackingStore (env->isolate (), out_len);
1041+ memcpy (static_cast <char *>((*out)->Data ()),
1042+ static_cast <char *>(old_out->Data ()),
1043+ out_len);
1044+ }
10321045
10331046 return true ;
10341047}
0 commit comments