1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package davmail.http;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.InputStream;
23 import java.lang.reflect.Constructor;
24 import java.lang.reflect.Method;
25 import java.nio.charset.StandardCharsets;
26 import java.security.Provider;
27 import java.security.Security;
28
29
30
31
32 public final class SunPKCS11ProviderHandler {
33
34 private SunPKCS11ProviderHandler() {
35 }
36
37
38
39
40
41
42 public static void registerProvider(String pkcs11Config) {
43 Provider p;
44
45 try {
46 Class sunPkcs11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
47 @SuppressWarnings("unchecked") Constructor sunPkcs11Constructor = sunPkcs11Class.getDeclaredConstructor(InputStream.class);
48 p = (Provider) sunPkcs11Constructor.newInstance(new ByteArrayInputStream(pkcs11Config.getBytes(StandardCharsets.UTF_8)));
49 } catch (NoSuchMethodException e) {
50
51 p = configurePkcs11Provider(pkcs11Config);
52 } catch (Exception e) {
53 StringBuilder errorMessage = new StringBuilder("Unable to configure SunPKCS11 provider");
54 Throwable cause = e.getCause();
55 while (cause != null) {
56 errorMessage.append(" ").append(cause.getMessage());
57 cause = cause.getCause();
58 }
59 throw new RuntimeException(errorMessage.toString());
60 }
61
62 Security.addProvider(p);
63 }
64
65 private static Provider configurePkcs11Provider(String pkcs11Config) {
66 Provider p;
67 try {
68 p = Security.getProvider("SunPKCS11");
69
70
71 Method configureMethod = Provider.class.getDeclaredMethod("configure", String.class);
72 configureMethod.invoke(p, "--"+pkcs11Config);
73 } catch (Exception e) {
74 StringBuilder errorMessage = new StringBuilder("Unable to configure SunPKCS11 provider");
75 Throwable cause = e.getCause();
76 while (cause != null) {
77 errorMessage.append(" ").append(cause.getMessage());
78 cause = cause.getCause();
79 }
80 throw new RuntimeException(errorMessage.toString());
81 }
82 return p;
83 }
84
85 }