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

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

Introduction

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

Prototype

public BouncyCastleProvider() 

Source Link

Document

Construct a new provider.

Usage

From source file:encryption.ThreefishCrypt.java

License:Open Source License

public static byte[] decrypt(byte[] key_aes, byte[] encrypted)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    SecretKey secret = new SecretKeySpec(key_aes, "Threefish-256");
    Cipher cipher;//w  ww  . j  a va 2  s .co  m
    try {
        if (Core.PROVIDER.equals(Core.SPONGEY_CASTLE))
            cipher = Cipher.getInstance("Threefish-256/CBC/PKCS5Padding",
                    new org.spongycastle.jce.provider.BouncyCastleProvider());
        else
            cipher = Cipher.getInstance("Threefish-256/CBC/PKCS5Padding", new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

        return cipher.doFinal(encrypted);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:es.gob.afirma.cert.signvalidation.ValidateBinarySignature.java

License:Open Source License

/** Verifica la valides de una firma. Si la firma es válida, no hace nada. Si no es
 * válida, lanza una excepción.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobación.
 * @throws CMSException Cuando la firma no tenga una estructura válida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse./*  w ww.  jav a2  s.c  o  m*/
 * @throws CertificateExpiredException Cuando el certificado estáa caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es válido.
 * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los
 * algoritmos utilizados en la firma.
 * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados.
 * @throws CRLException Cuando ocurre un error con las CRL de la firma.
 * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma
 * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo
 * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/
private static void verifySignatures(final byte[] sign, final byte[] data)
        throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException,
        NoSuchProviderException, CertificateException, IOException, OperatorCreationException {

    final CMSSignedData s;
    if (data == null) {
        s = new CMSSignedData(sign);
    } else {
        s = new CMSSignedData(new CMSProcessableByteArray(data), sign);
    }
    final Store<X509CertificateHolder> store = s.getCertificates();

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$

    for (final Object si : s.getSignerInfos().getSigners()) {
        final SignerInformation signer = (SignerInformation) si;

        final Iterator<X509CertificateHolder> certIt = store
                .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator();
        final X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded()));

        if (!signer
                .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(),
                        new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder()
                                .setProvider(new BouncyCastleProvider()).build(cert),
                        new BcDigestCalculatorProvider()))) {
            throw new CMSException("Firma no valida"); //$NON-NLS-1$
        }

    }

}

From source file:es.gob.afirma.signature.ValidateBinarySignature.java

License:Open Source License

/** Verifica la valides de una firma. Si la firma es v&aacute;lida, no hace nada. Si no es
 * v&aacute;lida, lanza una excepci&oacute;n.
 * @param sign Firma que se desea validar.
 * @param data Datos para la comprobaci&oacute;n.
 * @throws CMSException Cuando la firma no tenga una estructura v&aacute;lida.
 * @throws CertStoreException Cuando se encuentra un error en los certificados de
 * firma o estos no pueden recuperarse./*from   ww w  . j a va 2 s .com*/
 * @throws CertificateExpiredException Cuando el certificado est&aacute;a caducado.
 * @throws CertificateNotYetValidException Cuando el certificado aun no es v&aacute;lido.
 * @throws NoSuchAlgorithmException Cuando no se reconoce o soporta alguno de los
 * algoritmos utilizados en la firma.
 * @throws NoMatchDataException Cuando los datos introducidos no coinciden con los firmados.
 * @throws CRLException Cuando ocurre un error con las CRL de la firma.
 * @throws NoSuchProviderException Cuando no se encuentran los proveedores de seguridad necesarios para validar la firma
 * @throws IOException Cuando no se puede crear un certificado desde la firma para validarlo
 * @throws OperatorCreationException Cuando no se puede crear el validado de contenido de firma*/
