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

The following examples show how to use java.security.Security#addProvider() . 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: SecurityUtility.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Get Bouncy Castle provider from classpath, and call Security.addProvider.
 * Throw Exception if failed.
 */
public static Provider getBCProviderFromClassPath() throws Exception {
    Class clazz;
    try {
        // prefer non FIPS, for backward compatibility concern.
        clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS);
    } catch (ClassNotFoundException cnf) {
        log.warn("Not able to get Bouncy Castle provider: {}, try to get FIPS provider {}",
                BC_NON_FIPS_PROVIDER_CLASS, BC_FIPS_PROVIDER_CLASS);
        // attempt to use the FIPS provider.
        clazz = Class.forName(BC_FIPS_PROVIDER_CLASS);
    }

    Provider provider = (Provider) clazz.newInstance();
    Security.addProvider(provider);
    if (log.isDebugEnabled()) {
        log.debug("Found and Instantiated Bouncy Castle provider in classpath {}", provider.getName());
    }
    return provider;
}
 
Example 2
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testJwsPsSha() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    try {
        JwsHeaders outHeaders = new JwsHeaders();
        outHeaders.setSignatureAlgorithm(SignatureAlgorithm.PS256);
        JwsCompactProducer producer = initSpecJwtTokenWriter(outHeaders);
        PrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED, RSA_PRIVATE_EXPONENT_ENCODED);
        String signed = producer.signWith(
            new PrivateKeyJwsSignatureProvider(privateKey, SignatureAlgorithm.PS256));

        JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(signed);
        RSAPublicKey key = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED, RSA_PUBLIC_EXPONENT_ENCODED);
        assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key, SignatureAlgorithm.PS256)));
        JwtToken token = jws.getJwtToken();
        JwsHeaders inHeaders = new JwsHeaders(token.getJwsHeaders());
        assertEquals(SignatureAlgorithm.PS256,
                     inHeaders.getSignatureAlgorithm());
        validateSpecClaim(token.getClaims());
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 3
Source File: EncrypAES.java    From ProjectStudy with MIT License 5 votes vote down vote up
public EncrypAES() throws NoSuchAlgorithmException, NoSuchPaddingException {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    // 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
    keygen = KeyGenerator.getInstance("AES");
    keygen.init(128, new SecureRandom(KEY));
    // 生成密钥
    deskey = keygen.generateKey();
    System.out.println();
    // 生成Cipher对象,指定其支持的AES算法
    c = Cipher.getInstance("AES");
}
 
Example 4
Source File: ToolSHA2.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * SHA-224加密
 *
 * @param data
 *         待加密数据
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeSHA224(byte[] data) throws NoSuchAlgorithmException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化MessageDigest
    MessageDigest md = MessageDigest.getInstance("SHA-224");

    // 执行消息摘要
    return md.digest(data);
}
 
