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:com.thoughtworks.go.security.X509CertificateGenerator.java

public X509CertificateGenerator() {
    Security.addProvider(new BouncyCastleProvider());
    this.keyStoreManager = new KeyStoreManager();
}

From source file:de.rub.nds.burp.utilities.attacks.signatureFaking.SignatureFakingOracle.java

/**
 * Creates SignatureWrappingOracle, parses the document and searches for all the SignatureValue and KeyInfo elements
 * //  w  w w  . j a v a 2  s .c o  m
 * @param document
 * @param replaceAllcertificates
 * @throws SignatureFakingException
 */
public SignatureFakingOracle(final Document document, final boolean replaceAllcertificates)
        throws SignatureFakingException {
    Security.addProvider(new BouncyCastleProvider());
    signatureValueElements = new LinkedList<Node>();
    keyInfoElements = new LinkedList<Node>();
    certificates = new LinkedList<String>();
    certHandlers = new LinkedList<CertificateHandler>();
    doc = document;
    replaceAll = replaceAllcertificates;
    crawlSignatureElements();
    Logging.getInstance().log(getClass(), "found " + signatureValueElements.size() + " SignatureValue elements",
            Logging.DEBUG);
    crawlKeyInfoElements();
    Logging.getInstance().log(getClass(),
            "found " + keyInfoElements.size() + " KeyInfo elements containing X509 certificates",
            Logging.DEBUG);
}

From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java

public EncryptionImpl(int saltLength, int pbeIterationCount, int passwordLength, int pbeKeyLength,
        String randomAlgorithm, String pbeAlgorithm, String cipherAlgorithm, String keyGenerator,
        String passwordHashAlgorihtm) {
    Security.addProvider(new BouncyCastleProvider());

    this.saltLength = saltLength;
    this.pbeIterationCount = pbeIterationCount;
    this.passwordLength = passwordLength;
    this.pbeKeyLength = pbeKeyLength;

    this.randomAlgorithm = randomAlgorithm;
    this.pbeAlgorithm = pbeAlgorithm;
    this.cipherAlgorithm = cipherAlgorithm;
    this.keyGenerator = keyGenerator;
    this.passwordHashAlgorithm = passwordHashAlgorihtm;
}

From source file:org.dpr.mykeys.ihm.MyKeys.java

private void init() {

    // Locale.setDefault(Locale.ENGLISH);
    log.debug("loading configuration...");

    Locale currentLocale = Locale.getDefault();
    try {/*from  w ww.j  av  a2 s  .  c  o m*/
        messages = ResourceBundle.getBundle("org.dpr.mykeys.config.Messages", currentLocale);
    } catch (Exception e) {
        messages = ResourceBundle.getBundle("org.dpr.mykeys.config.Messages", Locale.ENGLISH);
    }
    try {
        KSConfig.load();
        checkConfig();
    } catch (Exception e) {
        MykeysFrame.showError(null, messages.getString("error.config"));
        throw new RuntimeException("Fatal Error");
    }
    Security.addProvider(new BouncyCastleProvider());
    ProviderUtil.init("BC");
    // buildComponents();
    // updateKeyStoreList();

}

From source file:org.adempierelbr.model.MLBRDigitalCertificate.java

/**
 * setCertificate//from   www .  ja v a  2 s  .  c om
 * Set all System.property for webservice connection
 */
