Skip to content

Commit cecbc27

Browse files
committed
Make cipher field in AESCipher and AESCipherCBCnoPad thread safe
DEVSIX-8435
1 parent 5a8f86d commit cecbc27

File tree

9 files changed

+41
-64
lines changed

9 files changed

+41
-64
lines changed

kernel/src/main/java/com/itextpdf/kernel/crypto/AESCipher.java

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -27,45 +27,28 @@ This file is part of the iText (R) project.
2727
import com.itextpdf.kernel.exceptions.KernelExceptionMessageConstant;
2828
import com.itextpdf.kernel.exceptions.PdfException;
2929
import com.itextpdf.kernel.logs.KernelLogMessageConstant;
30+
import org.slf4j.Logger;
31+
import org.slf4j.LoggerFactory;
3032

31-
import java.security.InvalidAlgorithmParameterException;
32-
import java.security.InvalidKeyException;
33-
import java.security.NoSuchAlgorithmException;
3433
import javax.crypto.BadPaddingException;
3534
import javax.crypto.Cipher;
3635
import javax.crypto.IllegalBlockSizeException;
37-
import javax.crypto.NoSuchPaddingException;
3836
import javax.crypto.spec.IvParameterSpec;
3937
import javax.crypto.spec.SecretKeySpec;
40-
import org.slf4j.Logger;
41-
import org.slf4j.LoggerFactory;
38+
import java.security.GeneralSecurityException;
4239

