Skip to content

Commit 3fcc9ff

Browse files
committed
[refactor] Cleanup exception to error mapping
1 parent 1b06acb commit 3fcc9ff

File tree

16 files changed

+107
-70
lines changed

16 files changed

+107
-70
lines changed

src/main/java/ro/kuberam/libs/java/crypto/CryptoError.java

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,33 +19,49 @@
1919
*/
2020
package ro.kuberam.libs.java.crypto;
2121

22+
import javax.annotation.Nullable;
23+
import javax.crypto.BadPaddingException;
24+
import javax.crypto.IllegalBlockSizeException;
25+
import javax.crypto.NoSuchPaddingException;
26+
import java.security.InvalidKeyException;
27+
import java.security.KeyStoreException;
28+
import java.security.NoSuchAlgorithmException;
29+
import java.security.NoSuchProviderException;
30+
import java.security.spec.InvalidKeySpecException;
31+
2232
public enum CryptoError {
2333

24-
UNKNOWN_ALGORITH("crypto:unknown-algorithm", "The specified algorithm is not supported."),
34+
UNKNOWN_ALGORITHM("crypto:unknown-algorithm", "The specified algorithm is not supported.", NoSuchAlgorithmException.class),
2535
UNKNOWN_PROVIDER("crypto:unknown-provider", "The specified provider is not available."),
2636
SIGNATURE_TYPE("crypto:signature-type", "The specified signature type is not supported."),
2737
UNREADABLE_KEYSTORE("crypto:unreadable-keystore", "I/O error while reading keystore, or the password is incorrect."),
2838
DENIED_KEYSTORE("crypto:denied-keystore", "Permission denied to read keystore."),
2939
KEYSTORE_URL("crypto:keystore-url", "The keystore URL is invalid."),
30-
KEYSTORE_TYPE("crypto:keystore-type", "The keystore type is not supported."),
40+
KEYSTORE_TYPE("crypto:keystore-type", "The keystore type is not supported.", KeyStoreException.class),
3141
ALIAS_KEY("crypto:alias-key", "Cannot find key for alias in given keystore."),
3242
SIGNATURE_ELEMENT("crypto:signature-element", "Cannot find Signature element."),
33-
INEXISTENT_PADDING("crypto:inexistent-padding", "No such padding."),
34-
INCORRECT_PADDING("crypto:incorrect-padding", "Incorrect padding."),
43+
INEXISTENT_PADDING("crypto:inexistent-padding", "No such padding.", NoSuchPaddingException.class),
44+
INCORRECT_PADDING("crypto:incorrect-padding", "Incorrect padding.", BadPaddingException.class),
3545
ENCRYPTION_TYPE("crypto:encryption-type", "The encryption type is not supported."),
36-
INVALID_CRYPTO_KEY("crypto:invalid-crypto-key", "The cryptographic key is invalid."),
37-
BLOCK_SIZE("crypto:block-size", "Illegal block size."),
46+
INVALID_CRYPTO_KEY("crypto:invalid-crypto-key", "The cryptographic key is invalid.", InvalidKeySpecException.class, InvalidKeyException.class),
47+
BLOCK_SIZE("crypto:block-size", "Illegal block size.", IllegalBlockSizeException.class),
3848
DECRYPTION_TYPE("crypto:decryption-type", "The decryption type is not supported."),
39-
NO_PROVIDER("crypto:no-provider", "The provider is not set."),
49+
NO_PROVIDER("crypto:no-provider", "The provider is not set.", NoSuchProviderException.class),
4050
INPUT_RESOURCES("crypto.input-resources", "The 'enveloped' and 'enveloping' signatures have to be applied to only one resource."),
4151
INCORRECT_INITIALIZATION_VECTOR("crypto:incorrect-initialization-vector", "The initialization vector is not correct");
4252

43-
private String code;
44-
private String message;
53+
private final String code;
54+
private final String message;
55+
@Nullable final Class<? extends Throwable>[] describesExceptions;
56+
57+
CryptoError(final String code, final String message) {
58+
this(code, message, null);
59+
}
4560

46-
CryptoError(String code, String message) {
61+
CryptoError(final String code, final String message, @Nullable final Class<? extends Throwable>... describesExceptions) {
4762
this.code = code;
4863
this.message = message;
64+
this.describesExceptions = describesExceptions;
4965
}
5066

5167
public String getCode() {
@@ -59,4 +75,22 @@ public String getMessage() {
5975
public String getDescription() {
6076
return this.code + ", " + this.message;
6177
}
78+
79+
public static @Nullable CryptoError describeException(@Nullable final Throwable t) {
80+
if (t == null) {
81+
return null;
82+
}
83+
84+
for (final CryptoError cryptoError : values()) {
85+
if (cryptoError.describesExceptions != null) {
86+
for (final Class<? extends Throwable> describesException : cryptoError.describesExceptions) {
87+
if (describesException == t.getClass()) {
88+
return cryptoError;
89+
}
90+
}
91+
}
92+
}
93+
94+
return null;
95+
}
6296
}

src/main/java/ro/kuberam/libs/java/crypto/CryptoException.java

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,37 @@
1919
*/
2020
package ro.kuberam.libs.java.crypto;
2121

22+
import javax.annotation.Nullable;
23+
2224
public class CryptoException extends Exception {
23-
/**
24-
*
25-
*/
2625
private static final long serialVersionUID = -2606956271206243301L;
27-
private CryptoError cryptoError;
26+
@Nullable private final CryptoError cryptoError;
2827

29-
public CryptoException(CryptoError cryptoError) {
28+
public CryptoException(final CryptoError cryptoError) {
3029
super(cryptoError.getDescription());
3130
this.cryptoError = cryptoError;
3231
}
3332

34-
public CryptoException(CryptoError cryptoError, Throwable cause) {
33+
public CryptoException(final CryptoError cryptoError, final Throwable cause) {
3534
super(cryptoError.getDescription(), cause);
3635
this.cryptoError = cryptoError;
3736
}
3837

39-
public static CryptoException fromCause(final Throwable cause) {
40-
final CryptoError cryptoError = CryptoError.valueOf(cause.getClass().getSimpleName());
41-
return new CryptoException(cryptoError, cause);
42-
}
38+
public CryptoException(final Throwable cause) {
39+
super(getDesc(cause), cause);
40+
this.cryptoError = CryptoError.describeException(cause);
41+
}
42+
43+
private static String getDesc(final Throwable cause) {
44+
final CryptoError cryptoError = CryptoError.describeException(cause);
45+
if (cryptoError != null) {
46+
return cryptoError.getDescription();
47+
} else {
48+
return cause.getMessage();
49+
}
50+
}
4351

52+
@Nullable
4453
public CryptoError getCryptoError() {
4554
return cryptoError;
4655
}

src/main/java/ro/kuberam/libs/java/crypto/Parameters.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public String getCanonicalizationAlgorithm() {
4242

4343
public void setCanonicalizationAlgorithm(final String canonicalizationAlgorithm) throws CryptoException {
4444
if (!contains(CANONICALIZATION_ALGORITHM_VALUES, canonicalizationAlgorithm)) {
45-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
45+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
4646
}
4747

4848
if (canonicalizationAlgorithm.equals("exclusive")) {
@@ -62,7 +62,7 @@ public String getDigestAlgorithm() {
6262

6363
public void setDigestAlgorithm(final String digestAlgorithm) throws CryptoException {
6464
if (!contains(DIGEST_ALGORITHM_VALUES, digestAlgorithm)) {
65-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
65+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
6666
}
6767

6868
if (digestAlgorithm.equals("SHA256")) {
@@ -80,7 +80,7 @@ public String getSignatureAlgorithm() {
8080

8181
public void setSignatureAlgorithm(final String signatureAlgorithm) throws CryptoException {
8282
if (!contains(SIGNATURE_ALGORITHM_VALUES, signatureAlgorithm)) {
83-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
83+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
8484
}
8585

8686
if (signatureAlgorithm.equals("DSA_SHA1")) {

src/main/java/ro/kuberam/libs/java/crypto/digest/Hash.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323
import java.io.InputStream;
2424
import java.nio.charset.StandardCharsets;
2525
import java.security.*;
26-
import java.util.Base64;
27-
import java.util.Optional;
26+
import java.util.*;
2827
import javax.annotation.Nullable;
2928

3029
import org.slf4j.Logger;
@@ -116,7 +115,7 @@ private static MessageDigest getMessageDigester(final String algorithm, @Nullabl
116115
return MessageDigest.getInstance(algorithm);
117116
}
118117
} catch (final NoSuchAlgorithmException e) {
119-
throw new CryptoException(CryptoError.NoSuchAlgorithmException, e);
118+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM, e);
120119
} catch (final NoSuchProviderException e) {
121120
throw new CryptoException(CryptoError.UNKNOWN_PROVIDER, e);
122121
}

src/main/java/ro/kuberam/libs/java/crypto/digest/Hmac.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public static byte[] hmac(final byte[] data, final byte[] secretKey, String algo
9898
return mac.doFinal(data);
9999

100100
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
101-
throw CryptoException.fromCause(e);
101+
throw new CryptoException(e);
102102
}
103103
}
104104

@@ -125,7 +125,7 @@ public static byte[] hmac(final InputStream data, final byte[] secretKey, String
125125
return mac.doFinal();
126126

127127
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
128-
throw CryptoException.fromCause(e);
128+
throw new CryptoException(e);
129129
}
130130
}
131131
}

src/main/java/ro/kuberam/libs/java/crypto/digitalSignature/GenerateXmlSignature.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ public static String generate(Document inputDoc, String mechanismType, String ca
103103
NodeList nodes = (NodeList) expr.evaluate(inputDoc, XPathConstants.NODESET);
104104
if (nodes.getLength() < 1) {
105105
// TODO this error message has to replaced
106-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
106+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
107107
}
108108

109109
// Node nodeToSign = nodes.item(0);
@@ -134,7 +134,7 @@ public static String generate(Document inputDoc, String mechanismType, String ca
134134
try {
135135
keyStore = KeyStore.getInstance(certificateDetails[0]);
136136
} catch (KeyStoreException e) {
137-
throw CryptoException.fromCause(e);
137+
throw new CryptoException(e);
138138
}
139139
keyStore.load(keyStoreInputStream, certificateDetails[1].toCharArray());
140140
String alias = certificateDetails[2];
@@ -219,14 +219,14 @@ public static String generate(Document inputDoc, String mechanismType, String ca
219219
return serializer.writeToString(sigParent);
220220
}
221221
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
222-
throw new CryptoException(CryptoError.NoSuchAlgorithmException, e);
222+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM, e);
223223
} catch (CertificateException e) {
224224
// TODO error code needs improving
225-
throw new CryptoException(CryptoError.InvalidKeySpecException, e);
225+
throw new CryptoException(CryptoError.INVALID_CRYPTO_KEY, e);
226226
} catch (KeyStoreException e) {
227227
throw new CryptoException(CryptoError.UNREADABLE_KEYSTORE, e);
228228
} catch (UnrecoverableKeyException | KeyException e) {
229-
throw new CryptoException(CryptoError.InvalidKeySpecException, e);
229+
throw new CryptoException(CryptoError.INVALID_CRYPTO_KEY, e);
230230
} catch (ParserConfigurationException | XPathExpressionException | MarshalException e) {
231231
throw new IOException(e);
232232
}
@@ -268,7 +268,7 @@ private static String getCanonicalizationAlgorithmUri(String canonicalizationAlg
268268
return CanonicalizationMethod.INCLUSIVE;
269269

270270
default:
271-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
271+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
272272
}
273273
}
274274

@@ -285,7 +285,7 @@ private static String getDigestAlgorithmURI(String digestAlgorithm) throws Crypt
285285
return DigestMethod.SHA1;
286286

287287
default:
288-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
288+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
289289
}
290290
}
291291

@@ -299,7 +299,7 @@ private static String getSignatureAlgorithmURI(String signatureAlgorithm) throws
299299
return SignatureMethod.RSA_SHA1;
300300

301301
default:
302-
throw new CryptoException(CryptoError.NoSuchAlgorithmException);
302+
throw new CryptoException(CryptoError.UNKNOWN_ALGORITHM);
303303
}
304304
}
305305
}

src/main/java/ro/kuberam/libs/java/crypto/encrypt/AsymmetricEncryption.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public static String encryptString(String data, Key key, String transformationNa
6666
resultBytes = cipher.doFinal(dataBytes);
6767
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException
6868
| InvalidKeyException e) {
69-
throw CryptoException.fromCause(e);
69+
throw new CryptoException(e);
7070
} catch (Exception e) {
7171
e.printStackTrace();
7272
}
@@ -93,7 +93,7 @@ public static String decryptString(String encryptedData, PrivateKey privateKey,
9393
resultBytes = cipher.doFinal(dataBytes);
9494
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException
9595
| InvalidKeyException e) {
96-
throw CryptoException.fromCause(e);
96+
throw new CryptoException(e);
9797
} catch (Exception e) {
9898
e.printStackTrace();
9999
}
@@ -120,7 +120,7 @@ public static String encryptBinary(InputStream data, String base64PublicKey, Str
120120
resultBytes = cipher.doFinal();
121121
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException
122122
| InvalidKeyException e) {
123-
throw CryptoException.fromCause(e);
123+
throw new CryptoException(e);
124124
} catch (Exception e) {
125125
e.printStackTrace();
126126
}
@@ -147,7 +147,7 @@ public static String decryptBinary(InputStream data, String base64PrivateKey, St
147147
resultBytes = cipher.doFinal();
148148
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException
149149
| InvalidKeyException e) {
150-
throw CryptoException.fromCause(e);
150+
throw new CryptoException(e);
151151
} catch (Exception e) {
152152
e.printStackTrace();
153153
}

src/main/java/ro/kuberam/libs/java/crypto/encrypt/SymmetricEncryption.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public static byte[] operation(byte[] input, String secretKey, String transforma
6666
try {
6767
cipher = Cipher.getInstance(transformationName, actualProvider);
6868
} catch (NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException e) {
69-
throw CryptoException.fromCause(e);
69+
throw new CryptoException(e);
7070
}
7171

7272
SecretKeySpec skeySpec = generateSecretKey(secretKey, algorithm);
@@ -75,20 +75,20 @@ public static byte[] operation(byte[] input, String secretKey, String transforma
7575
try {
7676
cipher.init(operationType, skeySpec, ivSpec);
7777
} catch (InvalidAlgorithmParameterException | InvalidKeyException e) {
78-
throw CryptoException.fromCause(e);
78+
throw new CryptoException(e);
7979
}
8080
} else {
8181
try {
8282
cipher.init(operationType, skeySpec);
8383
} catch (InvalidKeyException e) {
84-
throw new CryptoException(CryptoError.InvalidKeySpecException, e);
84+
throw new CryptoException(CryptoError.INVALID_CRYPTO_KEY, e);
8585
}
8686
}
8787

8888
try {
8989
result = cipher.doFinal(input);
9090
} catch (IllegalBlockSizeException | BadPaddingException e) {
91-
throw CryptoException.fromCause(e);
91+
throw new CryptoException(e);
9292
}
9393

9494
return result;

src/test/java/ro/kuberam/libs/java/crypto/ParametersTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public void testCanonicalizationAlgorithmWrongValue() {
3434
parameters.setCanonicalizationAlgorithm("inclusive-with-commentss");
3535
fail("Algorithm should have been unknown");
3636
} catch (CryptoException e) {
37-
assertEquals(CryptoError.NoSuchAlgorithmException, e.getCryptoError());
37+
assertEquals(CryptoError.UNKNOWN_ALGORITHM, e.getCryptoError());
3838
}
3939
}
4040

@@ -52,7 +52,7 @@ public void testDigestAlgorithmWrongValue() {
5252
parameters.setDigestAlgorithm("SHA1008");
5353
fail("Algorithm should have been unknown");
5454
} catch (CryptoException e) {
55-
assertEquals(CryptoError.NoSuchAlgorithmException, e.getCryptoError());
55+
assertEquals(CryptoError.UNKNOWN_ALGORITHM, e.getCryptoError());
5656
}
5757
}
5858

@@ -71,7 +71,7 @@ public void testSignatureAlgorithmWrongValue() {
7171
parameters.setSignatureAlgorithm("RSA_SHA1008");
7272
fail("Algorithm should have been unknown");
7373
} catch (CryptoException e) {
74-
assertEquals(CryptoError.NoSuchAlgorithmException, e.getCryptoError());
74+
assertEquals(CryptoError.UNKNOWN_ALGORITHM, e.getCryptoError());
7575
}
7676
}
7777

src/test/java/ro/kuberam/libs/java/crypto/digest/HashBinaryTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ public void hashBinary() throws IOException, CryptoException {
7373
try (final InputStream input = getClass().getResourceAsStream("../keystore.ks")) {
7474
assertNotNull(input);
7575

76-
final String result = Hash.hashBinary(input, algorithm, format);
76+
final String result = Hash.hashBinary(input, algorithm, null, format);
7777
assertEquals(expected, result);
7878
}
7979
}

0 commit comments

Comments
 (0)