Example usage for org.bouncycastle.openssl PEMParser PEMParser

List of usage examples for org.bouncycastle.openssl PEMParser PEMParser

Introduction

In this page you can find the example usage for org.bouncycastle.openssl PEMParser PEMParser.

Prototype

public PEMParser(Reader reader) 

Source Link

Document

Create a new PEMReader

Usage

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

License:Apache License

/**
 * Create a token encrypter and decrypter using the specified {@link Reader}, note the
 * caller is responsible for closing the Reader.
 * /*from w  w  w  . jav a 2  s  .  c om*/
 * @param privateKeyReader Reader to load the {@link KeyPair} from
 */
@SuppressWarnings("resource")
public BouncyCastleTokenDecrypter(Reader privateKeyReader) throws IOException {
    this((PEMKeyPair) new PEMParser(privateKeyReader).readObject());
}

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

License:Apache License

@Test
public void testCreateWriteAndReadBackKey() throws Exception {
    // Create ServiceKey
    final KeyPair kp = this.keysKeeper.createServiceKey("example.com", 2048, "username");
    assertNotNull(kp);//from   w w w. j  a v  a  2  s . co  m

    // Step 3: Read ServiceKey from filesystem
    ServiceKey foundKey = keysKeeper.getServiceKey("example.com");
    assertNotNull(foundKey);

    // Compare original ServiceKey content with new ServiceKey read from filesystem
    assertEquals("example.com", foundKey.getServiceName());
    assertEquals("username", foundKey.getCreatedByNetId());
    assertEquals(2048, foundKey.getKeyLength());
    //Verify created in same minute
    assertEquals(DateTime.now().minuteOfHour().roundFloorCopy(),
            foundKey.getDayCreated().minuteOfHour().roundFloorCopy());
    assertNotNull(foundKey.getFileEncrypter());
    assertNotNull(foundKey.getTokenEncrypter());

    final File keyFile = foundKey.getKeyFile();
    assertNotNull(keyFile);

    @SuppressWarnings("resource")
    PEMParser pemParser = new PEMParser(new FileReader(keyFile));
    Object object = pemParser.readObject();
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    final PublicKey actualPublicKey = converter.getPublicKey((SubjectPublicKeyInfo) object);

    assertArrayEquals(kp.getPublic().getEncoded(), actualPublicKey.getEncoded());
}

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");
    }//  w ww  .ja  v  a2s  . com

    // 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 send_cert_pem(File f, int num) throws Exception {
    PEMParser pem = new PEMParser(new InputStreamReader(new FileInputStream(f)));
    X509CertificateHolder crt = (X509CertificateHolder) pem.readObject();
    pem.close();//  w  w w  . ja  va  2s.  com
    send_cert(crt.getEncoded(), num);
}

From source file:esteidhacker.FakeEstEID.java

License:Open Source License

public void send_key_pem(File f, int num) throws Exception {
    PEMParser pem = new PEMParser(new InputStreamReader(new FileInputStream(f)));
    // OpenSSL genrsa makes a key pair.
    Object o = pem.readObject();//  w  ww .j  a  v a2s  .c  o  m
    RSAPrivateCrtKey key;
    if (o instanceof org.bouncycastle.openssl.PEMKeyPair) {
        PEMKeyPair pair = (PEMKeyPair) o;
        JcaPEMKeyConverter convert = new JcaPEMKeyConverter();
        key = (RSAPrivateCrtKey) convert.getPrivateKey(pair.getPrivateKeyInfo());
    } else {
        key = (RSAPrivateCrtKey) pem.readObject();
    }
    pem.close();
    send_key(key, num);
}

From source file:esteidhacker.FakeEstEIDCA.java

License:Open Source License

private X509CertificateHolder getRealCert(String path) throws IOException {
    PEMParser pem = new PEMParser(new InputStreamReader(getClass().getResourceAsStream(path)));
    X509CertificateHolder crt = (X509CertificateHolder) pem.readObject();
    pem.close();// www  .j a va  2 s. com
    return crt;
}