Example 5
Source File: DESTest.java    From java_security with MIT License 5 votes vote down vote up
public static void bcDES()
{
	try 
	{
		Security.addProvider(new BouncyCastleProvider());
		
		// 生成KEY
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES", "BC");
		keyGenerator.getProvider();
		keyGenerator.init(56);
		// 产生密钥
		SecretKey secretKey = keyGenerator.generateKey();
		// 获取密钥
		byte[] bytesKey = secretKey.getEncoded();
		
		
		// KEY转换
		DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
		SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
		Key convertSecretKey = factory.generateSecret(desKeySpec);
		
		
		// 加密
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
		byte[] result = cipher.doFinal(src.getBytes());
		System.out.println("bc des encrypt:" + Hex.encodeHexString(result));
		
		// 解密
		cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
		result = cipher.doFinal(result);
		System.out.println("bc des decrypt:" + new String(result));
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 6
Source File: TestTLS12.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void initialize() throws Exception {
    if (initSecmod() == false) {
        return;
    }
    String configName = BASE + SEP + "fips.cfg";
    sunPKCS11NSSProvider = getSunPKCS11(configName);
    System.out.println("SunPKCS11 provider: " + sunPKCS11NSSProvider);
    Security.addProvider(sunPKCS11NSSProvider);

    sunJCEProvider = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunJCEProvider);

    Security.removeProvider("SunJSSE");
    jsseProvider =new com.sun.net.ssl.internal.ssl.Provider(
            sunPKCS11NSSProvider);
    Security.addProvider(jsseProvider);
    System.out.println(jsseProvider.getInfo());

    ks = KeyStore.getInstance("PKCS11", sunPKCS11NSSProvider);
    ks.load(null, "test12".toCharArray());
    ts = ks;

    KeyStore ksPlain = readTestKeyStore();
    privateKey = (RSAPrivateKey)ksPlain.getKey("rh_rsa_sha256",
            passphrase);
    publicKey = (RSAPublicKey)ksPlain.getCertificate(
            "rh_rsa_sha256").getPublicKey();
}
 
Example 7
Source File: ConfigurationModuleSecurityProvider.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addSecurityProviders(Configuration config) {
   String action = config.getProperty("org.taktik.connector.technical.config.impl.ConfigurationModuleSecurityProvider.add.securityproviders.activated");
   if (StringUtils.isEmpty(action)) {
      Security.addProvider(new BouncyCastleProvider());

      try {
         Security.addProvider(this.instantiate("be.fedict.commons.eid.jca.BeIDProvider"));
      } catch (SilentInstantiationException var9) {
         LOG.warn("Unable to load:" + var9.getCause().getMessage());
      }
   } else if ("true".equalsIgnoreCase(action)) {
      try {
         ConfigurableFactoryHelper<Provider> helper = new ConfigurableFactoryHelper("org.taktik.connector.technical.config.impl.ConfigurationModuleSecurityProvider.add.securityproviders", (String)null);
         List<Provider> providerList = helper.getImplementations();
         String position = config.getProperty("org.taktik.connector.technical.config.impl.ConfigurationModuleSecurityProvider.add.securityproviders.insertProviderAt", "end");
         Iterator i$ = providerList.iterator();

         while(i$.hasNext()) {
            Provider provider = (Provider)i$.next();
            this.removeSecurityProvider(provider.getName());
            if ("end".equals(position)) {
               LOG.debug("Inserting provider " + provider.getName());
               Security.addProvider(provider);
            } else if ("begin".equals(position)) {
               LOG.debug("Inserting provider " + provider.getName() + " at position 1.");
               Security.insertProviderAt(provider, 1);
            } else if (StringUtils.isNumeric(position)) {
               Integer positionId = Integer.parseInt(position);
               LOG.debug("Inserting provider " + provider.getName() + " at position " + positionId + ".");
               Security.insertProviderAt(provider, positionId);
            } else {
               LOG.warn("Unsupported position value [" + position + "]");
            }
         }
      } catch (TechnicalConnectorException var10) {
         LOG.error(var10.getClass().getSimpleName() + ": " + var10.getMessage(), var10);
      }
   }

}
 
Example 8
Source File: Teku.java    From teku with Apache License 2.0 5 votes vote down vote up
public static void main(final String... args) {
  Thread.setDefaultUncaughtExceptionHandler(new TekuDefaultExceptionHandler());
  Security.addProvider(new BouncyCastleProvider());
  final PrintWriter outputWriter = new PrintWriter(System.out, true, UTF_8);
  final PrintWriter errorWriter = new PrintWriter(System.err, true, UTF_8);
  final int result =
      new BeaconNodeCommand(outputWriter, errorWriter, System.getenv(), Teku::start).parse(args);
  if (result != 0) {
    System.exit(result);
  }
}
 
Example 9
Source File: DynamoDbEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private EncryptionMaterialsProvider getMaterialProviderwithECDSA() 
       throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
        g.initialize(ecSpec, Utils.getRng());
        KeyPair keypair = g.generateKeyPair();
        Map<String, String> description = new HashMap<>();
        description.put(DynamoDbEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
        return new SymmetricStaticProvider(null, keypair, description);
}
 
Example 10
Source File: AddProvider.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean legacy = args[0].equals("2");
    Security.addProvider(new TestProvider("Test1"));
    Security.insertProviderAt(new TestProvider("Test2"), 1);
    try {
        Security.addProvider(new TestProvider("Test3"));
        if (legacy) {
            throw new Exception("Expected SecurityException");
        }
    } catch (SecurityException se) {
        if (!legacy) {
            throw se;
        }
    }
}
 
