Example usage for org.bouncycastle.openpgp PGPSignatureList size

List of usage examples for org.bouncycastle.openpgp PGPSignatureList size

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPSignatureList size.

Prototype

public int size() 

Source Link

Usage

From source file:cc.arduino.contributions.GPGDetachedSignatureVerifier.java

License:Open Source License

protected boolean verify(File signedFile, File signature, File publicKey) throws IOException {
    FileInputStream signatureInputStream = null;
    FileInputStream signedFileInputStream = null;
    try {//w  w w  .ja v  a 2s  . c o m
        signatureInputStream = new FileInputStream(signature);
        PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(signatureInputStream,
                new BcKeyFingerprintCalculator());

        Object nextObject;
        try {
            nextObject = pgpObjectFactory.nextObject();
            if (!(nextObject instanceof PGPSignatureList)) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
        PGPSignatureList pgpSignatureList = (PGPSignatureList) nextObject;
        assert pgpSignatureList.size() == 1;
        PGPSignature pgpSignature = pgpSignatureList.get(0);

        PGPPublicKey pgpPublicKey = readPublicKey(publicKey, keyId);

        pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), pgpPublicKey);
        signedFileInputStream = new FileInputStream(signedFile);
        pgpSignature.update(IOUtils.toByteArray(signedFileInputStream));

        return pgpSignature.verify();
    } catch (PGPException e) {
        throw new IOException(e);
    } finally {
        IOUtils.closeQuietly(signatureInputStream);
        IOUtils.closeQuietly(signedFileInputStream);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check the signature in clear-signed data
 *///from ww w . j  a  va  2  s. c o m
private boolean checkClearsign(InputStream in, PGPPublicKeyRingCollection pgpRings) throws PGPException {
    try {
        //
        // read the input, making sure we ingore the last newline.
        //
        ArmoredInputStream aIn = (ArmoredInputStream) in;
        boolean newLine = false;
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        int ch;
        while ((ch = aIn.read()) >= 0 && aIn.isClearText()) {
            if (newLine) {
                bOut.write((byte) '\n');
                newLine = false;
            }

            if (ch == '\n') {
                newLine = true;
                continue;
            }

            bOut.write((byte) ch);
        }

        PGPObjectFactory pgpFact = new PGPObjectFactory(aIn);
        PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
        PGPSignature sig = null;
        PGPPublicKey key = null;

        int count = 0;
        while (count < p3.size()) {
            sig = (PGPSignature) p3.get(count);
            key = pgpRings.getPublicKey(sig.getKeyID());
            if (key != null) {
                break;
            }

            count++;
        }

        if (key == null) {
            throw new PGPException("Corresponding public key not found");
        }
        if (key.isRevoked()) {
            String keyId = Long.toHexString(key.getKeyID()).substring(8);
            System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked");
            // throw new PGPException("Signing key (0x"+keyId+") has been revoked");
        }

        sig.initVerify(key, "BC");

        sig.update(bOut.toByteArray());

        return sig.verify();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in verification", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check a signature//from  w w  w. j av a  2s .  c o m
 */
private boolean checkSignature(OutputStream out, PGPSignatureList sigList, PGPObjectFactory pgpFact,
        PGPPublicKeyRingCollection pgpRing) throws PGPException {
    try {
        PGPSignature sig = null;
        PGPPublicKey key = null;

        int count = 0;
        while (count < sigList.size()) {
            sig = sigList.get(count);
            key = pgpRing.getPublicKey(sig.getKeyID());
            if (key != null) {
                break;
            }

            count++;
        }

        if (key == null) {
            throw new PGPException("Corresponding public key not found");
        }

        if (key.isRevoked()) {
            String keyId = Long.toHexString(key.getKeyID()).substring(8);
            System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked");
            // throw new PGPException("Signing key (0x"+keyId+") has been revoked");
        }

        PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();

        //            if (outputFilename == null) {
        //                outputFilename = ld.getFileName();
        //            }
        //
        //            FileOutputStream out = new FileOutputStream(outputFilename);

        InputStream dataIn = ld.getInputStream();

        sig.initVerify(key, "BC");

        int ch;
        while ((ch = dataIn.read()) >= 0) {
            sig.update((byte) ch);
            out.write(ch);
        }
        out.close();

        return sig.verify();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in verification", e);
    }
}

From source file:com.google.e2e.bcdriver.Decryptor.java

License:Apache License

private static final Result verifySignedContent(InputStream inp, KeyChecker.PKR verify)
        throws IOException, PGPException, SignatureException {
    PGPObjectFactory plainFact = new PGPObjectFactory(inp, new BcKeyFingerprintCalculator());

    Object msg = plainFact.nextObject();

    // swap in uncompressed data if necessary
    if (msg instanceof PGPCompressedData) {
        PGPCompressedData cData = (PGPCompressedData) msg;
        plainFact = new PGPObjectFactory(cData.getDataStream(), new BcKeyFingerprintCalculator());
        msg = plainFact.nextObject();/*from  w w w. ja  va2  s . co m*/
    }

    PGPOnePassSignatureList onePassSigList;
    PGPLiteralData lData;
    if (msg instanceof PGPOnePassSignatureList) {
        onePassSigList = (PGPOnePassSignatureList) msg;
        lData = (PGPLiteralData) plainFact.nextObject();
    } else {
        onePassSigList = null;
        lData = (PGPLiteralData) msg;
    }

    if ((verify != null) && (onePassSigList == null)) {
        throw new IOException("Message is unsigned");
    }

    PGPOnePassSignature onePassSig = null;
    int onePassStartIndex = -1;
    PGPPublicKey verifyKey = null;
    if (verify != null) {
        for (int i = 0; i < onePassSigList.size(); i++) {
            List<PGPPublicKey> candidates = verify.getSigningKeysByKeyID(onePassSigList.get(i).getKeyID());
            if (candidates.size() == 1) {
                onePassSig = onePassSigList.get(i);
                onePassStartIndex = i;
                verifyKey = candidates.get(0);
                break;
            }
        }
    }

    if ((verify != null) && (onePassSig == null)) {
        throw new IOException("Failed to find a signature from verifying key");
    }

    if (onePassSig != null) {
        onePassSig.init(new BcPGPContentVerifierBuilderProvider(), verifyKey);
    }
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    InputStream lin = lData.getInputStream();
    byte buf[] = new byte[8192];
    int nread;
    while ((nread = lin.read(buf)) > 0) {
        baout.write(buf, 0, nread);
        if (onePassSig != null) {
            onePassSig.update(buf, 0, nread);
        }
    }
    baout.close();
    if (onePassSig != null) {
        PGPSignatureList sigList = (PGPSignatureList) plainFact.nextObject();
        // One pass signature trailers occur in LIFO order compared to their
        // location in the header.
        PGPSignature sig = sigList.get(sigList.size() - 1 - onePassStartIndex);
        if (!onePassSig.verify(sig)) {
            throw new IOException("Invalid signature in message");
        }
    }
    return new Result(baout.toByteArray(), lData.getFileName());
}

From source file:com.google.e2e.bcdriver.KeyChecker.java

License:Apache License

private static final boolean isGoodBackSignature(PGPSignature sig, PGPPublicKey signer, PGPPublicKey target,
        StringBuilder errors) throws PGPException, SignatureException, IOException {

    SignatureSubpacket esigpack = null;//from ww w . ja  v  a  2  s.  c  o m

    // Prefer to get it from the hashed subpacket.
    PGPSignatureSubpacketVector svec = sig.getHashedSubPackets();
    if (svec != null) {
        esigpack = svec.getSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE);
    }

    if (esigpack == null) {
        svec = sig.getUnhashedSubPackets();
        if (svec != null) {
            esigpack = svec.getSubpacket(SignatureSubpacketTags.EMBEDDED_SIGNATURE);
        }
    }

    if (esigpack == null) {
        errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target)
                + " because it doesn't have a cross-certification.\n"
                + "See https://www.gnupg.org/faq/subkey-cross-certify.html\n");
        return false;
    }

    // Unfortunately, since PGPSignature(byte[]) is not public, we
    // have to go through this ugly contortion to get a signature.

    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    // dump out an old-style header.
    int hdr = 0x80 | (PacketTags.SIGNATURE << 2);
    int len = esigpack.getData().length;
    if (len <= 0xff) {
        baout.write(hdr);
        baout.write(len);
    } else if (len <= 0xffff) {
        baout.write(hdr | 0x01);
        baout.write((len >> 8) & 0xff);
        baout.write(len & 0xff);
    } else {
        baout.write(hdr | 0x02);
        baout.write((len >> 24) & 0xff);
        baout.write((len >> 16) & 0xff);
        baout.write((len >> 8) & 0xff);
        baout.write(len & 0xff);
    }

    baout.write(esigpack.getData());
    baout.close();

    PGPObjectFactory fact = new PGPObjectFactory(new ByteArrayInputStream(baout.toByteArray()),
            new BcKeyFingerprintCalculator());

    Object obj = fact.nextObject();

    if (!(obj instanceof PGPSignatureList)) {
        errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target)
                + " because no usable embedded signature is available.\n");
        return false;
    }
    PGPSignatureList esiglist = (PGPSignatureList) obj;
    if (esiglist.size() != 1) {
        errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target)
                + " because no usable embedded signature is available.\n");
        return false;
    }

    PGPSignature esig = esiglist.get(0);
    if (esig.getSignatureType() != PGPSignature.PRIMARYKEY_BINDING) {
        errors.append("Rejecting " + niceSig(sig) + " for subkey " + nicePk(target) + " because the embedded "
                + niceSig(esig) + " is not a proper backsignature.\n");
        return false;
    }

    esig.init(new BcPGPContentVerifierBuilderProvider(), target);

    return esig.verifyCertification(signer, target) && isSignatureCurrent(esig, errors);
}

