Java Code Examples for java.security.Security#removeProvider()

The following examples show how to use java.security.Security#removeProvider() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonWebKeyTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncryptDecryptPrivateKey() throws Exception {
    final String password = "Thus from my lips, by yours, my sin is purged.";
    final String key = "{\"kty\":\"oct\","
        + "\"alg\":\"A128KW\","
        + "\"k\":\"GawgguFyGrWKav7AX4VKUg\","
        + "\"kid\":\"AesWrapKey\"}";
    Security.addProvider(new BouncyCastleProvider());
    try {
        JsonWebKey jwk = readKey(key);
        validateSecretAesKey(jwk);
        String encryptedKey = JwkUtils.encryptJwkKey(jwk, password.toCharArray());
        JweCompactConsumer c = new JweCompactConsumer(encryptedKey);
        assertEquals("jwk+json", c.getJweHeaders().getContentType());
        assertEquals(KeyAlgorithm.PBES2_HS256_A128KW, c.getJweHeaders().getKeyEncryptionAlgorithm());
        assertEquals(ContentAlgorithm.A128CBC_HS256, c.getJweHeaders().getContentEncryptionAlgorithm());
        assertNotNull(c.getJweHeaders().getHeader("p2s"));
        assertNotNull(c.getJweHeaders().getHeader("p2c"));
        jwk = JwkUtils.decryptJwkKey(encryptedKey, password.toCharArray());
        validateSecretAesKey(jwk);
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 2
Source File: CipherTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testCipher_init_CallsInitWithParams_AlgorithmParameterSpec() throws Exception {
    Provider mockProviderRejects = new MockProvider("MockProviderRejects") {
        public void setup() {
            put("Cipher.FOO",
                    MockCipherSpi.MustInitWithAlgorithmParameterSpec_RejectsAll.class.getName());
            put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());
        }
    };
    Provider mockProviderAccepts = new MockProvider("MockProviderAccepts") {
        public void setup() {
            put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
            put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());
        }
    };

    Security.addProvider(mockProviderRejects);
    Security.addProvider(mockProviderAccepts);
    try {
        Cipher c = Cipher.getInstance("FOO");
        c.init(Cipher.ENCRYPT_MODE, new MockKey(), new IvParameterSpec(new byte[12]));
        assertEquals(mockProviderAccepts, c.getProvider());
    } finally {
        Security.removeProvider(mockProviderRejects.getName());
        Security.removeProvider(mockProviderAccepts.getName());
    }
}
 
Example 3
Source File: CipherTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testCipher_getInstance_CorrectPriority_AlgorithmOnlyFirst() throws Exception {
    Provider mockProviderOnlyAlgorithm = new MockProvider("MockProviderOnlyAlgorithm") {
        public void setup() {
            put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
        }
    };
    Provider mockProviderFullTransformSpecified = new MockProvider("MockProviderFull") {
        public void setup() {
            put("Cipher.FOO/FOO/FOO", MockCipherSpi.AllKeyTypes.class.getName());
        }
    };

    Security.addProvider(mockProviderOnlyAlgorithm);
    Security.addProvider(mockProviderFullTransformSpecified);
    try {
        Cipher c = Cipher.getInstance("FOO/FOO/FOO");
        assertEquals(mockProviderOnlyAlgorithm, c.getProvider());
    } finally {
        Security.removeProvider(mockProviderOnlyAlgorithm.getName());
        Security.removeProvider(mockProviderFullTransformSpecified.getName());
    }
}
 
Example 4
Source File: Provider2Test.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_getAlias() throws Exception {
    MockProvider mockProvider = new MockProvider("MOCKNAME", 1.0,
            "MOCKINFO");
    Provider.Service service = new Provider.Service(mockProvider,
            "MOCKTYPE", "MOCKALGORITHM", "TESTCLASSNAME", null, null);
    mockProvider.putService(service);
    Security.addProvider(mockProvider);
    try {
        MessageDigest messageDigest = MessageDigest
                .getInstance("NOTEXISTS");
    }

    catch (NoSuchAlgorithmException e) {
        // expected
    } finally {
        Security.removeProvider("MOCKNAME");
    }
}
 