Example 11
Source File: GenericCryptoModule.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor for the class.
 *
 * @param cryptomodule - The hardware cryptographic module
 * @param fipsmode - The fipsmode to set
 */
public GenericCryptoModule(CryptoModule cryptomodule, Boolean fipsmode) {
    Security.addProvider(new BouncyCastleFipsProvider());
    if (fipsmode) {
        CryptoServicesRegistrar.setApprovedOnlyMode(true);
    }
    this.cryptomodule = cryptomodule;
}
 
Example 12
Source File: PDFSigner.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * Faz a leitura do token em LINUX, precisa setar a lib (.SO) e a senha do token.
 */
@SuppressWarnings("restriction")
private KeyStore getKeyStoreToken() {

	try {
		// ATENÇÃO ALTERAR CONFIGURAÇÃO ABAIXO CONFORME O TOKEN USADO

		// Para TOKEN Branco a linha abaixo
		// String pkcs11LibraryPath =
		// "/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so";

		// Para TOKEN Azul a linha abaixo
		String pkcs11LibraryPath = "/usr/lib/libeToken.so";

		StringBuilder buf = new StringBuilder();
		buf.append("library = ").append(pkcs11LibraryPath).append("\nname = Provedor\n");
		Provider p = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(buf.toString().getBytes()));
		Security.addProvider(p);
		// ATENÇÃO ALTERAR "SENHA" ABAIXO
		Builder builder = KeyStore.Builder.newInstance("PKCS11", p,	new KeyStore.PasswordProtection("senha".toCharArray()));
		KeyStore ks;
		ks = builder.getKeyStore();

		return ks;

	} catch (Exception e1) {
		e1.printStackTrace();
		return null;
	} finally {
	}

}
 
Example 13
Source File: Config.java    From ripple-lib-java with ISC License 4 votes vote down vote up
static public void initBouncy() {
    if (!bouncyInitiated) {
        Security.addProvider(new BouncyCastleProvider());
        bouncyInitiated = true;
    }
}
 
Example 14
Source File: TlsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static X509CRLHolder createCRL() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SelfSignedX509CertificateAndSigningKey muneraSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
            .setDn(MUNERASOFT_DN)
            .setKeyAlgorithmName("RSA")
            .setSignatureAlgorithmName("SHA256withRSA")
            .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647")
            .build();
    X509Certificate muneraCertificate = muneraSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate();

    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    calendar.add(Calendar.YEAR, 1);
    Date nextYear = calendar.getTime();
    calendar.add(Calendar.YEAR, -1);
    calendar.add(Calendar.SECOND, -30);
    Date revokeDate = calendar.getTime();

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(
            new X500Name(MUNERASOFT_DN.getName()),
            currentDate
    );
    crlBuilder.addExtension(
            Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(muneraCertificate.getPublicKey())
    );
    crlBuilder.addExtension(
            Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4110))
    );
    crlBuilder.addCRLEntry(
            new BigInteger("1005"),
            revokeDate,
            CRLReason.unspecified
    );
    crlBuilder.addCRLEntry(
            new BigInteger("1006"),
            revokeDate,
            CRLReason.unspecified
    );
    return crlBuilder.setNextUpdate(nextYear).build(
            new JcaContentSignerBuilder("SHA256withRSA")
                    .setProvider("BC")
                    .build(muneraSelfSignedX509CertificateAndSigningKey.getSigningKey())
    );
}
 
Example 15
Source File: ECDSATest.java    From bushido-java-core with GNU General Public License v3.0 4 votes vote down vote up
@BeforeClass
public static void init ()
{
    Security.addProvider(new BouncyCastleProvider());
}
 
