org.bouncycastle.openpgp.PGPObjectFactory Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPObjectFactory. 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: KeyFilesOperationsPgpImpl.java    From pgptool with GNU General Public License v3.0 7 votes vote down vote up
@SuppressWarnings("rawtypes")
private static void readKeyFromStream(KeyDataPgp data, InputStream stream) throws IOException {
	PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(stream), fingerprintCalculator);
	for (Iterator iter = factory.iterator(); iter.hasNext();) {
		Object section = iter.next();
		log.debug("Section found: " + section);

		if (section instanceof PGPSecretKeyRing) {
			data.setSecretKeyRing((PGPSecretKeyRing) section);
		} else if (section instanceof PGPPublicKeyRing) {
			data.setPublicKeyRing((PGPPublicKeyRing) section);
		} else {
			log.error("Unknown section enountered in a key file: " + section);
		}
	}
}
 
Example #2
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 #3
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompressDecompress() throws Exception {
  // Compress the data and write out a compressed data OpenPGP message.
  byte[] data;
  try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
    PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(ZIP);
    try (OutputStream output2 = kompressor.open(output)) {
      output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
    }
    data = output.toByteArray();
  }
  logger.atInfo().log("Compressed data: %s", dumpHex(data));

  // Decompress the data.
  try (ByteArrayInputStream input = new ByteArrayInputStream(data)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPCompressedData object = (PGPCompressedData) pgpFact.nextObject();
    InputStream original = object.getDataStream();  // Closing this would close input.
    assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
        .isEqualTo(FALL_OF_HYPERION_A_DREAM);
    assertThat(pgpFact.nextObject()).isNull();
  }
}
 
Example #4
Source File: AptITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public boolean verifyReleaseFilePgpSignature(final InputStream signedData,
                                             final InputStream signature,
                                             final InputStream publicKey)
    throws Exception
{
  PGPObjectFactory pgpFact =
      new PGPObjectFactory(PGPUtil.getDecoderStream(signature), new JcaKeyFingerprintCalculator());
  PGPSignature sig = ((PGPSignatureList) pgpFact.nextObject()).get(0);

  PGPPublicKeyRingCollection pgpPubRingCollection =
      new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKey),
          new JcaKeyFingerprintCalculator());

  PGPPublicKey key = pgpPubRingCollection.getPublicKey(sig.getKeyID());
  sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key);
  byte[] buff = new byte[1024];
  int read = 0;
  while ((read = signedData.read(buff)) != -1) {
    sig.update(buff, 0, read);
  }
  signedData.close();
  return sig.verify();
}
 
Example #5
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 #6
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/**
 * ***********************************************
 */
private static PGPLiteralData asLiteral( final InputStream clear ) throws IOException, PGPException
{
    final PGPObjectFactory plainFact = new PGPObjectFactory( clear, new JcaKeyFingerprintCalculator() );
    final Object message = plainFact.nextObject();
    if ( message instanceof PGPCompressedData )
    {
        final PGPCompressedData cData = ( PGPCompressedData ) message;
        final PGPObjectFactory pgpFact =
                new PGPObjectFactory( cData.getDataStream(), new JcaKeyFingerprintCalculator() );
        // Find the first PGPLiteralData object
        Object object = null;
        for ( int safety = 0; ( safety++ < 1000 ) && !( object instanceof PGPLiteralData );
              object = pgpFact.nextObject() )
        {
            //ignore
        }
        return ( PGPLiteralData ) object;
    }
    else if ( message instanceof PGPLiteralData )
    {
        return ( PGPLiteralData ) message;
    }
    else if ( message instanceof PGPOnePassSignatureList )
    {
        throw new PGPException( "encrypted message contains a signed message - not literal data." );
    }
    else
    {
        throw new PGPException(
                "message is not a simple encrypted file - type unknown: " + message.getClass().getName() );
    }
}
 
Example #7
Source File: Marksdb.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a {@link PGPSignature} object from a blob of {@code .sig} data.
 *
 * @throws SignatureException if a signature object couldn't be extracted for any reason.
 */
private static PGPSignature pgpExtractSignature(@Tainted byte[] signature)
    throws SignatureException {
  try {
    ByteArrayInputStream input = new ByteArrayInputStream(signature);
    PGPObjectFactory decoder = new BcPGPObjectFactory(PGPUtil.getDecoderStream(input));
    Object object = decoder.nextObject();
    if (object == null) {
      throw new SignatureException(String.format(
          "No OpenPGP packets found in signature.\n%s",
          dumpHex(signature)));
    }
    if (!(object instanceof PGPSignatureList)) {
      throw new SignatureException(String.format(
          "Expected PGPSignatureList packet but got %s\n%s",
          object.getClass().getSimpleName(),
          dumpHex(signature)));
    }
    PGPSignatureList sigs = (PGPSignatureList) object;
    if (sigs.isEmpty()) {
      throw new SignatureException(String.format(
          "PGPSignatureList doesn't have a PGPSignature.\n%s",
          dumpHex(signature)));
    }
    return sigs.get(0);
  } catch (IOException e) {
    throw new SignatureException(String.format(
        "Failed to extract PGPSignature object from .sig blob.\n%s",
        dumpHex(signature)), e);
  }
}
 