Example 5
Source File: CipherTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Several exceptions can be thrown by init. Check that in this case we throw the right one,
 * as the error could fall under the umbrella of other exceptions.
 * http://b/18987633
 */
public void testCipher_init_DoesNotSupportKeyClass_throwsInvalidKeyException()
        throws Exception {
    Provider mockProvider = new MockProvider("MockProvider") {
        public void setup() {
            put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
            put("Cipher.FOO SupportedKeyClasses", "none");
        }
    };

    Security.addProvider(mockProvider);
    try {
        Cipher c = Cipher.getInstance("FOO");
        c.init(Cipher.DECRYPT_MODE, new MockKey());
        fail("Expected InvalidKeyException");
    } catch (InvalidKeyException expected) {
    } finally {
        Security.removeProvider(mockProvider.getName());
    }
}
 
Example 6
Source File: JsonWebKeyTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncryptDecryptPrivateSet() throws Exception {
    final String password = "Thus from my lips, by yours, my sin is purged.";
    Security.addProvider(new BouncyCastleProvider());
    try {
        JsonWebKeys jwks = readKeySet("jwkPrivateSet.txt");
        validatePrivateSet(jwks);
        String encryptedKeySet = JwkUtils.encryptJwkSet(jwks, password.toCharArray());
        JweCompactConsumer c = new JweCompactConsumer(encryptedKeySet);
        assertEquals("jwk-set+json", c.getJweHeaders().getContentType());
        assertEquals(KeyAlgorithm.PBES2_HS256_A128KW, c.getJweHeaders().getKeyEncryptionAlgorithm());
        assertEquals(ContentAlgorithm.A128CBC_HS256, c.getJweHeaders().getContentEncryptionAlgorithm());
        assertNotNull(c.getJweHeaders().getHeader("p2s"));
        assertNotNull(c.getJweHeaders().getHeader("p2c"));
        jwks = JwkUtils.decryptJwkSet(encryptedKeySet, password.toCharArray());
        validatePrivateSet(jwks);
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 7
Source File: NetconfControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
@Deactivate
public void deactivate() {
    netconfDeviceMap.values().forEach(device -> {
        if (device.isMasterSession()) {
            try {
                device.getSession().removeDeviceOutputListener(downListener);
            } catch (NetconfException e) {
                log.error("removeDeviceOutputListener Failed {}", e.getMessage());
            }
        }
        device.disconnect();
    });
    clusterCommunicator.removeSubscriber(SEND_REQUEST_SUBJECT_STRING);
    clusterCommunicator.removeSubscriber(SEND_REQUEST_SUBJECT_SET_STRING);
    clusterCommunicator.removeSubscriber(SEND_REPLY_SUBJECT_STRING);
    clusterCommunicator.removeSubscriber(SEND_REPLY_SUBJECT_SET_STRING);
    cfgService.unregisterProperties(getClass(), false);
    netconfDeviceListeners.clear();
    netconfDeviceMap.clear();
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    log.info("Stopped");
}
 
Example 8
Source File: SslUtils.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Registers Bouncy Castle (BC) as <em>first security provider</em> before any other providers 
 * coming with the Java runtime. This is done once, if not already applied.
 * <br>ATS calls this method internally when it is supposed to be needed.
 * 
 * <br><br><b>Note:</b> This is a static operation. All working threads will be affected.
 * The method itself is not thread-safe.
 * 
 * <br><br><b>Note:</b> Effective set of provider is done only once per Java runtime.
 *   Currently subsequent invocations do not check whether provider is removed meanwhile and 
 *   this way could be forcefully set other security provider.  
 */
public static void registerBCProvider() {

    if (bcProviderAlreadyRegisteredAsFirst) {
        return; // do nothing. Provider is already registered as first one.
    }

    boolean needToInsert = true;
    boolean needToRemove = false;

    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
        if (providers[i].getName().equalsIgnoreCase(BouncyCastleProvider.PROVIDER_NAME)) {
            if (i == 0) {
                needToInsert = false;
            } else {
                needToRemove = true;
            }
            break;
        }
    }

    if (needToInsert) {
        if (needToRemove) {
            Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
        }
        Provider bcProvider = new BouncyCastleProvider();
        Security.insertProviderAt(bcProvider, 1);
        bcProviderAlreadyRegisteredAsFirst = true;
        log.info("Bouncy Castle security provider is registered as first in the list of available providers");

        origKeystoreType = Security.getProperty("keystore.type");

        Security.setProperty("keystore.type", "jks");
        log.info("Default keystore type set to: JKS");
    }
}
 
Example 9
Source File: Providers.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void setAt(Provider p, int pos) throws Exception {
    if (Security.getProvider(p.getName()) != null) {
        Security.removeProvider(p.getName());
    }
    if (Security.insertProviderAt(p, pos) == -1) {
        throw new Exception("cannot setAt");
    }
}
 
Example 10
Source File: SignatureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private Signature getTestSignature() throws NoSuchAlgorithmException {
    Provider provider = new MyProvider("TestProvider", 1.0, "Test Provider", "Signature.ABC", MySignature.class.getName());
    Security.insertProviderAt(provider, 1);

    try {
        return Signature.getInstance("ABC");
    }
    finally {
       Security.removeProvider("TestProvider");
    }

}
 
Example 11
Source File: GenerationTests.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void removePKCS11Provider() throws Exception {
    secondChanceGranted = true;
    Security.removeProvider("SunPKCS11-Solaris");
    System.out.println("Second chance granted. Provider list: "
            + Arrays.toString(Security.getProviders()));
    setup();
}
 
Example 12
Source File: PGPPipe.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws ConfigurationException {
	super.configure();
	if (action == null)
		throw new ConfigurationException("Action can not be null!");

	if(Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) != null)
		Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);

	Security.addProvider(new BouncyCastleProvider());

	switch (action.toLowerCase()) {
		case "encrypt":
			pgpAction = new Encrypt(publicKeys, recipients);
			break;
		case "decrypt":
			pgpAction = new Decrypt(secretKey, secretPassword);
			break;
		case "sign":
			if(verificationAddresses == null || verificationAddresses.length == 0)
				throw new ConfigurationException("During signing action, senders has to be set.");
			pgpAction = new Sign(publicKeys, secretKey, secretPassword, recipients, verificationAddresses[0]);
			break;
		case "verify":
			pgpAction = new Verify(publicKeys, secretKey, secretPassword, verificationAddresses);
			break;
		default:
			throw new ConfigurationException("Unknown action. Action has to be set to one of [Encrypt, Decrypt, Sign, Verify]");
	}
	pgpAction.configure();
}
 
