Example usage for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject

List of usage examples for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject

Introduction

In this page you can find the example usage for org.bouncycastle.openssl.jcajce JcaPEMWriter writeObject.

Prototype

public void writeObject(PemObjectGenerator obj) throws IOException 

Source Link

Usage

From source file:com.infinities.skyport.util.RSAUtil.java

License:Apache License

private static String extractPrivateKey(KeyPair keys) throws IOException {
    StringWriter writer = new StringWriter();
    JcaPEMWriter pemWriter = null;
    try {//w  ww.  j  a v  a  2s. c o m
        pemWriter = new JcaPEMWriter(writer);
        pemWriter.writeObject(keys.getPrivate());
    } finally {
        if (pemWriter != null) {
            pemWriter.close();
        }
    }
    return writer.toString();
}

From source file:com.infinities.skyport.vnc.impl.PrivateKeyDecodedTest.java

License:Apache License

@Test
public void testDecoded() throws NoSuchAlgorithmException, JSchException, InvalidKeySpecException, IOException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);/*from w ww.  j a va  2  s  .  com*/
    KeyPair keys = keyGen.genKeyPair();
    StringWriter writer = new StringWriter();
    JcaPEMWriter pemWriter = null;
    try {
        pemWriter = new JcaPEMWriter(writer);
        pemWriter.writeObject(keys.getPrivate());
    } finally {
        if (pemWriter != null) {
            pemWriter.close();
        }
    }

    String privateKeyStr = writer.toString();
    System.out.println(privateKeyStr);
    CustomSession session = new CustomSession("pohsun", "127.0.0.1", 22, "password");
    session.addIdentity("remote", privateKeyStr.getBytes(), null, "");
    // com.jcraft.jsch.KeyPair.load(null,
    // privateKeyStr.getBytes("US-ASCII"), null);
    // PKCS8EncodedKeySpec privspec = new
    // PKCS8EncodedKeySpec(BaseEncoding.base64().decode(base64));
    // KeyFactory factory = KeyFactory.getInstance("RSA");
    // PrivateKey privkey = factory.generatePrivate(privspec);
    // byte[] decoded = BaseEncoding.base64().decode(base64);
    // CustomSession session = new CustomSession("pohsun", "127.0.0.1", 22);
    // session.addIdentity("remote", decoded.getBytes(), null, "");

}

From source file:com.rovemonteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * Converts RSA private key to PEM string.
 *
 * @param rsaKeyPair/*from w  ww . j a  v  a 2  s  . c o m*/
 * @return PEM string
 */
public static String getPEMStringFromRSAKeyPair(final RSAKeyPair rsaKeyPair) {
    final StringWriter pemStrWriter = new StringWriter();
    final JcaPEMWriter pemWriter = new JcaPEMWriter(pemStrWriter);
    try {
        final KeyPair keyPair = new KeyPair(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate());
        pemWriter.writeObject(keyPair.getPrivate());
        pemWriter.close();

    } catch (final IOException e) {
        LOG.warn("Caught exception:" + e.getMessage());
        return "";
    }

    return pemStrWriter.toString();
}

From source file:com.vmware.admiral.common.util.KeyUtil.java

License:Open Source License

public static String toPEMFormat(Key key) {
    StringWriter sw = new StringWriter();
    JcaPEMWriter pemWriter = new JcaPEMWriter(sw);
    try {//from ww  w .j av  a  2 s.  c om
        pemWriter.writeObject(key);
        pemWriter.close();

        return sw.toString();

    } catch (IOException x) {
        throw new RuntimeException("Failed to serialize key", x);
    }
}

From source file:de.petendi.commons.crypto.connector.BCConnector.java

License:Apache License

@Override
public void writeCertificate(Writer pemWriter, X509Certificate selfCert) throws IOException {
    JcaPEMWriter certWriter = new JcaPEMWriter(pemWriter);
    certWriter.writeObject(selfCert);
    certWriter.flush();//from   www  .j a v a2  s .  c  o  m
    certWriter.close();
}

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");
    }//from ww  w.  jav  a2  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.FakeEstEIDCA.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    FakeEstEIDCA ca = new FakeEstEIDCA();
    ca.generate();/*  w ww .  j  a  va  2  s .c o  m*/
    System.out.println("Root: " + ca.rootCert.getSubjectX500Principal().toString());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    // Generate keys
    KeyPair auth = keyGen.generateKeyPair();
    KeyPair sign = keyGen.generateKeyPair();
    X509Certificate authcert = ca.generateUserCertificate((RSAPublicKey) auth.getPublic(), false, "MARTIN",
            "PALJAK", "38207162722", "martin@martinpaljak.net");
    X509Certificate signcert = ca.generateUserCertificate((RSAPublicKey) sign.getPublic(), true, "MARTIN",
            "PALJAK", "38207162722", "martin@martinpaljak.net");

    JcaPEMWriter wr = new JcaPEMWriter(new OutputStreamWriter(System.out));
    wr.writeObject(authcert);
    wr.writeObject(signcert);
    wr.close();
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

License:Open Source License

/**
 * Encodes the current stored information in PEM format and returns it as a {@link String}
 * /* www  .  jav a  2 s  .  c o m*/
 * @return PEM encoded data
 * @throws IOException launched if a problem exists generating the PEM information
 */
@Nonnull
public String encode() throws IOException {
    StringWriter sw = new StringWriter();
    JcaPEMWriter w = new JcaPEMWriter(sw);
    try {
        w.writeObject(object);
    } finally {
        w.close();
    }
    return sw.toString();
}

From source file:mitm.BouncyCastleSslEngineSource.java

License:Apache License

private static void exportPem(File exportFile, Object... certs)
        throws IOException, CertificateEncodingException {
    Writer sw = null;/*from   www . j  a v a2 s . com*/
    JcaPEMWriter pw = null;
    try {
        sw = new FileWriter(exportFile);
        pw = new JcaPEMWriter(sw);
        for (Object cert : certs) {
            pw.writeObject(cert);
            pw.flush();
        }
    } finally {
        IOUtils.closeQuietly(pw);
        IOUtils.closeQuietly(sw);
    }
}

From source file:net.etfbl.cryptodigitalcertificate.tool.util.CryptoPEMExtractor.java

public void writeObject(Object object, String filePath) throws FileNotFoundException, IOException {
    JcaPEMWriter writer = new JcaPEMWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
    try {//from   ww w.ja  v a  2  s  .  c om
        writer.writeObject(object);
    } finally {
        writer.close();
    }
}