Example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Prototype

String PROVIDER_NAME

To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Click Source Link

Usage

From source file:org.nimbustools.auto_common.ezpz_ca.SigningPolicy.java

License:Apache License

public static String getPolicyString(String caCertPath) throws Exception {

    final X509Certificate cert;
    final FileReader fr = new FileReader(caCertPath);
    try {// ww  w .java 2  s.  c  o m
        Security.addProvider(new BouncyCastleProvider());
        final PEMReader reader = new PEMReader(fr, null, BouncyCastleProvider.PROVIDER_NAME);
        try {
            cert = (X509Certificate) reader.readObject();
        } finally {
            reader.close();
        }
    } finally {
        fr.close();
    }

    // access_id_CA
    final X500Principal subjectDN = cert.getSubjectX500Principal();
    final String DN = subjectDN.getName(X500Principal.RFC2253);
    final String access_id_CA = CertUtil.toGlobusID(DN, false);

    // cond_subjects
    final String signingtarget = EzPzCA.deriveSigningTargetString(cert);
    final String cond_subjectsRFC2253 = EzPzCA.getTargetDNfromSchema(signingtarget, "*");
    final String cond_subjects = CertUtil.toGlobusID(cond_subjectsRFC2253, true);

    final StringBuilder sb = new StringBuilder(PREFIX);
    sb.append("\n\n access_id_CA      X509         '");
    sb.append(access_id_CA);
    sb.append("'\n\n pos_rights        globus        CA:sign\n\n cond_subjects     globus       '\"");
    sb.append(cond_subjects);
    sb.append("\"'\n\n");
    sb.append(SUFFIX);
    return sb.toString();
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

public static void installBCProvider() {
    // we need to check if the BouncyCastle provider is already installed
    // before installing it
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from  w  w w  .  j a  va2 s  .c o  m*/
}

From source file:org.objectweb.proactive.extensions.ssl.CertificateGenerator.java

License:Open Source License

/**
 * Create a random, self signed, one time certificate
 *
 * A such certificate can be used to take advantage of the SSL/TLS encryption
 * feature without requiring any action from the user.
 *
 * A self signed certificate, valid for the next 10 year is issued.
 *
 * @return//from   ww w  . j a  v  a  2s .  c o m
 */
public X509Certificate generateCertificate(String subjectDN, KeyPair pair) throws SslException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Auto-generated certificate, use a default principal
    X500Principal defaultPrincipal;
    defaultPrincipal = new X500Principal(subjectDN);
    certGen.setIssuerDN(defaultPrincipal);
    certGen.setSubjectDN(defaultPrincipal);

    // Valid for the next few years
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + (10 * 365 * 24 * 60)));

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // Not certified by a CA
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // SSL requires signiture & encipherment
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
    certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage);

    // Allow client and server authentication
    Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>();
    extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsageV));

    try {
        X509Certificate cert = certGen.generate(pair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME);
        try {
            cert.checkValidity();
            cert.verify(pair.getPublic());
        } catch (GeneralSecurityException e) {
            throw new SslException("Generated certificate is not valid", e);
        }

        return cert;
    } catch (GeneralSecurityException e) {
        throw new SslException("Failed to generate certificate", e);
    }
}

From source file:org.objectweb.proactive.extensions.ssl.SameCertTrustManager.java

License:Open Source License

private void checkTrusted(X509Certificate cert) throws CertificateException {
    for (X509Certificate authCert : this.authCerts) {
        byte[] pk1 = cert.getPublicKey().getEncoded();
        byte[] pk2 = authCert.getPublicKey().getEncoded();
        if (Arrays.areEqual(pk1, pk2)) {
            try {
                cert.verify(authCert.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME);
                return;
            } catch (GeneralSecurityException e) {
                // Ok
            }/*  w  ww .  j ava2  s  . c  o  m*/
        }
    }

    throw new CertificateException(
            cert.getSubjectDN() + " public key does not match the master certificate public key");
}

From source file:org.objectweb.proactive.extensions.ssl.SslHelpers.java

License:Open Source License

/**
 * Insert Bouncy castle as a security provider if needed
 *///  ww w. ja  v  a 2  s.  com
static public void insertBouncyCastle() {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}

From source file:org.onosproject.netconf.ctl.impl.NetconfControllerImpl.java

License:Apache License

@Deactivate
public void deactivate() {
    netconfDeviceMap.values().forEach(device -> {
        device.getSession().removeDeviceOutputListener(downListener);
        device.disconnect();// w ww  .ja v a  2s  .  c  o  m
    });
    cfgService.unregisterProperties(getClass(), false);
    netconfDeviceListeners.clear();
    netconfDeviceMap.clear();
    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    log.info("Stopped");
}

From source file:org.onosproject.netconf.ctl.impl.NetconfSessionMinaImpl.java

License:Apache License