private static void verifySignatures(final byte[] sign, final byte[] data)
        throws CMSException, CertStoreException, NoSuchAlgorithmException, NoMatchDataException, CRLException,
        NoSuchProviderException, CertificateException, IOException, OperatorCreationException {

    final CMSSignedData s;
    if (data == null) {
        s = new CMSSignedData(sign);
    } else {
        s = new CMSSignedData(new CMSProcessableByteArray(data), sign);
    }
    final Store store = s.getCertificates();

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); //$NON-NLS-1$

    for (final Object si : s.getSignerInfos().getSigners()) {
        final SignerInformation signer = (SignerInformation) si;

        final Iterator<X509CertificateHolder> certIt = store
                .getMatches(new CertHolderBySignerIdSelector(signer.getSID())).iterator();
        final X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(certIt.next().getEncoded()));

        if (!signer
                .verify(new SignerInformationVerifier(new DefaultCMSSignatureAlgorithmNameGenerator(),
                        new DefaultSignatureAlgorithmIdentifierFinder(), new JcaContentVerifierProviderBuilder()
                                .setProvider(new BouncyCastleProvider()).build(cert),
                        new BcDigestCalculatorProvider()))) {
            throw new CMSException("Firma no valida"); //$NON-NLS-1$
        }

    }

}

From source file:es.jamisoft.cryptography.sign.Firma.java

License:Apache License

public static void main(String[] unused) throws Exception {
    Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC

    // Generate a key-pair
    //    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");

    kpg.initialize(512); // 512 is the keysize.

    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubk = kp.getPublic();
    PrivateKey prvk = kp.getPrivate();

    System.out.println(pubk.getEncoded());
    System.out.println(prvk.getEncoded());

    String datafile = "build.xml";
    FileInputStream fis = new FileInputStream(datafile);
    byte[] sigbytes = firmar(fis, prvk, Firma.ALGORITMO);
    System.out.println("Signature:: " + sigbytes);
    boolean result = verificar(fis, pubk, Firma.ALGORITMO, sigbytes);
    System.out.println("Signature Verification Result = " + result);
    fis.close();//ww w .  j  a va  2  s . c  o m
}

From source file:es.mityc.firmaJava.libreria.pkcs7.ConexionTarjeta.java

License:LGPL

/**
 * @param args/*from   w w  w  .  j  av  a2 s .com*/
 */
public static KeyStore conectar(char[] pin, String libreria) throws PKCS11Exception, ProviderException {
    KeyStore ks = null;
    try {
        if (Security.getProvider(SUNPCKS11_TOKEN) != null)
            Security.removeProvider(SUNPCKS11_TOKEN);
        String pkcs11config = NAME_IGUAL_TOKEN + LIBRARY_IGUAL + libreria;
        byte[] pkcs11configBytes = pkcs11config.getBytes();
        ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11configBytes);
        Provider pkcs11Provider = new SunPKCS11(configStream);
        Security.addProvider(new BouncyCastleProvider());
        Security.addProvider(pkcs11Provider);

        ks = KeyStore.getInstance(PKCS11, pkcs11Provider);
        ks.load(null, pin);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Throwable t = null;
        if (e.getCause() != null) {
            t = e.getCause();

            if (t.getCause() != null && t.getCause() instanceof PKCS11Exception) {
                PKCS11Exception pke = (PKCS11Exception) t.getCause();
                throw new PKCS11Exception(pke.getErrorCode());
            }

        }
    } catch (KeyStoreException e) {
        throw new PKCS11Exception(-1);
    } catch (ProviderException e) {
        if (e.getCause() != null) {
            Throwable t = e.getCause();
            if (t instanceof PKCS11Exception) {
                PKCS11Exception pke = (PKCS11Exception) t;
                throw new PKCS11Exception(pke.getErrorCode());
            } else
                throw e;
        } else {
            throw new ProviderException(e.getMessage());
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return ks;
}

From source file:esteidhacker.FakeEstEIDCA.java

License:Open Source License

public FakeEstEIDCA() throws NoSuchAlgorithmException {
    // Add BouncyCastle if not present
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null)
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
}

From source file:eu.betaas.taas.securitymanager.certificate.service.impl.GWStarCertificateIntService.java

License:Apache License