public static void setCertificate(Properties ctx, MOrgInfo oi) throws Exception {

    Integer certOrg = (Integer) oi.get_Value("LBR_DC_Org_ID");
    Integer certWS = (Integer) oi.get_Value("LBR_DC_WS_ID");
    MLBRDigitalCertificate dcOrg = new MLBRDigitalCertificate(Env.getCtx(), certOrg, null);
    MLBRDigitalCertificate dcWS = new MLBRDigitalCertificate(Env.getCtx(), certWS, null);

    String orgPassword = dcOrg.getPassword();
    String certType = null;
    InputStream certFileOrg = null;

    if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS12.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS12";
        certFileOrg = dcOrg.getAttachment(true).getEntry(0).getInputStream();
        if (certFileOrg == null)
            throw new Exception("Unable to find private key attachment");
    } else if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS11.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS11";
        Provider p = new sun.security.pkcs11.SunPKCS11(dcOrg.getConfigurationFile());
        Security.addProvider(p);
    } else
        return; //   Unknown Certificate

    KeyStore ks = KeyStore.getInstance(certType);
    try {
        ks.load(certFileOrg, orgPassword.toCharArray());
    } catch (IOException e) {
        throw new Exception("Incorrect Certificate Password");
    }

    InputStream certFileWS = dcWS.getAttachment(true).getEntry(0).getInputStream();
    if (certFileWS == null) {
        throw new Exception("Unable to find webservices keystore attachment");
    }

    String alias = dcOrg.getAlias();
    if (alias != null && ks.containsAlias(alias) && ks.isKeyEntry(alias))
        ;//   Do Nothing
    else {
        Enumeration<String> aliasesEnum = ks.aliases();
        while (aliasesEnum.hasMoreElements()) {
            alias = (String) aliasesEnum.nextElement();
            if (ks.isKeyEntry(alias))
                break;
        }
    }

    //Erro NFe 3.10
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, orgPassword.toCharArray());
    SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);
    socketFactoryDinamico.setFileCacerts(certFileWS, dcWS.getPassword());

    Protocol protocol = new Protocol("https", socketFactoryDinamico, 443);
    Protocol.registerProtocol("https", protocol);
}

From source file:com.intel.diceros.test.securerandom.DRNGTest.java

public void testDRNG() {
    Security.addProvider(new DicerosProvider());
    runTest(new DRNGTest());
}

From source file:wsattacker.library.signatureFaking.SignatureFakingOracle.java

/**
 * Creates SignatureWrappingOracle, parses the document and searches for all the SignatureValue and KeyInfo elements
 * /*from w  ww .  j  av  a2 s .c  om*/
 * @param documentString
 * @throws SignatureFakingException
 */
public SignatureFakingOracle(final String documentString) throws SignatureFakingException {
    Security.addProvider(new BouncyCastleProvider());
    signatureValueElements = new LinkedList<Node>();
    keyInfoElements = new LinkedList<Node>();
    certificates = new LinkedList<String>();
    certHandlers = new LinkedList<CertificateHandler>();
    try {
        doc = DomUtilities.stringToDom(documentString);
        crawlSignatureElements();
        log.debug("found " + signatureValueElements.size() + " SignatureValue elements");
        crawlKeyInfoElements();
        log.debug("found " + keyInfoElements.size() + " KeyInfo elements containing X509 certificates");
    } catch (SAXException e) {
        throw new SignatureFakingException(e);
    }
}

From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/* w w w  .j a  v a 2 s  . c  o m*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.debug("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on "
                + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}

From source file:org.apache.nifi.registry.properties.AESSensitivePropertyProvider.java

public AESSensitivePropertyProvider(String keyHex)
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
    byte[] key = validateKey(keyHex);

    try {/*  www .  j a  va  2 s .c  om*/
        Security.addProvider(new BouncyCastleProvider());
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        // Only store the key if the cipher was initialized successfully
        this.key = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
        logger.error("Encountered an error initializing the {}: {}", IMPLEMENTATION_NAME, e.getMessage());
        throw new SensitivePropertyProtectionException("Error initializing the protection cipher", e);
    }
}

From source file:test.unit.be.e_contract.mycarenet.etee.SealTest.java

@Test
public void testSeal() throws Exception {
    InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der");
    assertNotNull(sealInputStream);//from ww  w. ja va  2  s.com

    // check outer signature

    CMSSignedData cmsSignedData = new CMSSignedData(sealInputStream);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

    Security.addProvider(new BouncyCastleProvider());
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    assertTrue(signatureResult);

    LOG.debug("signer certificate: " + certificate);

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();

    // decrypt content

    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    @SuppressWarnings("unchecked")
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients();
    RecipientInformation recipientInformation = recipients.iterator().next();
    LOG.debug("recipient info type: " + recipientInformation.getClass().getName());
    KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation;

}