org.bouncycastle.openpgp.PGPEncryptedDataList Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPEncryptedDataList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings( "unchecked" )
private static Iterator<PGPPublicKeyEncryptedData> getEncryptedObjects( final byte[] message ) throws IOException
{
    try
    {
        final PGPObjectFactory factory =
                new PGPObjectFactory( PGPUtil.getDecoderStream( new ByteArrayInputStream( message ) ),
                        new JcaKeyFingerprintCalculator() );
        final Object first = factory.nextObject();
        final Object list = ( first instanceof PGPEncryptedDataList ) ? first : factory.nextObject();
        return ( ( PGPEncryptedDataList ) list ).getEncryptedDataObjects();
    }
    catch ( IOException e )
    {
        throw new IOException( e );
    }
}
 
Example #2
Source File: GPGFileDecryptor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Taking in a file inputstream and a passPhrase, generate a decrypted file inputstream.
 * @param inputStream file inputstream
 * @param passPhrase passPhrase
 * @return
 * @throws IOException
 */
public InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

  PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream);
  PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
  InputStream clear;

  try {
    clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(
        new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));

    JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);

    return new LazyMaterializeDecryptorInputStream(pgpFact);
  } catch (PGPException e) {
    throw new IOException(e);
  }
}
 
Example #3
Source File: EncryptionServicePgpImpl.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private PGPPublicKeyEncryptedData getPublicKeyEncryptedDataByKeyId(InputStream in, PGPSecretKey secretKey) {
	try {
		PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(in),
				KeyFilesOperationsPgpImpl.fingerprintCalculator);

		for (Iterator iter = factory.iterator(); iter.hasNext();) {
			Object section = iter.next();
			if (section instanceof PGPEncryptedDataList) {
				PGPEncryptedDataList d = (PGPEncryptedDataList) section;
				for (Iterator dataIter = d.getEncryptedDataObjects(); dataIter.hasNext();) {
					PGPPublicKeyEncryptedData data = (PGPPublicKeyEncryptedData) dataIter.next();
					if (data.getKeyID() == secretKey.getKeyID()) {
						return data;
					}
				}
			}
		}
		// NOTE: That is actually should NEVER happen since secret key we're
		// supposed to use here was taken exactly same way as we're looking
		// for PGPPublicKeyEncryptedData now
		throw new RuntimeException("Encryption data matching given key "
				+ KeyDataPgp.buildKeyIdStr(secretKey.getKeyID()) + " wasn't found");
	} catch (Throwable t) {
		throw new RuntimeException("Failed to find Encryption data section in encrypted file", t);
	}
}
 
Example #4
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptDecrypt_ExplicitStyle() throws Exception {
  int bufferSize = 64 * 1024;

  // Alice loads Bob's "publicKey" into memory.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();

  // Alice encrypts the secret message for Bob using his "publicKey".
  PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
      new BcPGPDataEncryptorBuilder(AES_128));
  encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
  byte[] encryptedData;
  try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
    try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
      output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
    }
    encryptedData = output.toByteArray();
  }
  logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData));

  // Bob loads his "privateKey" into memory.
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
  try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
    assertThat(encDataList.size()).isEqualTo(1);
    PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
    assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID());
    assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID());
    try (InputStream original =
        encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
      assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
          .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    }
  }
}
 
Example #5
Source File: PGPUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isEncryptedFile(Path file) {
    try (FileInputStream input = new FileInputStream(file.toFile())) {
        PGPObjectFactory factory = new PGPObjectFactory(input, FP_CALC);
        Object o = factory.nextObject();
        return o instanceof PGPEncryptedDataList || o instanceof PGPMarker;
    // NOTE: exception class is not well defined for non-pgp data
    } catch(IOException | RuntimeException ex) {
        return false;
    }
}
 
Example #6
Source File: PGPDecrypt.java    From peer-os with Apache License 2.0 3 votes vote down vote up
private static PGPPublicKeyEncryptedData getPGPEncryptedData( byte data[] ) throws IOException
{
    InputStream in = PGPUtil.getDecoderStream( new ByteArrayInputStream( data ) );

    JcaPGPObjectFactory objectFactory = new JcaPGPObjectFactory( in );

    PGPEncryptedDataList encryptedDataList = ( PGPEncryptedDataList ) objectFactory.nextObject();

    Iterator it = encryptedDataList.getEncryptedDataObjects();

    return ( PGPPublicKeyEncryptedData ) it.next();
}
 
Example #7
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 3 votes vote down vote up
@Test
public void testEncryptDecrypt_KeyRingStyle() throws Exception {
  int bufferSize = 64 * 1024;

  // Alice loads Bob's "publicKey" into memory from her public key ring.
  PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
      PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
  PGPPublicKeyRing publicKeyRing =
      publicKeyRings.getKeyRings("[email protected]", true, true).next();
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();

  // Alice encrypts the secret message for Bob using his "publicKey".
  PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
      new BcPGPDataEncryptorBuilder(AES_128));
  encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
  byte[] encryptedData;
  try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
    try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
      output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
    }
    encryptedData = output.toByteArray();
  }
  logger.atInfo().log("Encrypted data: %s", dumpHex(encryptedData));

  // Bob loads his chain of private keys into memory.
  PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
      PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

  // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
  try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
    assertThat(encDataList.size()).isEqualTo(1);
    PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
    // Bob loads the private key to which the message is addressed.
    PGPPrivateKey privateKey =
        extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
    try (InputStream original =
        encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
      assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
          .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    }
  }
}
 
Example #8
Source File: PgpUtils.java    From nomulus with Apache License 2.0 2 votes vote down vote up
/**
 * Stream the "list" that is PGPEncryptedDataList.
 *
 * <p>PGPEncryptedDataList is apparently very "legacy". It's not actually a list, and although it
 * implements "Iterable", there's no explicit type given. This requires multiple casts, which is
 * ugly. Moving the casts to a dedicated function makes it all clearer.
 */
static <T> Stream<T> stream(PGPEncryptedDataList ciphertexts, Class<T> expect) {
  return Streams.stream((Iterable<?>) ciphertexts)
      .map(ciphertext -> PgpUtils.pgpCast(ciphertext, expect));
}