Example #8
Source File: PgpUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static <T> T readSinglePgpObject(InputStream input, Class<T> expect) {
  try {
    PGPObjectFactory fact = new JcaPGPObjectFactory(input);
    return PgpUtils.pgpCast(fact.nextObject(), expect);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #9
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignVerify_Detached() throws Exception {
  // Load the keys.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Sign the data and write signature data to "signatureFile".
  // Note: RSA_GENERAL will encrypt AND sign. RSA_SIGN and RSA_ENCRYPT are deprecated.
  PGPSignatureGenerator signer = new PGPSignatureGenerator(
      new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
  signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
  addUserInfoToSignature(publicKey, signer);
  signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  signer.generate().encode(output);
  byte[] signatureFileData = output.toByteArray();
  logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData));

  // Load algorithm information and signature data from "signatureFileData".
  PGPSignature sig;
  try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
    assertThat(sigList.size()).isEqualTo(1);
    sig = sigList.get(0);
  }

  // Use "onePass" and "sig" to verify "publicKey" signed the text.
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  assertThat(sig.verify()).isTrue();

  // Verify that they DIDN'T sign the text "hello monster".
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update("hello monster".getBytes(UTF_8));
  assertThat(sig.verify()).isFalse();
}
 
Example #10
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 #11
Source File: Decryptor.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static DecryptionResult verifySignature(DecryptionResult result,
        PGPObjectFactory pgpFact, PGPOnePassSignature ops) throws PGPException, IOException {
    Object object = pgpFact.nextObject(); // nullable
    if (!(object instanceof PGPSignatureList)) {
        LOGGER.warning("invalid signature packet");
        result.errors.add(Coder.Error.INVALID_SIGNATURE_DATA);
        return result;
    }

    PGPSignatureList signatureList = (PGPSignatureList) object;
    if (signatureList.isEmpty()) {
        LOGGER.warning("no signature in signature list");
        result.errors.add(Coder.Error.INVALID_SIGNATURE_DATA);
        return result;
    }

    PGPSignature signature = signatureList.get(0);
    // TODO signature.getCreationTime()
    if (ops.verify(signature)) {
        // signature verification successful!
        result.signing = Coder.Signing.VERIFIED;
    } else {
        LOGGER.warning("signature verification failed");
        result.errors.add(Coder.Error.INVALID_SIGNATURE);
    }
    return result;
}
 
Example #12
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 #13
Source File: AptITSupport.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public boolean verifyInReleaseFilePgpSignature(final InputStream fileContent, final InputStream publicKeyString)
    throws Exception
{

  PGPPublicKeyRingCollection pgpRings =
      new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyString),
          new JcaKeyFingerprintCalculator());
  ArmoredInputStream aIn = new ArmoredInputStream(fileContent);
  ByteArrayOutputStream releaseContent = new ByteArrayOutputStream();
  ByteArrayOutputStream lineOut = new ByteArrayOutputStream();

  int fromPositon = -1;
  if (aIn.isClearText()) {
    do {
      fromPositon = readStreamLine(lineOut, fromPositon, aIn);
      releaseContent.write(lineOut.toByteArray());
    }
    while (fromPositon != -1 && aIn.isClearText());
  }

  PGPObjectFactory pgpFact = new PGPObjectFactory(aIn, new JcaKeyFingerprintCalculator());
  PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
  PGPSignature sig = p3.get(0);

  PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
  sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
  InputStream sigIn = new ByteArrayInputStream(releaseContent.toByteArray());

  fromPositon = -1;
  do {
    int length;
    if (fromPositon != -1) {
      sig.update((byte) '\r');
      sig.update((byte) '\n');
    }
    fromPositon = readStreamLine(lineOut, fromPositon, sigIn);
    length = lineOut.toString(StandardCharsets.UTF_8.name()).replaceAll("\\s*$", "").length();
    if (length > 0) {
      sig.update(lineOut.toByteArray(), 0, length);
    }
  }
  while (fromPositon != -1);

  return sig.verify();
}
 
Example #14
Source File: BouncyCastleTest.java    From nomulus with Apache License 2.0 3 votes vote down vote up
@Test
public void testSignVerify_OnePass() throws Exception {
  // Load the keys.
  PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
  PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
  PGPPublicKey publicKey = publicKeyRing.getPublicKey();
  PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

  // Sign the data and write signature data to "signatureFile".
  PGPSignatureGenerator signer = new PGPSignatureGenerator(
      new BcPGPContentSignerBuilder(RSA_GENERAL, SHA256));
  signer.init(PGPSignature.BINARY_DOCUMENT, privateKey);
  addUserInfoToSignature(publicKey, signer);
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  signer.generateOnePassVersion(false).encode(output);
  signer.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  signer.generate().encode(output);
  byte[] signatureFileData = output.toByteArray();
  logger.atInfo().log(".sig file data: %s", dumpHex(signatureFileData));

  // Load algorithm information and signature data from "signatureFileData".
  PGPSignature sig;
  PGPOnePassSignature onePass;
  try (ByteArrayInputStream input = new ByteArrayInputStream(signatureFileData)) {
    PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
    PGPOnePassSignatureList onePassList = (PGPOnePassSignatureList) pgpFact.nextObject();
    PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
    assertThat(onePassList.size()).isEqualTo(1);
    assertThat(sigList.size()).isEqualTo(1);
    onePass = onePassList.get(0);
    sig = sigList.get(0);
  }

  // Use "onePass" and "sig" to verify "publicKey" signed the text.
  onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  onePass.update(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
  assertThat(onePass.verify(sig)).isTrue();

  // Verify that they DIDN'T sign the text "hello monster".
  onePass.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  onePass.update("hello monster".getBytes(UTF_8));
  assertThat(onePass.verify(sig)).isFalse();
}
 
Example #15
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);
    }
  }
}