From source file:com.navnorth.learningregistry.LRVerify.java

License:Apache License

/**
 * Verfies that the provided message and signature using the public key
 *
 * @param isSignature InputStream of the signature
 * @param isMessage InputStream of the message
 * @param isPublicKey InputStream of the public key
 * @throws LRException//from  www  .j a v  a2  s .c o  m
 */
private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey)
        throws LRException {
    // Get the public key ring collection from the public key input stream
    PGPPublicKeyRingCollection pgpRings = null;

    try {
        pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey));
    } catch (Exception e) {
        throw new LRException(LRException.INVALID_PUBLIC_KEY);
    }

    // Add the Bouncy Castle security provider
    Security.addProvider(new BouncyCastleProvider());

    // Build an output stream from the message for verification
    boolean verify = false;
    int ch;
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ArmoredInputStream aIn = null;

    try {
        aIn = new ArmoredInputStream(isMessage);
        // We are making no effort to clean the input for this example
        // If this turns into a fully-featured verification utility in a future version, this will need to be handled
        while ((ch = aIn.read()) >= 0 && aIn.isClearText()) {
            bOut.write((byte) ch);
        }

        bOut.close();
    } catch (Exception e) {
        throw new LRException(LRException.MESSAGE_INVALID);
    }

    // Build an object factory from the signature input stream and try to get an object out of it
    Object o = null;
    try {
        PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature));
        o = pgpFact.nextObject();
    } catch (Exception e) {
        throw new LRException(LRException.SIGNATURE_INVALID);
    }

    // Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy
    try {
        if (o instanceof PGPSignatureList) {
            PGPSignatureList list = (PGPSignatureList) o;
            if (list.size() > 0) {
                PGPSignature sig = list.get(0);

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

                sig.update(bOut.toByteArray());
                verify = sig.verify();
            }
        }
    } catch (Exception e) {
        throw new LRException(LRException.SIGNATURE_NOT_FOUND);
    }

    return verify;
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@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);//from  ww w  . j  ava  2s  .  co m
    byte[] signatureFileData = output.toByteArray();
    logger.info(".sig file data: " + 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();
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@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);// www  .  j  a  v  a 2 s . c  o m
    byte[] signatureFileData = output.toByteArray();
    logger.info(".sig file data: " + 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();
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

License:Apache License

protected PGPSignature getSignatureWithKeyId(long keyID, PGPSignatureList sigList) {
    for (int i = 0; i < sigList.size(); i++) {
        PGPSignature signature = sigList.get(i);
        if (keyID == signature.getKeyID()) {
            return signature;
        }/*w  w  w  .  java  2  s.  c  o  m*/
    }
    throw new IllegalStateException("PGP signature is inconsistent");
}

From source file:org.jpos.util.PGPHelper.java

License:Open Source License

public static boolean verifySignature(InputStream in, PGPPublicKey pk)
        throws IOException, NoSuchProviderException, PGPException, SignatureException {
    boolean verify = false;
    boolean newl = false;
    int ch;//from  ww  w  .j a v  a 2s .c om
    ArmoredInputStream ain = new ArmoredInputStream(in, true);
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    while ((ch = ain.read()) >= 0 && ain.isClearText()) {
        if (newl) {
            out.write((byte) '\n');
            newl = false;
        }
        if (ch == '\n') {
            newl = true;
            continue;
        }
        out.write((byte) ch);
    }
    PGPObjectFactory pgpf = new PGPObjectFactory(ain, fingerPrintCalculater);
    Object o = pgpf.nextObject();
    if (o instanceof PGPSignatureList) {
        PGPSignatureList list = (PGPSignatureList) o;
        if (list.size() > 0) {
            PGPSignature sig = list.get(0);
            sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pk);
            while ((ch = ain.read()) >= 0 && ain.isClearText()) {
                if (newl) {
                    out.write((byte) '\n');
                    newl = false;
                }
                if (ch == '\n') {
                    newl = true;
                    continue;
                }
                out.write((byte) ch);
            }
            sig.update(out.toByteArray());
            verify = sig.verify();
        }
    }
    return verify;
}