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:aff4.commonobjects.AuthorityReader.java

License:Open Source License

public void init() throws IOException, ParseException {
    Security.addProvider(new BouncyCastleProvider());
    Reader dev = volume.open(Node.createURI(URN.getURI() + "/cert.pem"));
    PEMReader pemReader = new PEMReader(new InputStreamReader(new ReaderInputStream(dev)));
    X509Certificate cert = (X509Certificate) pemReader.readObject();
    dev.close();//from  www. j  av  a2  s .c  o  m

    publicKey = cert.getPublicKey();
}

From source file:aff4.commonobjects.AuthorityWriter.java

License:Open Source License

public void setPrivateCert(String certificateFilePath) throws IOException {
    Security.addProvider(new BouncyCastleProvider());
    InputStream dev = new FileInputStream(certificateFilePath);
    PEMReader pemReader = new PEMReader(new InputStreamReader(dev));
    KeyPair keyPair = (KeyPair) pemReader.readObject();

    dev.close();/*from  w  ww  .  j av a 2s  .c  o m*/
    privateKey = keyPair.getPrivate();
}

From source file:aff4.commonobjects.AuthorityWriter.java

License:Open Source License

public void setPublicCert(String certificateFilePath) throws IOException {
    Security.addProvider(new BouncyCastleProvider());
    InputStream dev = new FileInputStream(certificateFilePath);
    dev.close();//  w  w w . ja va 2  s.  com
    dev = new FileInputStream(certificateFilePath);

    Resource URN = getURN();
    String name = URLEncoder.encode(URN.getURI(), "UTF-8") + "/cert.pem";

    OutputStream certwriter = container.createOutputStream(name, true, dev.available());
    byte[] buf = new byte[1024];
    while (dev.available() > 0) {
        int res = dev.read(buf);
        certwriter.write(buf, 0, res);
    }
    dev.close();
    certwriter.close();
    container.add(container.getGraph(), URN, AFF4.publicKeyCertificate,
            Node.createURI(URN.getURI() + "/cert.pem"));
    //PublicKey pk = cert.getPublicKey();
}

From source file:aff4.commonobjects.WarrantReader.java

License:Open Source License

public boolean isValid() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException,
        TooManyValuesException, ParseException {

    Resource warrantURN = URN;/*from  w w  w  . ja  va 2s.  com*/
    Resource authority = (Resource) QueryTools.queryValue(volume, Node.ANY, warrantURN, AFF4.authority);

    boolean verified = false;

    Resource warrantGraph = volume.query(Node.ANY, warrantURN, AFF4.type, AFF4.Warrant).get(0).getGraph();

    QuadList signedStatements = volume.query(warrantGraph, Node.ANY, Node.ANY, Node.ANY);
    GraphCanonicalizer standardiser = new GraphCanonicalizer(signedStatements);
    String canonicalData = standardiser.getCanonicalString();

    byte[] bytes = canonicalData.getBytes("UTF-8");
    AuthorityReader authorityReader = new AuthorityReader(volume, authority);

    Signature signature = Signature.getInstance("SHA256withRSA", new BouncyCastleProvider());
    signature.initVerify(authorityReader.publicKey);
    signature.update(bytes);

    String sig = ((Literal) QueryTools.queryValue(volume, Node.ANY, warrantGraph, AFF4.signature)).asString();
    byte[] signatureBytes = Base64.decode(sig);
    if (!signature.verify(signatureBytes)) {
        return false;
    }

    HashDigestAdapter hasher = new HashDigestAdapter(new SHA256Digest());
    QuadList graphs = volume.query(Node.ANY, Node.ANY, AFF4.assertedBy, warrantURN);
    for (Quad graph : graphs) {
        Resource subjectGraph = graph.getSubject();
        if (!subjectGraph.equals(warrantGraph)) {
            //String digestMethod = ((Literal)QueryTools.queryValue(volume, Node.ANY, subjectGraph, AFF4.digestMethod)).asString();
            String digest = ((Literal) QueryTools.queryValue(volume, Node.ANY, subjectGraph, AFF4.hash))
                    .asString();

            QuadList statements = volume.query(subjectGraph, null, null, null);
            standardiser = new GraphCanonicalizer(statements);
            hasher.reset();
            hasher.update(standardiser.getCanonicalString());
            hasher.doFinal();

            String calculatedHash = hasher.getStringValue();
            if (!calculatedHash.equals(digest)) {
                return false;
            } else {
                assertions.add(subjectGraph);
            }
        }
    }

    return true;

}

From source file:aff4.commonobjects.WarrantWriter.java