4340
/**
4441
* Creates an AES Cipher with CBC and padding PKCS5/7.
4542
*/
4643
public class AESCipher {
47-
44+
4845
private static final Logger LOGGER = LoggerFactory.getLogger(AESCipher.class);
4946

5047
private static final String CIPHER_WITH_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
5148

5249
private static final IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.getFactory();
5350

54-
private static Cipher cipher;
55-
56-
static {
57-
try {
58-
if ("BC".equals(BOUNCY_CASTLE_FACTORY.getProviderName())) {
59-
// Do not pass bc provider and use default one here not to require bc provider for this functionality
60-
// Do not use bc provider in kernel
61-
cipher = Cipher.getInstance(CIPHER_WITH_PKCS5_PADDING);
62-
} else {
63-
cipher = Cipher.getInstance(CIPHER_WITH_PKCS5_PADDING, BOUNCY_CASTLE_FACTORY.getProvider());
64-
}
65-
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
66-
throw new PdfException(KernelExceptionMessageConstant.ERROR_WHILE_INITIALIZING_AES_CIPHER, e);
67-
}
68-
}
51+
private final Cipher cipher;
6952

7053
/**
7154
* Creates a new instance of AESCipher
@@ -77,10 +60,17 @@ public class AESCipher {
7760
*/
7861
public AESCipher(boolean forEncryption, byte[] key, byte[] iv) {
7962
try {
63+
if ("BC".equals(BOUNCY_CASTLE_FACTORY.getProviderName())) {
64+
// Do not pass bc provider and use default one here not to require bc provider for this functionality
65+
// Do not use bc provider in kernel
66+
cipher = Cipher.getInstance(CIPHER_WITH_PKCS5_PADDING);
67+
} else {
68+
cipher = Cipher.getInstance(CIPHER_WITH_PKCS5_PADDING, BOUNCY_CASTLE_FACTORY.getProvider());
69+
}
8070
cipher.init(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE,
8171
new SecretKeySpec(key, "AES"),
8272
new IvParameterSpec(iv));
83-
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
73+
} catch (GeneralSecurityException e) {
8474
throw new PdfException(KernelExceptionMessageConstant.ERROR_WHILE_INITIALIZING_AES_CIPHER, e);
8575
}
8676
}

kernel/src/main/java/com/itextpdf/kernel/crypto/AESCipherCBCnoPad.java

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,10 @@ This file is part of the iText (R) project.
2727
import com.itextpdf.kernel.exceptions.KernelExceptionMessageConstant;
2828
import com.itextpdf.kernel.exceptions.PdfException;
2929

30-
import java.security.InvalidAlgorithmParameterException;
31-
import java.security.InvalidKeyException;
32-
import java.security.NoSuchAlgorithmException;
3330
import javax.crypto.Cipher;
34-
import javax.crypto.NoSuchPaddingException;
3531
import javax.crypto.spec.IvParameterSpec;
3632
import javax.crypto.spec.SecretKeySpec;
33+
import java.security.GeneralSecurityException;
3734

3835
/**
3936
* Creates an AES Cipher with CBC and no padding.
@@ -44,21 +41,7 @@ public class AESCipherCBCnoPad {
4441

4542
private static final IBouncyCastleFactory BOUNCY_CASTLE_FACTORY = BouncyCastleFactoryCreator.getFactory();
4643

47-
private static Cipher cipher;
48-
49-
static {
50-
try {
51-
if ("BC".equals(BOUNCY_CASTLE_FACTORY.getProviderName())) {
52-
// Do not pass bc provider and use default one here not to require bc provider for this functionality
53-
// Do not use bc provider in kernel
54-
cipher = Cipher.getInstance(CIPHER_WITHOUT_PADDING);
55-
} else {
56-
cipher = Cipher.getInstance(CIPHER_WITHOUT_PADDING, BOUNCY_CASTLE_FACTORY.getProvider());
57-
}
58-
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
59-
throw new PdfException(KernelExceptionMessageConstant.ERROR_WHILE_INITIALIZING_AES_CIPHER, e);
60-
}
61-
}
44+
private final Cipher cipher;
6245

6346
/**
6447
* Creates a new instance of AESCipher with CBC and no padding
@@ -81,10 +64,17 @@ public AESCipherCBCnoPad(boolean forEncryption, byte[] key) {
8164
*/
8265
public AESCipherCBCnoPad(boolean forEncryption, byte[] key, byte[] initVector) {
8366
try {
67+
if ("BC".equals(BOUNCY_CASTLE_FACTORY.getProviderName())) {
68+
// Do not pass bc provider and use default one here not to require bc provider for this functionality
69+
// Do not use bc provider in kernel
70+
cipher = Cipher.getInstance(CIPHER_WITHOUT_PADDING);
71+
} else {
72+
cipher = Cipher.getInstance(CIPHER_WITHOUT_PADDING, BOUNCY_CASTLE_FACTORY.getProvider());
73+
}
8474
cipher.init(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE,
8575
new SecretKeySpec(key, "AES"),
8676
new IvParameterSpec(initVector));
87-
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
77+
} catch (GeneralSecurityException e) {
8878
throw new PdfException(KernelExceptionMessageConstant.ERROR_WHILE_INITIALIZING_AES_CIPHER, e);
8979
}
9080
}

kernel/src/main/java/com/itextpdf/kernel/crypto/securityhandler/EncryptionUtils.java

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ This file is part of the iText (R) project.
5050
import java.security.cert.Certificate;
5151
import java.security.cert.X509Certificate;
5252
import java.util.HashSet;
53-
import java.util.Iterator;
5453
import java.util.Set;
5554
import javax.crypto.Cipher;
5655
import javax.crypto.KeyGenerator;
@@ -114,11 +113,7 @@ static byte[] fetchEnvelopedData(Key certificateKey, Certificate certificate, St
114113
ICMSEnvelopedData data;
115114
try {
116115
data = BOUNCY_CASTLE_FACTORY.createCMSEnvelopedData(recipient.getValueBytes());
117-
Iterator<IRecipientInformation> recipientCertificatesIt =
118-
data.getRecipientInfos().getRecipients().iterator();
119-
while (recipientCertificatesIt.hasNext()) {
120-
IRecipientInformation recipientInfo = recipientCertificatesIt.next();
121-
116+
for (IRecipientInformation recipientInfo : data.getRecipientInfos().getRecipients()) {
122117
if (recipientInfo.getRID().match(certHolder) && !foundRecipient) {
123118
envelopedData = PdfEncryptor.getContent(recipientInfo, (PrivateKey) certificateKey,
124119
certificateKeyProvider);

kernel/src/main/java/com/itextpdf/kernel/pdf/PdfNumTree.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@ public PdfDictionary buildTree() {
8080
if (numbers.length <= NODE_SIZE) {
8181
PdfDictionary dic = new PdfDictionary();
8282
PdfArray ar = new PdfArray();
83-
for (int k = 0; k < numbers.length; ++k) {
84-
ar.add(new PdfNumber((int) numbers[k]));
85-
ar.add(items.get(numbers[k]));
83+
for (Integer number : numbers) {
84+
ar.add(new PdfNumber((int) number));
85+
ar.add(items.get(number));
8686
}
8787
dic.put(PdfName.Nums, ar);
8888
return dic;

kernel/src/main/java/com/itextpdf/kernel/pdf/PdfWriter.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ public PdfWriter(String filename, WriterProperties properties) throws FileNotFou
120120
* @return true if to use full compression, false otherwise.
121121
*/
122122
public boolean isFullCompression() {
123-
return properties.isFullCompression != null ? (boolean) properties.isFullCompression : false;
123+
return properties.isFullCompression != null && (boolean) properties.isFullCompression;
124124
}
125125

126126
/**

sign/src/main/java/com/itextpdf/signatures/validation/v1/CRLValidator.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ private void verifyCrlIntegrity(ValidationReport report, ValidationContext conte
325325
}
326326

327327
private Certificate getRoot(Certificate cert) {
328-
Certificate[] chain = certificateRetriever.retrieveMissingCertificates(new Certificate[] {cert});
328+
Certificate[] chain = certificateRetriever.retrieveMissingCertificates(new Certificate[]{cert});
329329
return chain[chain.length - 1];
330330
}
331331

sign/src/main/java/com/itextpdf/signatures/validation/v1/OCSPValidator.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,7 @@ public void validate(ValidationReport report, ValidationContext context, X509Cer
126126
* @param responseGenerationDate trusted date at which response is generated
127127
*/
128128
public void validate(ValidationReport report, ValidationContext context, X509Certificate certificate,
129-
ISingleResp singleResp, IBasicOCSPResp ocspResp, Date validationDate,
130-
Date responseGenerationDate) {
129+
ISingleResp singleResp, IBasicOCSPResp ocspResp, Date validationDate, Date responseGenerationDate) {
131130
ValidationContext localContext = context.setValidatorContext(ValidatorContext.OCSP_VALIDATOR);
132131
if (CertificateUtil.isSelfSigned(certificate)) {
133132
report.addReportItem(new CertificateReportItem(certificate, OCSP_CHECK,

sign/src/main/java/com/itextpdf/signatures/validation/v1/SafeCalling.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ private SafeCalling() {}
3737

3838
/**
3939
* Adds a report item to the report when an exception is thrown in the action.
40+
*
4041
* @param action The action to perform
4142
* @param report The report to add the ReportItem to
4243
* @param reportItemCreator A callback to generate a ReportItem
@@ -52,13 +53,14 @@ public static void onExceptionLog(ThrowingAction action, ValidationReport report
5253

5354
/**
5455
* Adds a report item to the report when an exception is thrown in the action.
56+
*
5557
* @param action The action to perform
5658
* @param defaultValue The value to return when an exception is thrown
5759
* @param report The report to add the ReportItem to
5860
* @param reportItemCreator A callback to generate a ReportItem
61+
* @param <T>
5962
*
6063
* @return The returned value from the action
61-
* @param <T>
6264
*/
6365
public static <T> T onExceptionLog(ThrowingSupplier<T> action, T defaultValue, ValidationReport report,
6466
Function<Exception, ReportItem> reportItemCreator) {
@@ -72,6 +74,7 @@ public static <T> T onExceptionLog(ThrowingSupplier<T> action, T defaultValue, V
7274

7375
/**
7476
* Adds a report item to the report when an exception is thrown in the action.
77+
*
7578
* @param action The action to perform
7679
* @param report The report to add the ReportItem to
7780
* @param reportItemCreator A callback to generate a ReportItem
@@ -85,16 +88,16 @@ public static void onRuntimeExceptionLog(Action action, ValidationReport report,
8588
}
8689
}
8790

88-
8991
/**
9092
* Adds a report item to the report when an exception is thrown in the action.
93+
*
9194
* @param action The action to perform
9295
* @param defaultValue The value to return when an exception is thrown
9396
* @param report The report to add the ReportItem to
9497
* @param reportItemCreator A callback to generate a ReportItem
98+
* @param <T>
9599
*
96100
* @return The returned value from the action
97-
* @param <T>
98101
*/
99102
public static <T> T onRuntimeExceptionLog(Supplier<T> action, T defaultValue, ValidationReport report,
100103
Function<Exception, ReportItem> reportItemCreator) {

sign/src/main/java/com/itextpdf/signatures/validation/v1/SignatureValidationProperties.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,14 @@ public class SignatureValidationProperties {
6666
* Create {@link SignatureValidationProperties} with default values.
6767
*/
6868
public SignatureValidationProperties() {
69-
setContinueAfterFailure(ValidatorContexts.all(),CertificateSources.all(), DEFAULT_CONTINUE_AFTER_FAILURE);
70-
setRevocationOnlineFetching(ValidatorContexts.all(),CertificateSources.all(), TimeBasedContexts.all(),
69+
setContinueAfterFailure(ValidatorContexts.all(), CertificateSources.all(), DEFAULT_CONTINUE_AFTER_FAILURE);
70+
setRevocationOnlineFetching(ValidatorContexts.all(), CertificateSources.all(), TimeBasedContexts.all(),
7171
DEFAULT_ONLINE_FETCHING);
7272

73-
setFreshness(ValidatorContexts.all(),CertificateSources.all(),
73+
setFreshness(ValidatorContexts.all(), CertificateSources.all(),
7474
TimeBasedContexts.of(TimeBasedContext.HISTORICAL), DEFAULT_FRESHNESS_HISTORICAL);
75-
setFreshness(ValidatorContexts.all(),CertificateSources.all(),
76-
TimeBasedContexts.of(TimeBasedContext.PRESENT),DEFAULT_FRESHNESS_PRESENT_OCSP);
75+
setFreshness(ValidatorContexts.all(), CertificateSources.all(),
76+
TimeBasedContexts.of(TimeBasedContext.PRESENT), DEFAULT_FRESHNESS_PRESENT_OCSP);
7777
setFreshness(ValidatorContexts.of(ValidatorContext.CRL_VALIDATOR), CertificateSources.all(),
7878
TimeBasedContexts.of(TimeBasedContext.PRESENT), DEFAULT_FRESHNESS_PRESENT_CRL);
7979

0 commit comments

Comments
 (0)