Exemplo n.º 1
0
  private void doOpenSslTestFile(String fileName, Class expectedPrivKeyClass) throws IOException {
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMDecryptorProvider decProv =
        new JcePEMDecryptorProviderBuilder().setProvider("BC").build("changeit".toCharArray());
    PEMParser pr = openPEMResource("data/" + fileName);
    Object o = pr.readObject();

    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
      fail("Didn't find OpenSSL key");
    }

    KeyPair kp =
        (o instanceof PEMEncryptedKeyPair)
            ? converter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(decProv))
            : converter.getKeyPair((PEMKeyPair) o);

    PrivateKey privKey = kp.getPrivate();

    if (!expectedPrivKeyClass.isInstance(privKey)) {
      fail("Returned key not of correct type");
    }
  }
Exemplo n.º 2
0
  private void keyPairTest(String name, KeyPair pair) throws IOException {
    PEMParser pemRd;
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut));

    pWrt.writeObject(pair.getPublic());

    pWrt.close();

    pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

    SubjectPublicKeyInfo pub = SubjectPublicKeyInfo.getInstance(pemRd.readObject());
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    PublicKey k = converter.getPublicKey(pub);

    if (!k.equals(pair.getPublic())) {
      fail("Failed public key read: " + name);
    }

    bOut = new ByteArrayOutputStream();
    pWrt = new PEMWriter(new OutputStreamWriter(bOut));

    pWrt.writeObject(pair.getPrivate());

    pWrt.close();

    pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

    KeyPair kPair = converter.getKeyPair((PEMKeyPair) pemRd.readObject());
    if (!kPair.getPrivate().equals(pair.getPrivate())) {
      fail("Failed private key read: " + name);
    }

    if (!kPair.getPublic().equals(pair.getPublic())) {
      fail("Failed private key public read: " + name);
    }
  }