1919import java .io .File ;
2020import java .io .FileReader ;
2121import java .io .IOException ;
22+ import java .lang .reflect .Field ;
2223import java .security .KeyException ;
2324import java .security .PrivateKey ;
25+ import java .util .HashMap ;
26+ import java .util .function .Function ;
2427
2528import org .bouncycastle .asn1 .ASN1ObjectIdentifier ;
2629import org .bouncycastle .asn1 .pkcs .PrivateKeyInfo ;
3639import org .bouncycastle .operator .OperatorCreationException ;
3740import org .bouncycastle .pkcs .PKCS8EncryptedPrivateKeyInfo ;
3841import org .bouncycastle .pkcs .PKCSException ;
42+ import sun .misc .Unsafe ;
3943
4044/**
4145 * Helper class for loading private keys (PVK or PEM, encrypted or not).
@@ -72,6 +76,36 @@ public static PrivateKey load(File file, String password) throws KeyException {
7276 throw new IllegalArgumentException ("Unsupported private key format (PEM or PVK file expected" );
7377 }
7478
79+ /**
80+ * Disables the signature verification of the jar containing the BouncyCastle provider.
81+ */
82+ private static void disableJceSecurity () {
83+ try {
84+ Class <?> jceSecurityClass = Class .forName ("javax.crypto.JceSecurity" );
85+ Field field = jceSecurityClass .getDeclaredField ("verificationResults" );
86+ field .setAccessible (true );
87+
88+ Field unsafeField = Unsafe .class .getDeclaredField ("theUnsafe" );
89+ unsafeField .setAccessible (true );
90+ Unsafe unsafe = (Unsafe ) unsafeField .get (null );
91+
92+ unsafe .putObject (unsafe .staticFieldBase (field ), unsafe .staticFieldOffset (field ), new HashMap <Object , Boolean >() {
93+ @ Override
94+ public Boolean get (Object key ) {
95+ // This is not the provider you are looking for, you don't need to see its identification, move along
96+ return Boolean .TRUE ;
97+ }
98+
99+ @ Override
100+ public Boolean computeIfAbsent (Object key , Function <? super Object , ? extends Boolean > mappingFunction ) {
101+ return super .computeIfAbsent (key , object -> Boolean .TRUE );
102+ }
103+ });
104+ } catch (Exception e ) {
105+ e .printStackTrace ();
106+ }
107+ }
108+
75109 private static PrivateKey readPrivateKeyPEM (File file , char [] password ) throws IOException , OperatorCreationException , PKCSException {
76110 try (FileReader reader = new FileReader (file )) {
77111 PEMParser parser = new PEMParser (reader );
@@ -84,7 +118,11 @@ private static PrivateKey readPrivateKeyPEM(File file, char[] password) throws I
84118 if (object == null ) {
85119 throw new IllegalArgumentException ("No key found in " + file );
86120 }
87-
121+
122+ if (BouncyCastleProvider .class .getName ().startsWith ("net.jsign" )) {
123+ // disable JceSecurity to allow the use of the repackaged BouncyCastle provider
124+ disableJceSecurity ();
125+ }
88126 BouncyCastleProvider provider = new BouncyCastleProvider ();
89127 JcaPEMKeyConverter converter = new JcaPEMKeyConverter ().setProvider (provider );
90128
0 commit comments