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:de.willuhn.jameica.security.JameicaTrustManager.java

License:Open Source License

/**
 * ct.//  ww w .  ja  v  a  2s  . c  om
 * @throws KeyStoreException
 * @throws Exception
 */
public JameicaTrustManager() throws KeyStoreException, Exception {
    this.validator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);

    if (Application.getConfig().getTrustJavaCerts()) {
        Logger.info("trusting java trustmanager");
        this.parentTrustManager = getSystemTrustManager();
    } else {
        Logger.info("system trustmanager disabled, will use only jameicas trustmanager");
    }
}

From source file:dorkbox.util.crypto.Crypto.java

License:Apache License

public static void addProvider() {
    // make sure we only add it once (in case it's added elsewhere...)
    Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (provider == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from   w  ww  . java 2  s .c o m*/
}

From source file:ec.rubrica.ocsp.ValidadorOCSP.java

License:Open Source License

public static void check(X509Certificate issuerCert, X509Certificate x509Cert)
        throws OcspValidationException, OcspTimeoutException {
    try {// www. ja  va 2  s .  c o m
        BigInteger serialNumber = x509Cert.getSerialNumber();
        X509CertificateHolder holder;

        try {
            holder = new X509CertificateHolder(issuerCert.getEncoded());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build().get(CertificateID.HASH_SHA1), holder,
                serialNumber);

        OCSPReqBuilder ocspGen = new OCSPReqBuilder();
        ocspGen.addRequest(id);
        OCSPReq ocspReq = ocspGen.build();

        // Ir al OCSP
        String ocspUrl = CertificateUtil.getOCSPURL(x509Cert);

        if (ocspUrl == null) {
            logger.info("URL de OCSP is null");
            return;
        }

        URL url;

        try {
            url = new URL(ocspUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        HttpURLConnection con;
        OCSPResp ocspResponse;

        try {
            con = (HttpURLConnection) url.openConnection();

            con.setRequestProperty("Content-Type", "application/ocsp-request");
            con.setRequestProperty("Accept", "application/ocsp-response");
            con.setDoOutput(true);

            OutputStream out = con.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
            dataOut.write(ocspReq.getEncoded());

            dataOut.flush();
            dataOut.close();

            /*
             * Se parsea la respuesta y se obtiene el estado del certificado
             * retornado por el OCSP
             */
            InputStream in = (InputStream) con.getContent();
            byte[] resp = read(in); // Read the reponse
            ocspResponse = new OCSPResp(resp);
        } catch (IOException e) {
            throw new OcspTimeoutException(url);
        }

        int status = ocspResponse.getStatus();
        System.out.println("status=" + status);

        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        if (basicResponse != null) {
            SingleResp[] responses = basicResponse.getResponses();
            SingleResp response = responses[0];
            CertificateStatus certStatus = response.getCertStatus();

            if (certStatus instanceof RevokedStatus) {
                System.out.println("REVOKED");
                RevokedStatus revokedStatus = (RevokedStatus) certStatus;
                System.out.println("Reason: " + revokedStatus.getRevocationReason());
                System.out.println("Date: " + revokedStatus.getRevocationTime());

                throw new OcspValidationException(revokedStatus.getRevocationReason(),
                        revokedStatus.getRevocationTime());
            }
        }
    } catch (OCSPException e) {
        throw new RuntimeException(e);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmadorPdf.java

License:Open Source License

public byte[] firmar(PrivateKey pk, X509Certificate certificado, String razon, String ubicacion)
        throws IOException {
    try {/*from   w w  w. ja va  2 s .c om*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);

        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason(razon);
        appearance.setLocation(ubicacion);

        Rectangle pageSize = reader.getPageSize(1);
        Rectangle position = new Rectangle(15, pageSize.getHeight() - 50, 250, pageSize.getHeight());
        appearance.setVisibleSignature(position, 1, "sig");

        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        Certificate[] chain = new Certificate[] { certificado };

        MakeSignature.signDetached(appearance, pks, chain, null, null, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

public static byte[] firmar(byte[] pdf, PrivateKey pk, Certificate[] chain, TSAClient tsaClient)
        throws IOException {
    try {/* w ww. j  a  v  a2 s . c  o m*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);
        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason("Testing");
        appearance.setLocation("Quito");
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");

        // Creating the signature
        PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        OcspClient ocsp = new OcspClientBouncyCastle();

        MakeSignature.signDetached(appearance, pks, chain, null, ocsp, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

/**
 * TODO: Mas de dos firmas?/*from ww w. j a  va2s  . c  om*/
 * 
 * @param pdf
 * @throws IOException
 * @throws SignatureException
 */
public static boolean verificar(byte[] pdf) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(pdf);
    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();

    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        System.out.println("Signature name: " + name);
        System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        PdfPKCS7 pk = af.verifySignature(name);
        Calendar cal = pk.getSignDate();
        Certificate[] pkc = pk.getCertificates();
        TimeStampToken ts = pk.getTimeStampToken();

        if (ts != null) {
            cal = pk.getTimeStampDate();
        }

        if (!pk.isTsp() && ts != null) {
            boolean impr;
            try {
                impr = pk.verifyTimestampImprint();
                System.out.println("Timestamp imprint verifies: " + impr);
                System.out.println("Timestamp date: " + cal);
            } catch (NoSuchAlgorithmException e) {
                throw new SignatureException(e);
            }
        }

        System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
        System.out.println("Document modified: " + !pk.verify());

        KeyStore kall = KeyStoreUtil.loadCacertsKeyStore();

        Object fails[] = CertificateVerification.verifyCertificates(pkc, kall, null, cal);

        if (fails == null) {
            System.out.println("Certificates verified against the KeyStore");
        } else {
            System.out.println("Certificate failed: " + fails[0]);
            return false;
        }

        BasicOCSPResp ocsp = pk.getOcsp();

        if (ocsp != null) {
            try {
                X509Certificate cert = new SecurityDataSubCaCert();

                boolean verifies = ocsp.isSignatureValid(new JcaContentVerifierProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert.getPublicKey()));

                System.out.println("OCSP signature verifies: " + verifies);

                System.out.println("OCSP revocation refers to this certificate: " + pk.isRevocationValid());

                return verifies;
            } catch (OperatorCreationException e) {
                throw new SignatureException(e);
            } catch (OCSPException e) {
                throw new SignatureException(e);
            }
        } else {
            return true;
        }
    }

    return false;
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleKeyPairGenerator.java

License:Apache License

@Override
public KeyPair generateKeyPair(Integer keyLength) {
    final KeyPairGenerator kpg;
    try {//www.  ja v  a2 s.  c om
        kpg = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("RSA support could not be found. There is a problem with this JVM.", e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException(
                "BounceCastle support could not be found. There is a problem with this JVM.", e);
    }

    kpg.initialize(keyLength);
    return kpg.generateKeyPair();
}

From source file:esteidhacker.CLI.java

License:Open Source License

public static void main(String argv[]) throws Exception {

    String pin1 = EstEID.PIN1String;
    String pin2 = EstEID.PIN2String;
    String puk = EstEID.PUKString;

    OptionSet args = parseArguments(argv);

    // Do the work, based on arguments
    if (args.has(OPT_VERSION)) {
        System.out.println("EstEID hacker v0.1");
    }//ww  w .  ja v  a 2  s. c o m

    // Load or generate a CA
    FakeEstEIDCA ca = new FakeEstEIDCA();
    if (args.has(OPT_CA)) {
        File f = (File) args.valueOf(OPT_CA);
        if (!f.exists()) {
            ca.generate();
            ca.storeToFile(f);
        } else {
            ca.loadFromFile(f);
        }
    } else if (args.has(OPT_EMULATE)) {
        ca.generate();
    } else if (args.has(OPT_NEW) || args.has(OPT_GENAUTH) || args.has(OPT_GENSIGN) || args.has(OPT_RESIGN)) {
        throw new IllegalArgumentException("Need a CA!");
    }

    if (args.has(OPT_PIN1)) {
        pin1 = (String) args.valueOf(OPT_PIN1);
    }
    if (args.has(OPT_PIN2)) {
        pin2 = (String) args.valueOf(OPT_PIN2);
    }
    if (args.has(OPT_PUK)) {
        puk = (String) args.valueOf(OPT_PUK);
    }

    if (args.has(OPT_RESIGN)) {
        File f = (File) args.valueOf(OPT_RESIGN);
        PEMParser pem = new PEMParser(new FileReader(f));
        X509Certificate crt = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate((X509CertificateHolder) pem.readObject());
        pem.close();

        X509Certificate newcert = ca.cloneUserCertificate((RSAPublicKey) crt.getPublicKey(), crt);
        JcaPEMWriter wr = new JcaPEMWriter(new OutputStreamWriter(System.out));
        wr.writeObject(newcert);
        wr.close();
    }

    Card card = null;
    CardTerminal term = null;

    try {
        if (args.has(OPT_EMULATE)) {
            // Load FakeEstEIDApplet into vJCRE emulator
            VRE vre = VRE.getInstance();
            VRE.debugMode = false;

            AID aid = AID.fromBytes(FakeEstEIDApplet.aid);
            vre.load(FakeEstEIDApplet.class, aid);
            vre.install(aid, true);
            // Establish connection to the applet
            term = TerminalFactory.getInstance("PC/SC", vre, new VJCREProvider()).terminals().list().get(0);
        } else {
            if (args.has(OPT_LIST)) {
                TerminalFactory tf = TerminalManager.getTerminalFactory(true);
                CardTerminals terms = tf.terminals();
                for (CardTerminal t : terms.list()) {
                    EstEID eid = EstEID.getInstance(t);
                    String s = "";
                    if (t.isCardPresent()) {
                        s = ": not EstEID";
                        CardType ct = eid.identify();
                        if (ct != null) {
                            s = ": " + ct.toString();
                        }
                    }
                    System.out.println((t.isCardPresent() ? "[*] " : "[ ] ") + t.getName() + s);
                }
            } else {
                // Connect to a real card
                term = TerminalManager.getTheReader();
            }
        }

        if (args.has(OPT_DEBUG))
            term = LoggingCardTerminal.getInstance(term);

        if (args.has(OPT_CLONE)) {
            // Connect to card.
            System.out.println("Enter card you want to clone and press enter.");
            System.console().readLine();

            EstEID esteid = EstEID.getInstance(term);
            esteid.identify();
            // Read certificates
            X509Certificate authcert = esteid.readAuthCert();
            X509Certificate signcert = esteid.readSignCert();
            // Read personal data file
            HashMap<PersonalData, String> pdf = new HashMap<PersonalData, String>();
            for (PersonalData pd : PersonalData.values()) {
                pdf.put(pd, esteid.getPersonalData(pd));
            }

            esteid.getCard().disconnect(false);
            System.out.println("Enter card with FakeEstEID and press enter.");
            System.console().readLine();
            // XXX: this identify requirement and accessing fake via esteid is silly
            esteid = EstEID.getInstance(term);
            esteid.identify();
            FakeEstEID fake = FakeEstEID.getInstance(esteid);
            fake.send_cert(authcert.getEncoded(), 1);
            fake.send_cert(signcert.getEncoded(), 2);
            // Generate random keys
            fake.send_new_key(1);
            fake.send_new_key(2);
            // Wipe personal data
            CommandAPDU wipe = new CommandAPDU(0x80, 0x04, 0x00, 0x01);
            esteid.getCard().getBasicChannel().transmit(wipe);

            // Store basic data
            for (PersonalData pd : PersonalData.values()) {
                CommandAPDU cmd = new CommandAPDU(0x80, 0x04, pd.getRec(), 0x00,
                        pdf.get(pd).getBytes("ISO8859-15"));
                esteid.getCard().getBasicChannel().transmit(cmd);
            }
            esteid.getCard().disconnect(true);
        }

        if (args.has(OPT_INSTALL)) {
            // Install the applet
            Card c = term.connect("*");
            GlobalPlatform gp = new GlobalPlatform(c.getBasicChannel());
            gp.imFeelingLucky();
            gp.uninstallDefaultSelected(true);
            System.err.println("Use GP utility directly for loading");
            TerminalManager.disconnect(c, true);
        }

        EstEID esteid = EstEID.getInstance(term);
        esteid.identify();

        if (args.has(OPT_RELAX)) {
            esteid.strict = false;
        }

        if (args.has(OPT_VERBOSE) || args.has(OPT_INFO)) {
            System.out.println("ATR: " + HexUtils.encodeHexString(esteid.getCard().getATR().getBytes()));
            System.out.println("Type: " + esteid.getType());
        }

        FakeEstEID fake = FakeEstEID.getInstance(esteid);

        if (args.has(OPT_AUTHCERT)) {
            File f = (File) args.valueOf(OPT_AUTHCERT);
            fake.send_cert_pem(f, 1);
        }

        if (args.has(OPT_SIGNCERT)) {
            File f = (File) args.valueOf(OPT_SIGNCERT);
            fake.send_cert_pem(f, 2);
        }

        if (args.has(OPT_AUTHKEY)) {
            File f = (File) args.valueOf(OPT_AUTHKEY);
            fake.send_key_pem(f, 1);
        }

        if (args.has(OPT_SIGNKEY)) {
            File f = (File) args.valueOf(OPT_SIGNKEY);
            fake.send_key_pem(f, 2);
        }

        if (args.has(OPT_GENAUTH)) {
            fake.send_new_key(1);
        }

        if (args.has(OPT_GENSIGN)) {
            fake.send_new_key(2);
        }

        if (args.has(OPT_NEW) || args.has(OPT_EMULATE)) {
            fake.make_sample_card(ca, args.has(OPT_CHECK));
        }

        // FIXME: this is ugly and bad code.
        if (args.has(OPT_DATA)) {
            for (PersonalData pd : PersonalData.values()) {
                CommandAPDU cmd = new CommandAPDU(0x80, 0x04, pd.getRec(), 0x00, 256);
                ResponseAPDU resp = esteid.getCard().getBasicChannel().transmit(cmd);
                String value = new String(resp.getData(), Charset.forName("ISO8859-15"));
                System.out.println("Enter new value (for " + pd.name() + "): " + value);
                String input = System.console().readLine();
                cmd = new CommandAPDU(0x80, 0x04, pd.getRec(), 0x00, input.getBytes("ISO8859-15"));
                esteid.getCard().getBasicChannel().transmit(cmd);
            }
        }

        // Following assumes a "ready" card (-new).
        if (args.has(OPT_INFO)) {
            Map<PIN, Byte> counts = esteid.getPINCounters();

            System.out.print("PIN tries remaining:");
            for (PIN p : PIN.values()) {
                System.out.print(" " + p.toString() + ": " + counts.get(p) + ";");
            }
            System.out.println();

            String docnr = esteid.getPersonalData(PersonalData.DOCUMENT_NR);
            System.out.println("Doc#: " + docnr);
            if (!docnr.startsWith("N")) {
                System.out.println("Cardholder: " + esteid.getPersonalData(PersonalData.GIVEN_NAMES1) + " "
                        + esteid.getPersonalData(PersonalData.SURNAME));
            }
            X509Certificate authcert = esteid.readAuthCert();
            System.out.println("Certificate subject: " + authcert.getSubjectDN());
        }

        if (args.has(OPT_TEST_PINS) || args.has(OPT_TEST)) {
            if (args.has(OPT_PIN1) ^ args.has(OPT_PIN2) || args.has(OPT_PIN2) ^ args.has(OPT_PUK)) {
                System.out.println("Need any or all of PIN options if testing for PINS");
                System.exit(1);
            }
            esteid.pin_tests(pin1, pin2, puk);
        }

        if (args.has(OPT_TEST_CRYPTO) || args.has(OPT_TEST)) {
            esteid.crypto_tests(pin1, pin2);
        }
    } catch (Exception e) {
        if (TerminalManager.getExceptionMessage(e) != null) {
            System.out.println("PC/SC Error: " + TerminalManager.getExceptionMessage(e));
        } else {
            throw e;
        }
    } finally {
        if (card != null) {
            TerminalManager.disconnect(card, true);
        }
    }
}

From source file:esteidhacker.FakeEstEID.java

License:Open Source License

public void make_sample_card(FakeEstEIDCA ca, boolean check) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    keyGen.initialize(2048);/*from w w  w  . j  a v  a 2  s  . c  om*/
    // Generate keys
    KeyPair auth = keyGen.generateKeyPair();
    KeyPair sign = keyGen.generateKeyPair();
    X509Certificate authcert = ca.generateUserCertificate((RSAPublicKey) auth.getPublic(), false, "SIILIPOISS",
            "UDUS", "10101010005", "kalevipoeg@soome.fi");
    X509Certificate signcert = ca.generateUserCertificate((RSAPublicKey) sign.getPublic(), true, "SIILIPOISS",
            "UDUS", "10101010005", "kalevipoeg@soome.fi");
    if (check) {
        // Verify softkeys
        if (!verifyKeypairIntegrity((RSAPrivateCrtKey) auth.getPrivate(),
                (RSAPublicKey) authcert.getPublicKey())) {
            throw new RuntimeCryptoException("Cert and key mismatch");
        }
        if (!verifyKeypairIntegrity((RSAPrivateCrtKey) sign.getPrivate(),
                (RSAPublicKey) signcert.getPublicKey())) {
            throw new RuntimeCryptoException("Cert and key mismatch");
        }
    }
    send_key((RSAPrivateCrtKey) auth.getPrivate(), 1);
    send_key((RSAPrivateCrtKey) sign.getPrivate(), 2);
    send_cert(authcert.getEncoded(), 1);
    send_cert(signcert.getEncoded(), 2);

    CommandAPDU cmd = null;
    ResponseAPDU resp = null;
    if (check) {
        // Verify on-card keys.
        Cipher verify_cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
        byte[] rnd = new byte[8];

        r.nextBytes(rnd);
        cmd = new CommandAPDU(0x00, 0x88, 0x00, 0x00, rnd, 256);
        resp = channel.transmit(cmd);
        check(resp);
        verify_cipher.init(Cipher.DECRYPT_MODE, authcert.getPublicKey());
        byte[] result = verify_cipher.doFinal(resp.getData());
        if (!java.util.Arrays.equals(rnd, result)) {
            throw new RuntimeCryptoException("Card and auth key don't match!");
        }

        r.nextBytes(rnd);
        cmd = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, rnd, 256);
        resp = channel.transmit(cmd);
        check(resp);
        verify_cipher.init(Cipher.DECRYPT_MODE, signcert.getPublicKey());
        result = verify_cipher.doFinal(resp.getData());
        if (!java.util.Arrays.equals(rnd, result)) {
            throw new RuntimeCryptoException("Card and sign key don't match!");
        }
    }
    // Dump default data file
    for (int i = 0; i < defaultDataFile.length; i++) {
        cmd = new CommandAPDU(0x80, 0x04, i + 1, 0x00, defaultDataFile[i].toUpperCase().getBytes("ISO8859-15"));
        resp = channel.transmit(cmd);
        check(resp);
    }
}

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);
}