neuhalje/bouncy-gpg

Empty key rings

Closed this issue · 3 comments

Does it make sense to support empty key rings? If I'm encrypting something, I presumably only need the recipient's public key to do so. Likewise, if I'm decrypting something, I only need my secret key.

This seems to be possible with GPG on the command line. Is my understanding not correct?

Hi Mark,

empty keyrings can be created by calling KeyringConfigs.forGpgExportedKeys(...).

The following test does exactly that:

  @Test
  public void encryptWithOnlyPubkeyInRing_decryptWithOnlyPrivKeyInring_yieldsOriginalPlaintext()
      throws IOException, PGPException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException {

    final byte[] ciphertext;
    {
      ByteArrayOutputStream result = new ByteArrayOutputStream();
      BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(result);

      final InMemoryKeyring encryptionKeyring = KeyringConfigs
          .forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
      encryptionKeyring.addPublicKey(ExampleMessages.PUBKEY_RECIPIENT.getBytes());

      final OutputStream outputStream = BouncyGPG
          .encryptToStream()
          .withConfig(encryptionKeyring)
          .withAlgorithms(algorithmSuite)
          .toRecipient("recipient@example.com")
          .andDoNotSign()
          .binaryOutput()
          .andWriteTo(bufferedOutputStream);

      final InputStream is = new ByteArrayInputStream(
          ExampleMessages.IMPORTANT_QUOTE_TEXT.getBytes());
      Streams.pipeAll(is, outputStream);
      outputStream.close();
      bufferedOutputStream.close();
      is.close();
      ciphertext = result.toByteArray();
    }

    // Decrypt

    {
      final InMemoryKeyring decryptionKeyring = KeyringConfigs
          .forGpgExportedKeys(KeyringConfigCallbacks.withPassword("recipient"));
      decryptionKeyring.addSecretKey(ExampleMessages.SECRET_KEY_RECIPIENT.getBytes());

      final ByteArrayOutputStream plainBA = new ByteArrayOutputStream();

      final InputStream plainIS = BouncyGPG.decryptAndVerifyStream()
          .withConfig(decryptionKeyring)
          .andIgnoreSignatures()
          .fromEncryptedInputStream(new ByteArrayInputStream(ciphertext));

      Streams.pipeAll(plainIS, plainBA);

      assertArrayEquals(ExampleMessages.IMPORTANT_QUOTE_TEXT.getBytes(), plainBA.toByteArray());
    }
  }

cheers
Jens

Just tested in my project, works great so far. Is that code among the example code? If not, it should be, super helpful.