License:Open Source License

public static String calculateSignature(String canonicalGraph, PrivateKey key)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException

{
    Security.addProvider(new BouncyCastleProvider());
    String signature = null;/*from   www. j  a v  a2s .c  om*/
    Signature sig = Signature.getInstance("SHA256withRSA", new BouncyCastleProvider());
    sig.initSign(key);
    sig.update(canonicalGraph.getBytes("UTF-8"));
    signature = new String(Base64.encode(sig.sign()), "UTF-8");
    return signature;
}

From source file:aff4.commonobjects.WarrantWriter.java

License:Open Source License

static String digest(String data) throws UnsupportedEncodingException {
    Security.addProvider(new BouncyCastleProvider());
    HashDigestAdapter digest = new HashDigestAdapter(new SHA256Digest());
    digest.update(data);/*from w w w. j a  v a  2s . co m*/
    digest.doFinal();

    return digest.getStringValue();
}

From source file:app.EmailProxy.java

License:Open Source License

/**
 * <p>The constructor.</p>//from  w  w  w.  j  a  v a2  s. c  o m
 * <p>Starts the proxy server threads and sets up the gui.</p>
 * @param configFile The path and filename of the config file where the proxy loads and saves extra configuration information.
 */
public EmailProxy(String configFile) {

    // Register cleanup handler
    Runtime.getRuntime().addShutdownHook(this);

    // Load settings
    try {
        configData = new ConfigurationData(configFile);
    } catch (IOException e) {
        System.err.println("Could not load configuration data : " + e.getMessage());
        System.exit(0);
    }

    // Starting GUI & redirecting stdout & stderr if hideGUI is false
    MainWindow mainWindow = new MainWindow(configData);
    StatusOutputStream statusWindow = new StatusOutputStream(mainWindow);
    PrintStream stdOut = new PrintStream(statusWindow);
    PrintStream stdErr = new PrintStream(statusWindow);
    System.setOut(stdOut);
    System.setErr(stdErr);
    mainWindow.show();

    // display a short copyright message
    displayCopyrightMessageShort();

    // Construct pipes and start server threads
    try {

        KeyHandler publicKeyManagers[] = null;
        KeyHandler secretKeyManagers[] = null;

        // Create Algorithm Handler
        AlgorithmHandler algorithmHandler = null;
        if (configData.getSetting("algorithm", "openpgp").compareToIgnoreCase("openpgp") == 0) {

            Security.addProvider(new BouncyCastleProvider());

            String symAlg = configData.getSetting("openpgp.symmetricalgorithm.used", "IDEA");
            int symmetricAlgorithm = 0;

            // load defaults
            if ("IDEA".compareToIgnoreCase(symAlg) == 0) {
                symmetricAlgorithm = SymmetricAlgorithmSettings.IDEA;
            } else if ("CAST5".compareToIgnoreCase(symAlg) == 0) {
                symmetricAlgorithm = SymmetricAlgorithmSettings.CAST5;
            } else if ("3DES".compareToIgnoreCase(symAlg) == 0) {
                symmetricAlgorithm = SymmetricAlgorithmSettings.TRIPLEDES;
            } else {
                System.err.println("Symmetric algorithm '" + symAlg + "' is not supported.");
            }

            algorithmHandler = new OpenPGPHandler(symmetricAlgorithm);

            // Load key manager lists
            Vector pubkm = new Vector();
            Vector seckm = new Vector();

            // load base key managers
            pubkm.add(new OpenPGPPublicKeyring(
                    configData.getSetting("keymanager.openpgp.primary.pubring", "pubring.pgp"), null));
            seckm.add(new OpenPGPPublicKeyring(
                    configData.getSetting("keymanager.openpgp.primary.secring", "secring.pgp"), null));

            // load extra key managers
            KeyHandler[] tmp = KeyHandler.loadKeysourceList(configData, "keymanager.openpgp.publiclist.");
            if (tmp != null) {
                for (int n = 0; n < tmp.length; n++)
                    pubkm.add(tmp[n]);
            }

            tmp = KeyHandler.loadKeysourceList(configData, "keymanager.openpgp.secretlist.");
            if (tmp != null) {
                for (int n = 0; n < tmp.length; n++)
                    seckm.add(tmp[n]);
            }

            // store in arrays
            publicKeyManagers = new KeyHandler[pubkm.size()];
            for (int n = 0; n < publicKeyManagers.length; n++)
                publicKeyManagers[n] = (KeyHandler) pubkm.elementAt(n);

            secretKeyManagers = new KeyHandler[seckm.size()];
            for (int n = 0; n < secretKeyManagers.length; n++)
                secretKeyManagers[n] = (KeyHandler) seckm.elementAt(n);
        }

        // Create incoming email pipe

        // Create client side protocol handler
        POP3Handler pop3 = new POP3Handler();
        POP3Handler serverSide = null;
        pop3.initServerConnection(Integer.parseInt(configData.getSetting("proxyserver.incoming.port", "110")));

        // Create server side protocol handler
        if (configData.getSetting("mailserver.incoming.protocol.used", "POP3")
                .compareToIgnoreCase("POP3") == 0) {
            // server side is pop3.. pop3 server is always defined, so i just have to configure it
            serverSide = pop3;
            serverSide.initClientConnection(configData.getSetting("mailserver.incoming.address", ""),
                    Integer.parseInt(configData.getSetting("mailserver.incoming.port", "110")));
        }

        incomingPipe = new IncomingEmailPipe(pop3, algorithmHandler, secretKeyManagers, publicKeyManagers,
                serverSide);

        // Create outgoing SMTP pipe
        SMTPHandler smtp = new SMTPHandler();
        smtp.initClientConnection(configData.getSetting("mailserver.outgoing.address", ""),
                Integer.parseInt(configData.getSetting("mailserver.outgoing.port", "25")));
        smtp.initServerConnection(Integer.parseInt(configData.getSetting("proxyserver.outgoing.port", "25")));

        outgoingPipe = new OutgoingEmailPipe(smtp, algorithmHandler, secretKeyManagers, publicKeyManagers, smtp,
                (configData.getSetting("openpgp.encryptalloutgoingemail", "1").compareTo("1") == 0),
                (configData.getSetting("openpgp.signalloutgoingemail", "1").compareTo("1") == 0));

    } catch (Exception e) {
        System.err.println("Could not create email pipes : " + e.getMessage());
        e.printStackTrace(System.err);
    }

    // Start the pipes
    incomingPipe.start();
    outgoingPipe.start();

}