public void createGwStarCredentials(X500Name subjRoot, X500Name subjInter, X500Name subjEnd, String ufn) {
    log.debug("In the beginning of createGwStarCredentials...");
    Security.addProvider(new BouncyCastleProvider());
    // First, create the GW* "signing" credentials including only the root and 
    // intermediate certificates which are encapsulated in a KeyStore
    BcCredential interCredentials = null;
    try {/* ww w .  ja  v a  2  s  .com*/
        interCredentials = GWCertificateUtilsBc.createGwStarInterCredentials(subjRoot, subjInter, ROOT_ALIAS,
                INTER_ALIAS);
    } catch (Exception e) {
        log.error("Error creating GW* intermediate credentials: " + e.getMessage());
        e.printStackTrace();
    }

    log.info("Intermediate certificate of GW* has been created...");

    // create a PKCS12 file from the chain of certificate within the Intermediate credential
    AsymmetricKeyParameter priv = interCredentials.getPrivateKey();
    X509CertificateHolder[] chain = interCredentials.getCertificateChain();

    try {
        PKCS12Utils.createPKCS12FileBc(new FileOutputStream(certPath + PKCS12_FILE_NAME_INTER), priv, chain,
                GWCertificateUtilsBc.KEY_PASSWD);
    } catch (FileNotFoundException e) {
        log.error("Error creating PKCS12 file of intermediate credentials: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        log.error("Error creating PKCS12 file of intermediate credentials: " + e.getMessage());
        e.printStackTrace();
    }

    // Then, create the GW* "own" credentials including the root, intermediate,
    // and the end entity certificates which are encapsulated in a KeyStore
    BcCredential ownCredentials = null;
    try {
        ownCredentials = GWCertificateUtilsBc.createGwStarOwnCredentials(subjEnd, ROOT_ALIAS, INTER_ALIAS,
                END_ENTITY_ALIAS, ufn, certPath);
    } catch (Exception e) {
        log.error("Error creating end entity credentials for GW*: " + e.getMessage());
        e.printStackTrace();
    }

    priv = ownCredentials.getPrivateKey();
    chain = ownCredentials.getCertificateChain();

    try {
        PKCS12Utils.createPKCS12FileBc(new FileOutputStream(certPath + PKCS12_FILE_NAME_OWN), priv, chain,
                GWCertificateUtilsBc.KEY_PASSWD);
    } catch (FileNotFoundException e) {
        log.error("Error creating PKCS12 file of end entity credentials: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        log.error("Error creating PKCS12 file of end entity credentials: " + e.getMessage());
        e.printStackTrace();
    }

    log.info("End entity certificate of GW* has been created...");

    // set this GW as GW*
    Config.isGwStar = true;
}

From source file:eu.betaas.taas.securitymanager.core.service.impl.JoinInstanceService.java

License:Apache License

public boolean requestGwCertificate(String countryCode, String state, String location, String orgName,
        String gwId) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    boolean ok = false;
    log.info("Start the request certificate instance...");

    ArrayOfCertificate certsArray = null;

    // initiate a CertificationRequest message
    X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE);
    x500NameBld.addRDN(BCStyle.C, countryCode);
    x500NameBld.addRDN(BCStyle.ST, state);
    x500NameBld.addRDN(BCStyle.L, location);
    x500NameBld.addRDN(BCStyle.O, orgName);
    x500NameBld.addRDN(BCStyle.CN, "BETaaS Gateway Certificate");

    X500Name subject = x500NameBld.build();

    AsymmetricCipherKeyPair kp = ECKeyPairGen.generateECKeyPair192();
    //      log.info("intServ: "+intServ.toString());
    // get the certification request message
    PKCS10CertificationRequest gwCertReq = gwCertificateService.buildCertificationRequest(subject, kp, gwId);
    log.info("Successfully generate PKCS10CertificationRequest!!");

    // get the GW* external cert. service via ServiceTracker
    IGatewayStarCertificateExtService extServ = null;

    extCertTracker = new ServiceTracker(context, IGatewayStarCertificateExtService.class.getName(), null);
    extCertTracker.open();//  w w  w. jav a2  s  .  c  o  m

    // give time to the tracker to find CertificateExtService
    Thread.sleep(2500);

    ServiceReference[] refs = extCertTracker.getServiceReferences();

    // iterating through the service references
    for (ServiceReference ref : refs) {
        log.debug("GW ID: " + ref.getProperty("gwId"));
        log.debug("Is it GW*: " + ((IGatewayStarCertificateExtService) context.getService(ref)).isGWStar());
        // check if the gatewayId of remote GW equals gwStar
        if (((IGatewayStarCertificateExtService) context.getService(ref)).isGWStar()) {
            log.debug("Found the ExtCert service of GW*");
            extServ = (IGatewayStarCertificateExtService) context.getService(ref);
        }
    }

    // send a request to issue a certificate for me (this GW) to GW* 
    if (gwCertReq != null && extServ != null) {
        certsArray = extServ.issueGwCertificate(gwCertReq.getEncoded());

        X509CertificateHolder[] certs = new X509CertificateHolder[certsArray.getCertificate().size()];

        // decode the received array of certificates (consists of intermediate 
        // and my own certificates) from array byte[] to X509Certificate
        for (int i = 0; i < certsArray.getCertificate().size(); i++) {
            byte[] cert = certsArray.getCertificate().get(i);
            certs[i] = new X509CertificateHolder(cert);
        }

        log.debug("Start storing the newly created certificate from GW*...");
        // now store the certificates in a .p12 file
        gwCertificateService.storeMyCertificate(kp.getPrivate(), certs);
        ok = true;

        log.info("Successfully requesting certificate from GW* and store it");

        // closing the service tracker
        extCertTracker.close();
    }

    return ok;
}

