Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:test.integ.be.e_contract.mycarenet.cxf.SyncClientTest.java

@Test
public void testEcho() throws Exception {
    // setup/*w  w  w  . j  a  va 2s.  c  om*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync",
                sessionKey, packageLicenseKey);

        ObjectFactory objectFactory = new ObjectFactory();
        XmlDocumentWrapperType request = objectFactory.createXmlDocumentWrapperType();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element element = document.createElement("test");
        request.setAny(element);
        request.setLang("en");
        // operate
        XmlDocumentWrapperType result;
        try {
            result = syncClient.echo(request);
        } finally {
            LOG.debug("payload: " + syncClient.getPayload());
        }

        // verify
        assertEquals(result.getAny().getNodeName(), "test");
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:org.apache.nifi.processors.standard.TestEncryptContent.java

@Before
public void setUp() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

@Override
public Optional<SslContext> initSslContext() {
    try {/*from  ww w . j a  va2 s  . co m*/
        Security.addProvider(new BouncyCastleProvider());
        return Optional.of(SslContextBuilder.forClient().keyManager(createAndInitKeyManagerFactory())
                .trustManager(createAndInitTrustManagerFactory()).clientAuth(ClientAuth.REQUIRE).build());
    } catch (Exception e) {
        log.error("[{}:{}] Creating TLS factory failed!", caCert, cert, e);
        throw new RuntimeException("Creating TLS factory failed!", e);
    }
}

From source file:be.fedict.eid.tsl.Pkcs11Token.java

public Pkcs11Token(String pkcs11Library, int slotIdx) throws IOException {
    this.pkcs11Library = pkcs11Library;
    this.slotIdx = slotIdx;
    LOG.debug("PKCS#11 library: " + this.pkcs11Library);
    String pkcs11ConfigFile = createPkcs11ProviderConfigFile();
    this.pkcs11Provider = new SunPKCS11(pkcs11ConfigFile);
    if (-1 == Security.addProvider(this.pkcs11Provider)) {
        throw new RuntimeException("could not add security provider");
    }/*w w w. ja v  a  2s  .com*/
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java

@BeforeClass
public static void before() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:org.apache.nifi.encrypt.StringEncryptor.java

/**
 * Creates an instance of the nifi sensitive property encryptor. Validates
 * that the encryptor is actually working.
 *
 * @param niFiProperties properties/*from  www  .  ja  v a  2  s. com*/
 * @return encryptor
 * @throws EncryptionException if any issues arise initializing or
 * validating the encryptor
 */
public static StringEncryptor createEncryptor(final NiFiProperties niFiProperties) throws EncryptionException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    final String sensitivePropAlgorithmVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_ALGORITHM);
    final String sensitivePropProviderVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_PROVIDER);
    final String sensitivePropValueNifiPropVar = niFiProperties.getProperty(NF_SENSITIVE_PROPS_KEY,
            DEFAULT_SENSITIVE_PROPS_KEY);

    if (StringUtils.isBlank(sensitivePropAlgorithmVal)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_ALGORITHM + "must bet set");
    }

    if (StringUtils.isBlank(sensitivePropProviderVal)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_PROVIDER + "must bet set");
    }

    if (StringUtils.isBlank(sensitivePropValueNifiPropVar)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_KEY + "must bet set");
    }

    final StringEncryptor nifiEncryptor;
    try {
        nifiEncryptor = new StringEncryptor(sensitivePropAlgorithmVal, sensitivePropProviderVal,
                sensitivePropValueNifiPropVar);
        //test that we can infact encrypt and decrypt something
        if (!nifiEncryptor.decrypt(nifiEncryptor.encrypt(TEST_PLAINTEXT)).equals(TEST_PLAINTEXT)) {
            throw new EncryptionException(
                    "NiFi property encryptor does appear to be working - decrypt/encrypt return invalid results");
        }

    } catch (final EncryptionInitializationException | EncryptionOperationNotPossibleException ex) {
        throw new EncryptionException("Cannot initialize sensitive property encryptor", ex);

    }
    return nifiEncryptor;
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtilTest.java

public void testPassZipGeneration() throws IOException, Exception {

    Security.addProvider(new BouncyCastleProvider());

    ObjectMapper jsonObjectMapper = new ObjectMapper();
    PKPass pass = jsonObjectMapper.readValue(new File("/Users/patrice/Downloads/passbook/Passes/pass2.json"),
            PKPass.class);
    pass.setRelevantDate(new Date());
    pass.getBarcode().setMessageEncoding(Charset.forName("utf-8"));
    PKSigningInformation pkSigningInformation = PKSigningUtil
            .loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(keyStorePath, keyStorePassword,
                    appleWWDRCA);// w w w .  j  av  a  2s. co  m
    byte[] signedAndZippedPkPassArchive = PKSigningUtil.createSignedAndZippedPkPassArchive(pass,
            "/Users/patrice/Downloads/passbook/Passes/bitzecheCoupons.raw", pkSigningInformation);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(signedAndZippedPkPassArchive);
    IOUtils.copy(inputStream, new FileOutputStream("/Users/patrice/Downloads/pass.zip"));
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);//from   w ww  .j a  va 2  s .  c o m
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() },
            secureRandom);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443);
    LOG.debug("socket created");
    SSLSession sslSession = sslSocket.getSession();
    Certificate[] peerCertificates = sslSession.getPeerCertificates();
    for (Certificate peerCertificate : peerCertificates) {
        LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal());
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint((X509Certificate) peerCertificates[peerCertificates.length - 1]);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);
    trustValidator.isTrusted(peerCertificates);
}

From source file:servlets.SecretKeyProvider.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww  .jav a  2  s .c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String opcion = request.getParameter("opcion");

    switch (opcion) {
    case "public":
        InputStream is = getServletContext().getResourceAsStream("/WEB-INF/server1024.publica");
        IOUtils.copy(is, response.getOutputStream());
        break;

    case "secret": {
        try {
            SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
            request.getSession().setAttribute("clave", secretKey);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC

            byte[] bufferPriv = new byte[5000];
            InputStream in = getServletContext().getResourceAsStream("/WEB-INF/server1024.privada");
            int chars = in.read(bufferPriv, 0, 5000);
            in.close();

            byte[] bufferPriv2 = new byte[chars];
            System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars);

            // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8
            PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2);
            PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec);

            // PASO 3a: Poner cifrador en modo CIFRADO
            cifrador.init(Cipher.ENCRYPT_MODE, clavePrivada2); // Cifra con la clave publica

            byte[] bufferCifrado = cifrador.doFinal(secretKey.getEncoded());

            String mandar = new String(Base64.encodeBase64(bufferCifrado));
            response.getWriter().print(mandar);

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    }
}

From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java

@BeforeClass
public static void setup() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    BASE_DIR_FILE.mkdirs();//w ww . ja va2s.  c  o  m
    confDir = KeyStoreTestUtil.getClasspathDir(TestCRLValidator.class);
}