Example 13
Source File: GenerationTests.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void removePKCS11Provider() throws Exception {
    secondChanceGranted = true;
    Security.removeProvider("SunPKCS11-Solaris");
    System.out.println("Second chance granted. Provider list: "
            + Arrays.toString(Security.getProviders()));
    setup();
}
 
Example 14
Source File: GenerationTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void removePKCS11Provider() throws Exception {
    secondChanceGranted = true;
    Security.removeProvider("SunPKCS11-Solaris");
    System.out.println("Second chance granted. Provider list: "
            + Arrays.toString(Security.getProviders()));
    setup();
}
 
Example 15
Source File: AbstractBCTestCRLUtils.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@AfterAll
public static void reset() {
	Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
 
Example 16
Source File: CertificateFactory2Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
protected void tearDown() throws Exception {
    super.tearDown();
    Security.removeProvider(mProv.getName());
}
 
Example 17
Source File: CertStore2Test.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
protected void tearDown() throws Exception {
    super.tearDown();
    Security.removeProvider(CERT_STORE_PROVIDER_NAME);
}
 
Example 18
Source File: TestAESWithProviderChange.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String argv[]) throws Exception {
    Security.removeProvider(SUNJCE);
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    new TestAESWithProviderChange().run(argv);
}
 
Example 19
Source File: SFTPService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
private void removeSecurityProvider() {
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}
 
Example 20
Source File: JweJsonProducerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void unregisterBouncyCastleIfNeeded() throws Exception {
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}