org.bouncycastle.openpgp.bc.BcPGPObjectFactory Java Examples

The following examples show how to use org.bouncycastle.openpgp.bc.BcPGPObjectFactory. 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: 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 #2
Source File: PackageBuilderTest.java    From dropwizard-debpkg-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testPackageSignature() throws IOException, PackagingException, PGPException, SignatureException, org.bouncycastle.openpgp.PGPException, NoSuchProviderException {
    final File debFile = createPackage(ImmutableList.<Resource>of(
            new StringResource("hello world", true, "/tmp/test.txt", USER, USER, TarEntry.DEFAULT_FILE_MODE)
    ));

    final File packageDir = temporaryFolder.newFolder();
    ArchiveUtils.extractAr(debFile, packageDir);

    final File pgpSignatureFile = new File(packageDir, "_gpgorigin");
    assertTrue(pgpSignatureFile.exists());

    try (final InputStream keyringIn = PGPUtil.getDecoderStream(PackageBuilderTest.class.getResourceAsStream("public.asc"))) {
        try (final InputStream signatureIn = PGPUtil.getDecoderStream(new FileInputStream(pgpSignatureFile))) {
            final PGPPublicKey publicKey = ((PGPPublicKeyRing) new BcPGPPublicKeyRingCollection(keyringIn).getKeyRings().next()).getPublicKey();
            final PGPSignature signature = ((PGPSignatureList) new BcPGPObjectFactory(signatureIn).nextObject()).get(0);
            signature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

            signature.update(Files.asByteSource(new File(packageDir, "debian-binary")).read());
            signature.update(Files.asByteSource(new File(packageDir, "control.tar.gz")).read());
            signature.update(Files.asByteSource(new File(packageDir, "data.tar.gz")).read());

            assertTrue(signature.verify());
        }
    }
}
 
Example #3
Source File: Ring.java    From jpgpj with MIT License 5 votes vote down vote up
/**
 * Separates stream into PGP packets.
 * @see PGPObjectFactory
 */
protected Iterator<?> parse(InputStream stream)
throws IOException, PGPException {
    DetectionResult result = FileDetection.detectContainer(stream);
    switch (result.type) {
        case ASCII_ARMOR:
            result.stream = new ArmoredInputStream(result.stream); // fall thru
        case PGP:
            return new BcPGPObjectFactory(result.stream).iterator();
        case KEYBOX:
            return new BcKeyBox(result.stream).getKeyBlobs().iterator();
        default:
            throw new PGPException("not a keyring");
    }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: Decryptor.java    From jpgpj with MIT License 4 votes vote down vote up
/**
 * Separates stream into PGP packets.
 * @see PGPObjectFactory
 */
protected Iterator<?> parse(InputStream stream)
        throws IOException, PGPException {
    return new BcPGPObjectFactory(stream).iterator();
}
 
Example #8
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 #9
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);
    }
  }
}