@@ -21,6 +21,7 @@ public class CipherSubscriber implements Subscriber<ByteBuffer> {
2121 private final Long contentLength ;
2222 private final boolean isLastPart ;
2323 private final int tagLength ;
24+ private final boolean isEncrypt ;
2425 private final AtomicBoolean finalBytesCalled = new AtomicBoolean (false );
2526
2627 private byte [] outputBuffer ;
@@ -31,6 +32,7 @@ public class CipherSubscriber implements Subscriber<ByteBuffer> {
3132 this .cipher = materials .getCipher (iv );
3233 this .isLastPart = isLastPart ;
3334 this .tagLength = materials .algorithmSuite ().cipherTagLengthBytes ();
35+ this .isEncrypt = (CipherMode .DECRYPT != materials .cipherMode ());
3436 }
3537
3638 CipherSubscriber (Subscriber <? super ByteBuffer > wrappedSubscriber , Long contentLength , CryptographicMaterials materials , byte [] iv ) {
@@ -73,7 +75,9 @@ public void onNext(ByteBuffer byteBuffer) {
7375 // Note that while the JCE Javadoc specifies that the outputBuffer is null in this case,
7476 // in practice SunJCE and ACCP return an empty buffer instead, hence checks for
7577 // null OR length == 0.
76- if (contentRead .get () + tagLength >= contentLength ) {
78+
79+ // tagLength should only be added on Encrypt
80+ if (contentRead .get () + (isEncrypt ? tagLength : 0 ) >= contentLength ) {
7781 // All content has been read, so complete to get the final bytes
7882 System .out .println ("[CipherSubscriber] All content read (" + contentRead .get () + " bytes), proceeding to finalBytes" );
7983 finalBytes ();
@@ -154,7 +158,8 @@ public void onComplete() {
154158 // In rare cases, e.g. when the last part of a low-level MPU has 0 length,
155159 // onComplete will be called before onNext is called once.
156160 System .out .println ("[CipherSubscriber] onComplete called" );
157- if (contentRead .get () + tagLength <= contentLength ) {
161+ // tagLength should only be added on Encrypt
162+ if (contentRead .get () + (isEncrypt ? tagLength : 0 ) >= contentLength ) {
158163 System .out .println ("[CipherSubscriber] onComplete called prematurely! The content read is " + contentRead .get () + " but the contentLength is " + contentLength );
159164 finalBytes ();
160165 }
0 commit comments