Java Code Examples for org.bouncycastle.openpgp.PGPSignature#init()

The following examples show how to use org.bouncycastle.openpgp.PGPSignature#init() . 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
/**
 * Verifies that a public key is signed with another public key
 *
 * @param keyToVerify the public key to verify
 * @param id the id we are verifying against the public key
 * @param keyToVerifyWith the key to verify with
 *
 * @return true if verified, false otherwise
 */
public static boolean verifyPublicKey( PGPPublicKey keyToVerify, String id, PGPPublicKey keyToVerifyWith )
        throws PGPException
{
    try
    {
        Iterator<PGPSignature> signIterator = keyToVerify.getSignatures();
        while ( signIterator.hasNext() )
        {
            PGPSignature signature = signIterator.next();
            signature.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ), keyToVerifyWith );
            if ( signature.verifyCertification( id.getBytes(), keyToVerify ) )
            {
                return true;
            }
        }
        return false;
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error verifying public key", e );
    }
}
 
Example 2
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 3
Source File: Decryptor.java    From jpgpj with MIT License 5 votes vote down vote up
public void setSig(PGPSignature s) throws PGPException {
    sig = s;
    if (sig1 != null) return;

    Subkey subkey = findVerificationSubkey(s.getKeyID());
    if (subkey != null)
        s.init(getVerifierProvider(), subkey.getPublicKey());
}
 
Example 4
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static PGPPublicKeyRing removeSignature( PGPPublicKeyRing keyToRemoveFrom,
                                                PGPPublicKey keySignatureToRemove ) throws PGPException
{
    try
    {
        PGPPublicKey oldKey = keyToRemoveFrom.getPublicKey();

        PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( keyToRemoveFrom, oldKey );

        Iterator<PGPSignature> signIterator = oldKey.getSignatures();
        while ( signIterator.hasNext() )
        {
            PGPSignature signature = signIterator.next();
            signature.init( new JcaPGPContentVerifierBuilderProvider().setProvider( provider ),
                    keySignatureToRemove );

            String sigId = PGPKeyUtil.encodeNumericKeyId( oldKey.getKeyID() );

            if ( signature.verifyCertification( sigId, oldKey ) )
            {
                PGPPublicKey updatedKey = PGPPublicKey.removeCertification( oldKey, signature );
                keyToRemoveFrom = PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, updatedKey );
            }
        }

        return keyToRemoveFrom;
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error removing signature", e );
    }
}
 
Example 5
Source File: Marksdb.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static void pgpVerifySignature(byte[] data, byte[] signature, PGPPublicKey publicKey)
    throws PGPException, SignatureException {
  Security.addProvider(new BouncyCastleProvider());
  PGPSignature sig = pgpExtractSignature(signature);
  sig.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
  sig.update(data);
  if (!sig.verify()) {
    throw new SignatureException(String.format(
        "MarksDB PGP signature verification failed.\n%s",
        dumpHex(signature)));
  }
}
 
Example 6
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 7
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 8
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();
}