From source file:Applet.utiles.Utiles.java

/**
 * Se agrega el proveedor de seguridad.
 */
public static void addProvider() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:application.Main.java

License:Open Source License

@Override
public void start(Stage primaryStage) {
    Security.addProvider(new BouncyCastleProvider());
    try {/*from   w w w . j  a va  2s .  c om*/
        Parent root = UiLoader.loadMainUI();
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("yact.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setTitle("YaCT" + " " + version);
        primaryStage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java

License:Apache License

public static void main(String[] args) {
    try {// w  w  w  . j ava2  s .c o  m
        //IMPORTANT HINT REGARDING STRING ENCODING
        //in Java all Strings have UTF-8 as default encoding
        //therefore: there are only a few references to UTF-8 encoding in this demo code
        //however, if values are retrieved from a database or another program language is used, then one needs to
        //make sure that the UTF-8 encoding is correctly implemented

        //this demo cashbox does not implement error handling
        //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible
        //if an error occurs, only the stacktraces are logged
        //obviously this needs to be adapted in a productive cashbox

        //----------------------------------------------------------------------------------------------------
        //basic inits
        //add bouncycastle provider
        Security.addProvider(new BouncyCastleProvider());

        //----------------------------------------------------------------------------------------------------
        //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256
        if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) {
            System.out.println(
                    "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files.");
            System.exit(0);
        }

        //----------------------------------------------------------------------------------------------------
        //parse cmd line options
        Options options = new Options();

        // add CMD line options
        options.addOption("o", "output-dir", true,
                "specify base output directory, if none is specified, a new directory will be created in the current working directory");
        //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)");
        options.addOption("v", "verbose", false, "dump demo receipts to cmd line");
        options.addOption("c", "closed system", false, "simulate closed system");

        Option turnoverCounterLengthOption = Option.builder("l").longOpt("turnover-counter-length")
                .numberOfArgs(1).required(false).type(Number.class).desc("turnover counter length in bytes")
                .build();
        options.addOption(turnoverCounterLengthOption);

        ///parse CMD line options
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        //setup inputs from cmd line
        //verbose
        VERBOSE = cmd.hasOption("v");
        CLOSED_SYSTEM = cmd.hasOption("c");

        //parse and verify turnover counter length
        if (cmd.hasOption("l")) {
            try {
                TURN_OVER_COUNTER_LENGTH_IN_BYTES = ((Number) cmd.getParsedOptionValue("l")).intValue();
                if ((TURN_OVER_COUNTER_LENGTH_IN_BYTES < 5) || (TURN_OVER_COUNTER_LENGTH_IN_BYTES > 8)) {
                    TURN_OVER_COUNTER_LENGTH_IN_BYTES = -1;
                }
            } catch (ParseException e1) {
            }
        }
        if (TURN_OVER_COUNTER_LENGTH_IN_BYTES == -1) {
            System.out.println("turnover counter length in bytes is invalid, using length 8");
            TURN_OVER_COUNTER_LENGTH_IN_BYTES = 8;
        }

        //output directory
        String outputParentDirectoryString = cmd.getOptionValue("o");
        if (outputParentDirectoryString == null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
            outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
        }
        File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
        OUTPUT_PARENT_DIRECTORY.mkdirs();

        //----------------------------------------------------------------------------------------------------
        //external simulation runs... not implemented yet, currently only the internal test suites can be executed
        //String simulationFileOrDirectoryPath = cmd.getOptionValue("i");
        //handling of arbitrary input simulation files will be possible in 0.7
        //if (simulationFileOrDirectoryPath == null) {
        //} else {
        //                File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath);
        //                cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory);
        //}

        List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns();

        //setup simulation and execute
        int index = 1;
        for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) {
            System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size());
            System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel());
            index++;

            File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY,
                    cashboxSimulation.getSimulationRunLabel());
            testSetDirectory.mkdirs();

            CashBoxParameters cashBoxParameters = new CashBoxParameters();
            cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId());
            cashBoxParameters.setTurnOverCounterAESKey(
                    CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey()));
            cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());
            cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule());
            cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID());
            cashBoxParameters.setTurnOverCounterLengthInBytes(TURN_OVER_COUNTER_LENGTH_IN_BYTES);

            //create pre-defined number of signature devices
            for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) {
                JWSModule jwsModule = new ManualJWSModule();
                SignatureModule signatureModule;
                if (!CLOSED_SYSTEM) {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule(
                            RKSuite.R1_AT100, null);
                } else {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule(
                            cashboxSimulation.getCompanyID() + "-" + "K" + i);
                }
                jwsModule.setOpenSystemSignatureModule(signatureModule);
                cashBoxParameters.getJwsSignatureModules().add(jwsModule);
            }

            //init cashbox
            DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

            //exceute simulation run
            demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList());

            //----------------------------------------------------------------------------------------------------
            //export DEP
            DEPExportFormat depExportFormat = demoCashBox.exportDEP();
            //get JSON rep and dump export format to file/std output
            File depExportFile = new File(testSetDirectory, "dep-export.json");
            dumpJSONRepOfObject(depExportFormat, depExportFile, true,
                    "------------DEP-EXPORT-FORMAT------------");

            //----------------------------------------------------------------------------------------------------
            //store signature certificates and AES key (so that they can be used for verification purposes)
            CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer();
            HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>();
            cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap);

            //store AES key as BASE64 String
            //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location
            cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey());
            List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules();
            for (JWSModule jwsSignatureModule : jwsSignatureModules) {
                CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer();
                certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID());
                certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(),
                        certificateOrPublicKeyContainer);
                X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule()
                        .getSigningCertificate();
                if (certificate == null) {
                    //must be public key based... (closed system)
                    PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey();
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(publicKey.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY);
                } else {
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(certificate.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE);
                }
            }

            File cryptographicMaterialContainerFile = new File(testSetDirectory,
                    "cryptographicMaterialContainer.json");
            dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true,
                    "------------CRYPTOGRAPHIC MATERIAL------------");

            //----------------------------------------------------------------------------------------------------
            //export QR codes to file
            //dump machine readable code of receipts (this "code" is used for the QR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            //dump to File
            File qrCoreRepExportFile = new File(testSetDirectory, "qr-code-rep.json");
            List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
            List<String> qrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true,
                    "------------QR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //export OCR codes to file
            //dump machine readable code of receipts (this "code" is used for the OCR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            //dump to File
            File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json");
            List<String> ocrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true,
                    "------------OCR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //create PDF receipts and print to directory
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            File qrCodeDumpDirectory = new File(testSetDirectory, "qr-code-dir-pdf");
            qrCodeDumpDirectory.mkdirs();
            List<byte[]> printedQRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.QR_CODE);
            CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //export receipts as PDF (OCR)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf");
            ocrCodeDumpDirectory.mkdirs();
            List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.OCR);
            CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //dump executed testsuite
            File testSuiteDumpFile = new File(testSetDirectory,
                    cashboxSimulation.getSimulationRunLabel() + ".json");
            dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true,
                    "------------CASHBOX Simulation------------");
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}