1 package org.apache.fulcrum.yaafi.framework.crypto;
2
3 import java.io.InputStream;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import org.apache.fulcrum.yaafi.framework.reflection.Clazz;
25
26
27
28
29
30
31
32
33
34
35 public class CryptoStreamFactory {
36
37 private static boolean isInitialized;
38
39
40 private static Object cryptoStreamFactory;
41
42
43 private static String className = "org.apache.fulcrum.jce.crypto.CryptoStreamFactoryImpl";
44
45
46
47
48
49
50
51
52
53 public static InputStream getDecryptingInputStream(InputStream is, String isEncrypted) throws Exception {
54 InputStream result;
55
56 if (isEncrypted.equalsIgnoreCase("true")) {
57
58 result = createDecryptingInputStream(is, "getInputStream");
59 } else if (isEncrypted.equalsIgnoreCase("auto") && hasCryptoStreamFactory()) {
60
61 result = createDecryptingInputStream(is, "getSmartInputStream");
62 } else if (isEncrypted.equalsIgnoreCase("auto") && !hasCryptoStreamFactory()) {
63
64 result = is;
65 } else if (isEncrypted.equalsIgnoreCase("false")) {
66
67 result = is;
68 } else {
69 throw new IllegalArgumentException("Unknown decryption mode : " + isEncrypted);
70 }
71
72 return result;
73 }
74
75
76
77
78
79
80
81
82
83 private static InputStream createDecryptingInputStream(InputStream is, String factoryMethodName) throws Exception {
84 Class[] signature = { InputStream.class };
85 Object[] args = { is };
86 Object cryptoStreamFactory = getCryptoStreamFactory();
87
88 if (cryptoStreamFactory == null) {
89 throw new IllegalStateException(
90 "No CryptoStreamFactory available - unable to create a decrypting input stream");
91 } else {
92 return (InputStream) Clazz.invoke(cryptoStreamFactory, factoryMethodName, signature, args);
93 }
94 }
95
96
97
98
99
100
101
102 private synchronized static Object getCryptoStreamFactory() throws Exception {
103 if (!isInitialized) {
104 isInitialized = true;
105 ClassLoader clazzLoader = CryptoStreamFactory.class.getClassLoader();
106
107 if (Clazz.hasClazz(clazzLoader, className)) {
108 Class[] signature = {};
109 Object[] args = {};
110 Class<?> clazz = Clazz.getClazz(clazzLoader, className);
111 cryptoStreamFactory = Clazz.newInstance(clazz, signature, args);
112 }
113 }
114
115 return cryptoStreamFactory;
116 }
117
118
119
120
121
122 private static boolean hasCryptoStreamFactory() throws Exception {
123 return getCryptoStreamFactory() != null;
124 }
125 }