1 /*
2  * Copyright (C) 2014 jsonwebtoken.io
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package io.jsonwebtoken.lang;
17
18 import java.security.Provider;
19 import java.security.Security;
20 import java.util.concurrent.atomic.AtomicBoolean;
21
22 public final class RuntimeEnvironment {
23
24     private static final RuntimeEnvironment INSTANCE = new RuntimeEnvironment();
25
26     private RuntimeEnvironment(){}
27
28     private static final String BC_PROVIDER_CLASS_NAME = "org.bouncycastle.jce.provider.BouncyCastleProvider";
29
30     private static final AtomicBoolean bcLoaded = new AtomicBoolean(false);
31
32     public static final boolean BOUNCY_CASTLE_AVAILABLE = Classes.isAvailable(BC_PROVIDER_CLASS_NAME);
33
34     public static void enableBouncyCastleIfPossible() {
35
36         if (bcLoaded.get()) {
37             return;
38         }
39
40         try {
41             Class clazz = Classes.forName(BC_PROVIDER_CLASS_NAME);
42
43             //check to see if the user has already registered the BC provider:
44
45             Provider[] providers = Security.getProviders();
46
47             for(Provider provider : providers) {
48                 if (clazz.isInstance(provider)) {
49                     bcLoaded.set(true);
50                     return;
51                 }
52             }
53
54             //bc provider not enabled - add it:
55             Security.addProvider((Provider)Classes.newInstance(clazz));
56             bcLoaded.set(true);
57
58         } catch (UnknownClassException e) {
59             //not available
60         }
61     }
62
63     static {
64         enableBouncyCastleIfPossible();
65     }
66
67 }
68