From source file:fr.treeptik.cloudunit.utils.KeyStoreUtils.java

License:Apache License

private static <T> T loadPEM(String keyPath) throws IOException {
    PEMParser parser = new PEMParser(new BufferedReader(new FileReader(keyPath)));
    return (T) parser.readObject();
}

From source file:google.registry.testing.sftp.TestSftpServer.java

License:Open Source License

@Nullable
private static KeyPair createKeyPair(String key) {
    try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
        PEMKeyPair pemPair = (PEMKeyPair) pemParser.readObject();
        KeyPair result = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair);
        logger.info("Read key pair " + result);
        return result;
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Couldn't read key pair from string(!)", e);
        return null;
    }/*from  w  w w.  jav  a2 s .  com*/
}

From source file:io.apigee.trireme.crypto.algorithms.DsaKeyPairProvider.java

License:Open Source License

/**
 * DSA public key format -- the PEM file contains a "SubjectPublicKeyInfo" object, which contains
 * an "Algorithm Identifier" that consists of three integers (p, q, and g) and a single
 * integer representing y. We use those four parts to assemble a Java public key.
 *///from w ww . j ava  2s. c  o  m
@Override
public PublicKey readPublicKey(String algorithm, Reader rdr) throws CryptoException, IOException {
    PEMParser pp = new PEMParser(rdr);
    try {
        Object po = pp.readObject();
        if (log.isDebugEnabled()) {
            log.debug("Trying to read an {} public key and got {}", algorithm, po);
        }

        if (po instanceof SubjectPublicKeyInfo) {
            SubjectPublicKeyInfo pk = (SubjectPublicKeyInfo) po;

            AlgorithmIdentifier alg = pk.getAlgorithm();
            if (!(alg.getParameters() instanceof ASN1Sequence)) {
                throw new CryptoException("Invalid DSA public key format: Algorithm ID not a Sequence");
            }

            ASN1Sequence identifiers = (ASN1Sequence) (alg.getParameters());
            if (identifiers.size() != 3) {
                throw new CryptoException("Invalid DSA public key format: Identifier does not have 3 items");
            }

            DERInteger p = (DERInteger) identifiers.getObjectAt(0);
            DERInteger q = (DERInteger) identifiers.getObjectAt(1);
            DERInteger g = (DERInteger) identifiers.getObjectAt(2);

            ASN1Primitive pkPrim = pk.parsePublicKey();
            if (!(pkPrim instanceof ASN1Integer)) {
                throw new CryptoException("Invalid DSA public key format: Public key is not an integer");
            }
            DERInteger y = (DERInteger) pkPrim;

            try {
                KeyFactory factory = KeyFactory.getInstance("DSA");
                DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(),
                        g.getValue());
                return factory.generatePublic(pubSpec);
            } catch (GeneralSecurityException gse) {
                throw new CryptoException(gse);
            }
        }
        throw new CryptoException("Input data does not contain a public key");
    } finally {
        pp.close();
    }
}

From source file:io.apigee.trireme.crypto.algorithms.RsaKeyPairProvider.java

License:Open Source License

@Override
public KeyPair readKeyPair(String algorithm, Reader rdr, char[] passphrase)
        throws CryptoException, IOException {
    PEMParser pp = new PEMParser(rdr);
    try {//ww  w.  jav a 2s.c o  m
        Object po = pp.readObject();
        if (log.isDebugEnabled()) {
            log.debug("Trying to read an {} key pair and got {}", algorithm, po);
        }

        if (po instanceof PEMKeyPair) {
            return convertKeyPair((PEMKeyPair) po);
        }
        if (po instanceof PEMEncryptedKeyPair) {
            PEMDecryptorProvider dec = new JcePEMDecryptorProviderBuilder().build(passphrase);
            PEMKeyPair kp = ((PEMEncryptedKeyPair) po).decryptKeyPair(dec);
            return convertKeyPair(kp);
        }
        throw new CryptoException("Input data does not contain a key pair");
    } finally {
        pp.close();
    }
}