From source file:eu.betaas.taas.securitymanager.core.service.impl.SecureGWCommService.java

License:Apache License

public boolean deriveSharedKeys(String gwDestId) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    boolean sendLast = false;

    log.info("Start deriving shared keys");

    BcCredential myCertStore = null;/*from www.  j a va2  s  .c o  m*/

    // generate an ephemeral KeyPair
    AsymmetricCipherKeyPair myEphKp = gwEcmqvIntService.generateEphemeralKeyPair();

    // initiate the ECMQV procedure...
    // first load the credential and then the certificate of this GW
    myCertStore = gwCertificateService.loadMyCertificate(PKCS12Utils.GW_CERT);
    X509CertificateHolder myCert = null;
    if (myCertStore != null) {
        myCert = (X509CertificateHolder) myCertStore.getCertificateChain()[0];
    }
    // then, invoke the initEcmqv method to other GW, by retrieving the 
    // external ECMQV service first
    EcmqvMessage eMsg = null;
    IGatewayEcmqvExtService ecmqvExtServ = null;

    // initializing service tracker of GWEcmqvExtService
    ecmqvExtTracker = new ServiceTracker(context, IGatewayEcmqvExtService.class.getName(), null);
    ecmqvExtTracker.open();

    // give time to the tracker to find CertificateExtService
    Thread.sleep(2500);

    ServiceReference[] refs = ecmqvExtTracker.getServiceReferences();
    // iterating through the service references
    for (ServiceReference ref : refs) {
        // check if gatewayId of remote GW equals to gwDestId of this GW
        if (ref.getProperty("gwId").equals(gwDestId)) {
            log.debug("Found ExtEcmqv service of the GW destination ID");
            ecmqvExtServ = (IGatewayEcmqvExtService) context.getService(ref);
        }
    }

    if (ecmqvExtServ != null) {
        // the actual invocation of initEcmqv 
        eMsg = ecmqvExtServ.initEcmqv(((ECPublicKey) myEphKp.getPublic()).getW().getAffineX().toByteArray(), // the X-coordinate of EC public key param. 
                ((ECPublicKey) myEphKp.getPublic()).getW().getAffineY().toByteArray(), // the Y-coordinate of EC public key param.
                myCert.getEncoded());
    }

    // upon receiving the eMsg, verify it and calculate the MAC 3
    byte[] mac3 = null;
    if (eMsg != null) {
        mac3 = gwEcmqvIntService.responseEcmqv(eMsg);
    }

    // upon successful verification of eMsg which results in MAC 3, send MAC 3
    // to the other GW

    if (mac3 != null && ecmqvExtServ != null) {
        sendLast = ecmqvExtServ.lastEcmqv(mac3);
        log.info("the MAC 3 is correctly confirmed");
    }

    // closing the service tracker
    ecmqvExtTracker.close();

    return sendLast;
}

From source file:eu.codesketch.adam.docker.StringSSLConfig.java

License:Apache License

@Override
public SSLContext getSSLContext()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    try {//w  w  w . j a  v  a2s.co m

        Security.addProvider(new BouncyCastleProvider());

        // properties acrobatics not needed for java > 1.6
        String httpProtocols = System.getProperty("https.protocols");
        System.setProperty("https.protocols", "TLSv1");
        SslConfigurator sslConfig = SslConfigurator.newInstance(true);
        if (httpProtocols != null) {
            System.setProperty("https.protocols", httpProtocols);
        }

        sslConfig.keyStore(CertificateUtils.createKeyStore(key, certificate));
        sslConfig.keyStorePassword("docker");
        sslConfig.trustStore(CertificateUtils.createTrustStore(certificateAuthority));

        return sslConfig.createSSLContext();

    } catch (Exception e) {
        throw new DockerClientException(e.getMessage(), e);
    }
}