@Deprecated
private void startSession() throws IOException {
    final ConnectFuture connectFuture;
    connectFuture = client.connect(deviceInfo.name(), deviceInfo.ip().toString(), deviceInfo.port())
            .verify(connectTimeout, TimeUnit.SECONDS);
    session = connectFuture.getSession();
    //Using the device ssh key if possible
    if (deviceInfo.getKey() != null) {
        try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            try {
                KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
                session.addPublicKeyIdentity(kp);
            } catch (IOException e) {
                throw new NetconfException("Failed to authenticate session with device " + deviceInfo
                        + "check key to be a valid key", e);
            }/*w  w w.  j a v  a  2s.  c  om*/
        }
    } else {
        session.addPasswordIdentity(deviceInfo.password());
    }
    session.auth().verify(connectTimeout, TimeUnit.SECONDS);
    Set<ClientSession.ClientSessionEvent> event = session
            .waitFor(
                    ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
                            ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED),
                    0);

    if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
        log.debug("Session closed {} {}", event, session.isClosed());
        throw new NetconfException(
                "Failed to authenticate session with device " + deviceInfo + "check the user/pwd or key");
    }
    openChannel();
}

From source file:org.opensc.test.pkcs11.SaveCertificateTest.java

License:Open Source License

@Override
public void tearDown() {
    super.tearDown();

    Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.pepstock.jem.node.security.Crypto.java

License:Open Source License

/**
 * Loads a private key from a file, using password and file passed ar argument
 * /*from w ww .j a va 2s .c  o m*/
 * @param pemKeyFile is the pem file of the RSA private key of the user.
 * @param password the password of the private key if the private key is
 *            protected by a password, null otherwise
 * @return the private Key read from pem file
 * @throws KeyException if any Exception occurs while extracting private key
 * @throws MessageException if any Exception occurs while extracting private key
 */
public static Key loadPrivateKeyFromFile(File pemKeyFile, String password)
        throws MessageException, KeyException {
    try {
        // checks if the provider is loaded.
        // if not, it adds BouncyCastle as provider
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        // private key file in PEM format, from file
        PEMParser pemParser = new PEMParser(
                new InputStreamReader(new FileInputStream(pemKeyFile), CharSet.DEFAULT));
        // reads the object and close the parser and input stream
        Object object = pemParser.readObject();
        pemParser.close();
        // creates a key converter by BouncyCastle
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
        // gets key pair instance
        KeyPair kp;
        // if is a PEM
        if (object instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new MessageException(NodeMessage.JEMC205E);
            }
            // uses the PEM decryptor using password
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
            kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
        } else {
            // if here, the key it's protected by password
            LogAppl.getInstance().emit(NodeMessage.JEMC199W);
            kp = converter.getKeyPair((PEMKeyPair) object);
        }
        return kp.getPrivate();
    } catch (FileNotFoundException e) {
        throw new KeyException(e.getMessage(), e);
    } catch (PEMException e) {
        throw new KeyException(e.getMessage(), e);
    } catch (IOException e) {
        throw new KeyException(e.getMessage(), e);
    }
}

From source file:org.primeoservices.cfpass.PassUtils.java

License:Apache License

public static void createSignature(final String directoryPath, final String keyStoreFilePath,
        final String keyStorePassword) throws Exception {
    // Add BC provider
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from   w w  w  .ja  va2  s  .c o m

    // Check directory
    final File directory = new File(directoryPath);
    if (directory.exists() && !directory.isDirectory()) {
        throw new IllegalArgumentException(directoryPath + " is not a directory");
    }

    // Check manifest file
    final File manifest = new File(directory, "manifest.json");
    if (manifest.exists() && !manifest.isFile()) {
        throw new IllegalArgumentException("File manifest.json doesn't exists");
    }

    // Check key store
    final File keyStore = new File(keyStoreFilePath);
    if (keyStore.exists() && !keyStore.isFile()) {
        throw new IllegalArgumentException("Keystore not found");
    }

    // Load key store
    final FileInputStream clientStoreIn = new FileInputStream(keyStore);
    final KeyStore clientStore = KeyStore.getInstance("PKCS12");
    clientStore.load(clientStoreIn, keyStorePassword.toCharArray());

    // Extract private key and certificate
    final Enumeration<String> aliases = clientStore.aliases();
    String alias = "";
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        if (clientStore.isKeyEntry(alias)) {
            break;
        }
    }
    final PrivateKey key = (PrivateKey) clientStore.getKey(alias, keyStorePassword.toCharArray());
    final X509Certificate cert = (X509Certificate) clientStore.getCertificate(alias);

    // Load Apple certificate
    final InputStream appleCertIn = PassUtils.class.getResourceAsStream("/AppleWWDRCA.cer");
    final CertificateFactory appleCertFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate appleCert = (X509Certificate) appleCertFactory.generateCertificate(appleCertIn);

    // Signature
    final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(key);

    final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
    final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
            new DERSet(new DERUTCTime(new Date())));
    signedAttributes.add(signingAttribute);
    // Create the signing table
    final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
    // Create the table table generator that will added to the Signer builder
    final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
            signedAttributesTable);

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(appleCert);
    certList.add(cert);
    Store certs = new JcaCertStore(certList);

    final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .setSignedAttributeGenerator(signedAttributeGenerator).build(sha1Signer, cert));
    generator.addCertificates(certs);

    final CMSSignedData sigData = generator.generate(new CMSProcessableFile(manifest), false);
    final byte[] signedDataBytes = sigData.getEncoded();

    // Write signature
    final File signatureFile = new File(directoryPath, "signature");
    final FileOutputStream signatureOutputStream = new FileOutputStream(signatureFile);
    signatureOutputStream.write(signedDataBytes);
    signatureOutputStream.close();
}