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:edu.ncsu.asbransc.mouflon.decryptlogs.Decrypt.java

License:Open Source License

/**
 * @param args/* ww w  . j  a  v  a 2s  .c o  m*/
 */
public static void main(String[] args) {
    //TODO make this handle fixing zip, unzipping, before decrypting
    //TODO clean up (delete encrypted intermediates) when done
    System.out.println(System.getProperty("java.class.path"));
    String keyFileName = args[0];
    String zipFileName = args[1];
    String outFileName = zipFileName.substring(0, zipFileName.length() - 4);
    File f = new File(keyFileName); //the key file
    File outFile = new File(outFileName);
    Security.addProvider(new BouncyCastleProvider());
    System.out.println(f.getAbsolutePath());
    FileOutputStream fout = null;
    CipherInputStream cin = null;
    FileInputStream fin = null;
    try {
        SecretKey aeskey = readAndDecryptAESKey(f);
        //System.out.println(bytearrToString(aeskey.getEncoded()));
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        fin = new FileInputStream(new File(zipFileName)); //the zip file
        byte[] ivbytes = new byte[16];
        fin.read(ivbytes, 0, 16);
        //System.out.println(bytearrToString(ivbytes));
        IvParameterSpec iv = new IvParameterSpec(ivbytes);
        c.init(Cipher.DECRYPT_MODE, aeskey, iv);

        cin = new CipherInputStream(fin, c);
        //GZIPInputStream gzin = new GZIPInputStream(cin);
        fout = new FileOutputStream(outFile);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        //System.out.println(fin.available());
        while ((bytesRead = cin.read(buffer)) > 0) { //this loop grabs more of the file and uploads it 4KB  at a time
            System.out.println(bytesRead);
            fout.write(buffer, 0, bytesRead);
        }
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        try {
            cin.close();
            fin.close();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    try {
        FixZip.fixInvalidZipFile(outFile);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

License:Apache License

public static boolean crypto(List<String> args) {
    Security.addProvider(new BouncyCastleProvider());
    keyStorage = new KeyStorage();
    boolean terminate = false;
    if (args.contains("--keygen")) {
        terminate = true;// w w w. ja  v a 2s  .  c om
        try {
            System.out.println("Keys saved into:\n" + keyStorage.genKeys());
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            keyChain = keyStorage.readKeys();
            cryptor = new Cryptor(keyChain);
        } catch (Exception e) {
            System.out.println("Cannot read keys. Generate new keys with --keygen option");
            terminate = true;
        }
    }

    return terminate;
}

From source file:edu.rice.batchsig.bench.BenchSigner.java

License:Apache License

public static void main(String args[]) throws FileNotFoundException, ParseException {
    Security.addProvider(new BouncyCastleProvider());
    try {/*w ww . j  a v  a  2  s.  co  m*/
        BenchSigner bench = new BenchSigner();
        bench.parsecmd(args);
        System.exit(0);

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
}

From source file:edu.tamu.tcat.crypto.bouncycastle.AsymmetricKeyBuilderImpl.java

License:Apache License

@Override
public KeyPair generateECKeyPair(Curve curve) throws CipherException {
    ECParameterSpec spec = ECNamedCurveTable.getParameterSpec(curve.getCurveName());
    try {//ww w .  j av  a  2s. c  o m
        KeyPairGenerator generator = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
        generator.initialize(spec, new SecureRandom());
        return generator.generateKeyPair();
    } catch (Exception e) {
        throw new CipherException(e);
    }
}

From source file:edu.utn.frba.grupo5303.serverenviolibre.services.WSAfipService.java

private byte[] create_cms(String p12file, String p12pass, String signer, String dstDN, String service,
        Long TicketTime) {/*from www.j ava2s .com*/

    PrivateKey pKey = null;
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;
    String LoginTicketRequest_xml;
    String SignerDN = null;

    ArrayList<X509Certificate> certList = null;

    //
    // Manage Keys & Certificates
    //
    try {
        // Create a keystore using keys from the pkcs#12 p12file
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream p12stream = getClass().getResourceAsStream(p12file);
        ks.load(p12stream, p12pass.toCharArray());
        p12stream.close();

        // Get Certificate & Private key from KeyStore
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);
        SignerDN = pCertificate.getSubjectDN().toString();

        // Create a list of Certificates to include in the final CMS
        certList = new ArrayList<X509Certificate>();
        certList.add(pCertificate);

        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (Exception e) {
        logger.log(Level.SEVERE, "---### Exception ###---: {0}", e);
    }

    //
    // Create XML Message
    // 
    LoginTicketRequest_xml = create_LoginTicketRequest(SignerDN, dstDN, service, TicketTime);

    //
    // Create CMS Message
    //
    try {
        // Create a new empty CMS Message
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        // Add a Signer to the Message
        gen.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);

        // Add the Certificate to the Message
        gen.addCertificatesAndCRLs(cstore);

        // Add the data (XML) to the Message
        CMSProcessable data = new CMSProcessableByteArray(LoginTicketRequest_xml.getBytes());

        // Add a Sign of the Data to the Message
        CMSSignedData signed = gen.generate(data, true, "BC");

        asn1_cms = signed.getEncoded();

    } catch (Exception e) {
        logger.log(Level.SEVERE, "---### Exception ###---: {0}", e);
    }

    return (asn1_cms);
}

From source file:edu.utn.frba.grupo5303.wsaacliente.Facturador.java

public String solicitarFECAE() throws CertStoreException, CMSException, NoSuchAlgorithmException,
        NoSuchProviderException, IOException, ServiceException {
    PrivateKey pKey = null;//from w  w w  . j  a  v a 2  s . co  m
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;

    ArrayList<X509Certificate> certList = null;

    //
    // Manage Keys & Certificates
    //
    try {
        // Create a keystore using keys from the pkcs#12 p12file
        KeyStore ks = KeyStore.getInstance("pkcs12");
        FileInputStream p12stream = new FileInputStream(p12file);
        ks.load(p12stream, p12pass.toCharArray());
        p12stream.close();

        // Get Certificate & Private key from KeyStore
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);

        // Create a list of Certificates to include in the final CMS
        certList = new ArrayList<X509Certificate>();
        certList.add(pCertificate);

        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (Exception e) {
        e.printStackTrace();
    }

    String pedido = generarXMLPedido();

    // Create a new empty CMS Message
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    // Add a Signer to the Message
    gen.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);

    // Add the Certificate to the Message
    gen.addCertificatesAndCRLs(cstore);

    // Add the data (XML) to the Message
    CMSProcessable data = new CMSProcessableByteArray(pedido.getBytes());

    //        FECAESolicitar sol = new FECAESolicitar();
    //        sol.setAuth(new FEAuthRequest());
    //        sol.setFeCAEReq(new FECAERequest());        

    // Add a Sign of the Data to the Message
    CMSSignedData signed = gen.generate(data, true, "BC");

    // 
    asn1_cms = signed.getEncoded();

    Service service = new Service();
    Call call = (Call) service.createCall();

    //
    // Prepare the call for the Web service
    //
    call.setTargetEndpointAddress(new java.net.URL("https://wswhomo.afip.gov.ar/wsfev1/service.asmx"));
    call.setOperationName("FECAESolicitar");
    call.addParameter("request", XMLType.XSD_STRING, ParameterMode.IN);
    call.setReturnType(XMLType.XSD_STRING);

    //
    // Make the actual call and assign the answer to a String
    //
    String response = (String) call.invoke(new Object[] { Base64.encode(asn1_cms) });

    return response;
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {/*from  ww  w.  j ava 2  s  . c  o  m*/
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

From source file:ee.ria.xroad.common.TestSecurityUtil.java

License:Open Source License

/**
 * Initializes BouncyCastle security library.
 * Disables specified algorithms when building certpath.
 *///from   www . j  av  a 2  s . c om
public static void initSecurity() {
    // This property disables specified algorithms when building certpath
    // Ultimately, we should load custom security properties file
    // for example, on the command line via -Djava.security.properties.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD5");

    Security.addProvider(new BouncyCastleProvider());

    org.apache.xml.security.Init.init();
}

From source file:eidassaml.starterkit.EidasSaml.java

License:EUPL

/**
 * Inits the OpenSAML library and the EidasSaml Starterkit library.
 * Set BouncyCastleProvider as Security Provider
 * It is nessesary to call this method! 
 * //ww w  . j a  v  a2  s .  c o  m
 * @throws ConfigurationException if there is a problem to init the OpenSAML lib or the eidassaml templates
 */
public static synchronized void Init() throws ConfigurationException {
    if (!isInit) {
        DefaultBootstrap.bootstrap();
        try {
            TemplateLoader.init();
        } catch (IOException e) {
            throw new ConfigurationException(
                    "EidasSaml: Can not init Templateloader. SAML Message will not build correctly!", e);
        }
        Security.addProvider(new BouncyCastleProvider());
        org.apache.xml.security.algorithms.JCEMapper.setProviderId("BC");
        isInit = true;
    }
}

From source file:encryption.AESCrypt.java

License:Open Source License

public static byte[] encrypt(byte[] key_aes, byte[] clean)
        throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    SecretKey secret = new SecretKeySpec(key_aes, "AES");
    Cipher cipher;/*from w w  w .  j  av  a 2 s  . c  om*/
    try {
        if (Core.PROVIDER.equals(Core.SPONGEY_CASTLE))
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding",
                    new org.spongycastle.jce.provider.BouncyCastleProvider());
        else
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
        return cipher.doFinal(clean);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}