Java Code Examples for org.bouncycastle.openpgp.PGPSignatureList#get()

The following examples show how to use org.bouncycastle.openpgp.PGPSignatureList#get() . 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: 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 2
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 3
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 4
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static boolean verifyClearSign( byte[] message, PGPPublicKeyRing pgpRings )
        throws IOException, PGPException, SignatureException
{
    ArmoredInputStream aIn = new ArmoredInputStream( new ByteArrayInputStream( message ) );
    ByteArrayOutputStream bout = new ByteArrayOutputStream();


    //
    // write out signed section using the local line separator.
    // note: trailing white space needs to be removed from the end of
    // each line RFC 4880 Section 7.1
    //
    ByteArrayOutputStream lineOut = new ByteArrayOutputStream();

    boolean isFirstLineClearText = aIn.isClearText();
    int lookAhead = readInputLine( lineOut, aIn );

    if ( lookAhead != -1 && isFirstLineClearText )
    {
        bout.write( lineOut.toByteArray() );
        while ( lookAhead != -1 && aIn.isClearText() )
        {
            lookAhead = readInputLine( lineOut, lookAhead, aIn );
            bout.write( lineOut.toByteArray() );
        }
    }

    JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory( aIn );
    PGPSignatureList p3 = ( PGPSignatureList ) pgpFact.nextObject();
    PGPSignature sig = p3.get( 0 );


    PGPPublicKey publicKey = pgpRings.getPublicKey( sig.getKeyID() );
    sig.init( new JcaPGPContentVerifierBuilderProvider().setProvider( "BC" ), publicKey );

    //
    // read the input, making sure we ignore the last newline.
    //

    InputStream sigIn = new ByteArrayInputStream( bout.toByteArray() );

    lookAhead = readInputLine( lineOut, sigIn );

    processLine( sig, lineOut.toByteArray() );

    if ( lookAhead != -1 )
    {
        do
        {
            lookAhead = readInputLine( lineOut, lookAhead, sigIn );

            sig.update( ( byte ) '\r' );
            sig.update( ( byte ) '\n' );

            processLine( sig, lineOut.toByteArray() );
        }
        while ( lookAhead != -1 );
    }

    sigIn.close();

    return sig.verify();
}
 
Example 5
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 6
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();
}