@@ -820,10 +820,15 @@ CipherBase::UpdateResult CipherBase::Update(
820820 len);
821821
822822 CHECK_LE (static_cast <size_t >(buf_len), (*out)->ByteLength ());
823- if (buf_len == 0 )
823+ if (buf_len == 0 ) {
824824 *out = ArrayBuffer::NewBackingStore (env ()->isolate (), 0 );
825- else
826- *out = BackingStore::Reallocate (env ()->isolate (), std::move (*out), buf_len);
825+ } else if (static_cast <size_t >(buf_len) != (*out)->ByteLength ()) {
826+ std::unique_ptr<BackingStore> old_out = std::move (*out);
827+ *out = ArrayBuffer::NewBackingStore (env ()->isolate (), buf_len);
828+ memcpy (static_cast <char *>((*out)->Data ()),
829+ static_cast <char *>(old_out->Data ()),
830+ buf_len);
831+ }
827832
828833 // When in CCM mode, EVP_CipherUpdate will fail if the authentication tag is
829834 // invalid. In that case, remember the error and throw in final().
@@ -911,11 +916,14 @@ bool CipherBase::Final(std::unique_ptr<BackingStore>* out) {
911916 &out_len) == 1 ;
912917
913918 CHECK_LE (static_cast <size_t >(out_len), (*out)->ByteLength ());
914- if (out_len > 0 ) {
915- *out =
916- BackingStore::Reallocate (env ()->isolate (), std::move (*out), out_len);
917- } else {
919+ if (out_len == 0 ) {
918920 *out = ArrayBuffer::NewBackingStore (env ()->isolate (), 0 );
921+ } else if (static_cast <size_t >(out_len) != (*out)->ByteLength ()) {
922+ std::unique_ptr<BackingStore> old_out = std::move (*out);
923+ *out = ArrayBuffer::NewBackingStore (env ()->isolate (), out_len);
924+ memcpy (static_cast <char *>((*out)->Data ()),
925+ static_cast <char *>(old_out->Data ()),
926+ out_len);
919927 }
920928
921929 if (ok && kind_ == kCipher && IsAuthenticatedMode ()) {
@@ -1015,10 +1023,15 @@ bool PublicKeyCipher::Cipher(
10151023 }
10161024
10171025 CHECK_LE (out_len, (*out)->ByteLength ());
1018- if (out_len > 0 )
1019- *out = BackingStore::Reallocate (env->isolate (), std::move (*out), out_len);
1020- else
1026+ if (out_len == 0 ) {
10211027 *out = ArrayBuffer::NewBackingStore (env->isolate (), 0 );
1028+ } else if (out_len != (*out)->ByteLength ()) {
1029+ std::unique_ptr<BackingStore> old_out = std::move (*out);
1030+ *out = ArrayBuffer::NewBackingStore (env->isolate (), out_len);
1031+ memcpy (static_cast <char *>((*out)->Data ()),
1032+ static_cast <char *>(old_out->Data ()),
1033+ out_len);
1034+ }
10221035
10231036 return true ;
10241037}
0 commit comments