Skip to content

Commit e8914d4

Browse files
committed
improve taglength, comment code
1 parent 8ca7c00 commit e8914d4

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

src/main/java/software/amazon/encryption/s3/internal/CipherSubscriber.java

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,29 +17,20 @@
1717
public class CipherSubscriber implements Subscriber<ByteBuffer> {
1818
private final AtomicLong contentRead = new AtomicLong(0);
1919
private final Subscriber<? super ByteBuffer> wrappedSubscriber;
20-
private Cipher cipher;
20+
private final Cipher cipher;
2121
private final Long contentLength;
22-
private boolean isLastPart;
23-
private int tagLength;
24-
private AtomicBoolean finalBytesCalled = new AtomicBoolean(false);
22+
private final boolean isLastPart;
23+
private final int tagLength;
24+
private final AtomicBoolean finalBytesCalled = new AtomicBoolean(false);
2525

2626
private byte[] outputBuffer;
2727

2828
CipherSubscriber(Subscriber<? super ByteBuffer> wrappedSubscriber, Long contentLength, CryptographicMaterials materials, byte[] iv, boolean isLastPart) {
2929
this.wrappedSubscriber = wrappedSubscriber;
3030
this.contentLength = contentLength;
31-
cipher = materials.getCipher(iv);
31+
this.cipher = materials.getCipher(iv);
3232
this.isLastPart = isLastPart;
33-
34-
// Determine the tag length based on the cipher algorithm.
35-
// This class uses the tag length to identify the end of the stream before the onComplete signal is sent.
36-
if (cipher.getAlgorithm().contains("GCM")) {
37-
tagLength = 16;
38-
} else if (cipher.getAlgorithm().contains("CBC") || cipher.getAlgorithm().contains("CTR")) {
39-
tagLength = 0;
40-
} else {
41-
throw new IllegalArgumentException("Unsupported cipher type: " + cipher.getAlgorithm());
42-
}
33+
this.tagLength = materials.algorithmSuite().cipherTagLengthBytes();
4334
}
4435

4536
CipherSubscriber(Subscriber<? super ByteBuffer> wrappedSubscriber, Long contentLength, CryptographicMaterials materials, byte[] iv) {
@@ -140,7 +131,12 @@ public void onComplete() {
140131
wrappedSubscriber.onComplete();
141132
}
142133

143-
public void finalBytes() {
134+
/**
135+
* Finalize encryption, including calculating the auth tag for AES-GCM.
136+
* As such this method MUST only be called once, which is enforced using
137+
* `finalBytesCalled`.
138+
*/
139+
private void finalBytes() {
144140
if (!finalBytesCalled.compareAndSet(false, true)) {
145141
// already called, don't repeat
146142
return;

0 commit comments

Comments
 (0)