1
1
/*
2
- * Copyright (c) 2002, 2018 , Oracle and/or its affiliates. All rights reserved.
2
+ * Copyright (c) 2002, 2022 , Oracle and/or its affiliates. All rights reserved.
3
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
4
*
5
5
* This code is free software; you can redistribute it and/or modify it
@@ -915,10 +915,10 @@ int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
915
915
int estOutSize = getOutputSizeByOperation (inputLen , true );
916
916
int outputCapacity = checkOutputCapacity (output , outputOffset ,
917
917
estOutSize );
918
- int offset = decrypting ? 0 : outputOffset ; // 0 for decrypting
918
+ int offset = outputOffset ; // 0 for decrypting
919
919
byte [] finalBuf = prepareInputBuffer (input , inputOffset ,
920
920
inputLen , output , outputOffset );
921
- byte [] outWithPadding = null ; // for decrypting only
921
+ byte [] internalOutput = null ; // for decrypting only
922
922
923
923
int finalOffset = (finalBuf == input ) ? inputOffset : 0 ;
924
924
int finalBufLen = (finalBuf == input ) ? inputLen : finalBuf .length ;
@@ -932,11 +932,15 @@ int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
932
932
if (outputCapacity < estOutSize ) {
933
933
cipher .save ();
934
934
}
935
- // create temporary output buffer so that only "real"
936
- // data bytes are passed to user's output buffer.
937
- outWithPadding = new byte [estOutSize ];
935
+ if (outputCapacity < estOutSize || padding != null ) {
936
+ // create temporary output buffer if the estimated size is larger
937
+ // than the user-provided buffer or a padding needs to be removed
938
+ // before copying the unpadded result to the output buffer
939
+ internalOutput = new byte [estOutSize ];
940
+ offset = 0 ;
941
+ }
938
942
}
939
- byte [] outBuffer = decrypting ? outWithPadding : output ;
943
+ byte [] outBuffer = ( internalOutput != null ) ? internalOutput : output ;
940
944
941
945
int outLen = fillOutputBuffer (finalBuf , finalOffset , outBuffer ,
942
946
offset , finalBufLen , input );
@@ -952,9 +956,11 @@ int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
952
956
+ " bytes needed" );
953
957
}
954
958
// copy the result into user-supplied output buffer
955
- System .arraycopy (outWithPadding , 0 , output , outputOffset , outLen );
956
- // decrypt mode. Zero out output data that's not required
957
- Arrays .fill (outWithPadding , (byte ) 0x00 );
959
+ if (internalOutput != null ) {
960
+ System .arraycopy (internalOutput , 0 , output , outputOffset , outLen );
961
+ // decrypt mode. Zero out output data that's not required
962
+ Arrays .fill (internalOutput , (byte ) 0x00 );
963
+ }
958
964
}
959
965
endDoFinal ();
960
966
return outLen ;
0 commit comments