Example 16
Source File: GetPrivateKey.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (initSecmod() == false) {
        return;
    }

    String configName = BASE + SEP + "nss.cfg";
    Provider p = getSunPKCS11(configName);

    System.out.println(p);
    Security.addProvider(p);

    if (args.length > 1 && "sm".equals(args[0])) {
        System.setProperty("java.security.policy",
                BASE + File.separator + args[1]);
        System.setSecurityManager(new SecurityManager());
    }

    KeyStore ks = KeyStore.getInstance(PKCS11, p);
    ks.load(null, password);
    Collection<String> aliases = new TreeSet<>(
            Collections.list(ks.aliases()));
    System.out.println("entries: " + aliases.size());
    System.out.println(aliases);

    PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password);
    System.out.println(privateKey);

    byte[] data = generateData(1024);

    System.out.println("Signing...");
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(data);
    byte[] sig = signature.sign();

    X509Certificate[] chain =
            (X509Certificate[]) ks.getCertificateChain(keyAlias);
    signature.initVerify(chain[0].getPublicKey());
    signature.update(data);
    boolean ok = signature.verify(sig);
    if (ok == false) {
        throw new Exception("Signature verification error");
    }

    System.out.println("OK");

}
 
Example 17
Source File: TestAESWithProviderChange.java    From openjdk-jdk9 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 18
Source File: ApvssTest.java    From protect with MIT License 4 votes vote down vote up
@BeforeClass
public static void setupBefore() {
	Security.addProvider(new BouncyCastleProvider());
}
 
Example 19
Source File: AbstractKerberosMgmtSaslTestBase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Creates directory services, starts LDAP server and KDCServer
 *
 * @param managementClient
 * @param containerId
 * @throws Exception
 * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
 *      java.lang.String)
 */
@Override
public void setup(ManagementClient managementClient) throws Exception {
    try {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
            removeBouncyCastle = true;
        }
    } catch (SecurityException ex) {
        LOGGER.warn("Cannot register BouncyCastleProvider", ex);
    }
    directoryService = DSAnnotationProcessor.getDirectoryService();
    final String hostname = CoreUtils.getCannonicalHost(TestSuiteEnvironment.getHttpAddress());
    final Map<String, String> map = new HashMap<String, String>();
    map.put("hostname", NetworkUtils.formatPossibleIpv6Address(hostname));
    final String secondaryTestAddress = NetworkUtils
            .canonize(CoreUtils.getCannonicalHost(TestSuiteEnvironment.getSecondaryTestAddress(false)));
    map.put("ldaphost", secondaryTestAddress);
    final String ldifContent = StrSubstitutor.replace(IOUtils.toString(
            AbstractKerberosMgmtSaslTestBase.class.getResourceAsStream("remoting-krb5-test.ldif"), "UTF-8"), map);
    LOGGER.trace(ldifContent);
    final SchemaManager schemaManager = directoryService.getSchemaManager();
    try {
        for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent, StandardCharsets.UTF_8))) {
            directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
        }
    } catch (Exception e) {
        LOGGER.warn("Importing LDIF to a directoryService failed.", e);
        throw e;
    }
    kdcServer = KDCServerAnnotationProcessor.getKdcServer(directoryService, 1024, hostname);
    final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer(
            (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class));
    createLdapServer.setSaslHost(secondaryTestAddress);
    createLdapServer.setSaslPrincipal("ldap/" + secondaryTestAddress + "@JBOSS.ORG");
    KerberosTestUtils.fixApacheDSTransportAddress(createLdapServer, secondaryTestAddress);
    ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService);
    ldapServer.getSaslHost();
    ldapServer.setSearchBaseDn("dc=wildfly,dc=org");
    ldapServer.start();

    KRB5_CONFIGURATION = new Krb5LoginConfiguration(CoreUtils.getLoginConfiguration());
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(KRB5_CONFIGURATION);

}
 
Example 20
Source File: Config.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
static public void initBouncy() {
    if (!bouncyInitiated) {
        Security.addProvider(new BouncyCastleProvider());
        bouncyInitiated = true;
    }
}