1
2
3
4 package org.rcfaces.core.internal.util;
5
6 import java.security.MessageDigest;
7 import java.security.NoSuchAlgorithmException;
8 import java.util.Arrays;
9 import java.util.HashSet;
10 import java.util.Set;
11
12 import javax.faces.FacesException;
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16
17
18
19
20
21
22 public class MessageDigestSelector {
23
24 private static final Log LOG = LogFactory
25 .getLog(MessageDigestSelector.class);
26
27 private static final Set notSupported = new HashSet(32);
28
29 private static final Set supported = new HashSet(32);
30
31 public static MessageDigest getInstance(String[] algorithmNames) {
32 String algorithmName = null;
33
34 synchronized (notSupported) {
35 for (int i = 0; i < algorithmNames.length; i++) {
36 algorithmName = algorithmNames[i];
37
38 if (algorithmName == null || algorithmName.length() == 0) {
39 continue;
40 }
41
42 algorithmName = algorithmName.trim();
43
44 if (notSupported.contains(algorithmName)) {
45 if (LOG.isTraceEnabled()) {
46 LOG.trace("Algorithm '" + algorithmName
47 + "' is marked disabled.");
48
49 }
50 continue;
51 }
52
53 if (supported.contains(algorithmName)) {
54 if (LOG.isTraceEnabled()) {
55 LOG.trace("Algorithm '" + algorithmName
56 + "' is marked enabled.");
57
58 }
59 break;
60 }
61
62 MessageDigest messageDigest;
63 try {
64 messageDigest = MessageDigest.getInstance(algorithmName);
65
66 } catch (NoSuchAlgorithmException e) {
67 LOG.debug("Message digest '" + algorithmName
68 + "' throws exception", e);
69
70 messageDigest = null;
71 }
72
73 if (messageDigest != null) {
74 supported.add(algorithmName);
75
76 LOG
77 .debug("Mark algorithm '" + algorithmName
78 + "' enabled.");
79
80 return messageDigest;
81 }
82
83 notSupported.add(algorithmName);
84
85 LOG.debug("Mark algorithm '" + algorithmName + "' disabled.");
86 }
87 }
88
89 if (algorithmName != null) {
90 if (LOG.isTraceEnabled()) {
91 LOG.trace("Try algorithm '" + algorithmName + "' ...");
92 }
93
94 try {
95 MessageDigest messageDigest = MessageDigest
96 .getInstance(algorithmName);
97
98 if (messageDigest != null) {
99 return messageDigest;
100 }
101
102 } catch (NoSuchAlgorithmException e) {
103 LOG.error("Message digest '" + algorithmName
104 + "' throws exception", e);
105 }
106 }
107
108 throw new FacesException("Can not find valid algorithm in '"
109 + Arrays.asList(algorithmNames) + "'");
110 }
111 }