Example usage for org.bouncycastle.openpgp.operator.bc BcPGPContentVerifierBuilderProvider BcPGPContentVerifierBuilderProvider

List of usage examples for org.bouncycastle.openpgp.operator.bc BcPGPContentVerifierBuilderProvider BcPGPContentVerifierBuilderProvider

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.bc BcPGPContentVerifierBuilderProvider BcPGPContentVerifierBuilderProvider.

Prototype

public BcPGPContentVerifierBuilderProvider() 

Source Link

Usage

From source file:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

@Override
public void verify(OutputStream outputStream, final InputStream inputStream) {

    try {/*  ww  w .  j  a v  a2 s  .  c o  m*/
        final File keyFile = this.publicKeyRing;

        final InputStream in = PGPUtil.getDecoderStream(inputStream);

        PGPObjectFactory pgpFact = new PGPObjectFactory(in);

        final PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());

        final PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) pgpFact.nextObject();

        final PGPOnePassSignature ops = p1.get(0);

        final PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject();

        final InputStream dIn = p2.getInputStream();
        int ch;
        final PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(new FileInputStream(keyFile)));

        final PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID());

        ops.init(new BcPGPContentVerifierBuilderProvider(), key);

        while ((ch = dIn.read()) >= 0) {
            ops.update((byte) ch);
            outputStream.write(ch);
        }

        outputStream.close();

        final PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();

        if (!ops.verify(p3.get(0))) {
            outputStream = null;
        }
    } catch (final FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final PGPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java

License:Open Source License

/**
 * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys.
 *
 * @param pubKeyFile Path to file providing the public key to use
 * @param sigFile    Path to detached signature file
 * @param dataFile   Path to signed data file
 * @return {@code true} if signature is valid, {@code false} if signature is not valid
 * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or
 *                   signature could be extracted from the provided files due to a "bad" format.<br>
 *                   <code>FileNotFoundException, IOException, SignatureException, PGPException</code>
 *//*  ww w.ja v  a  2 s .  c  om*/
public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception {
    InputStream inputStream;
    int bytesRead;
    PGPPublicKey publicKey;
    PGPSignature pgpSignature;
    boolean result;

    // Read keys from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile));
    PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream,
            new JcaKeyFingerprintCalculator());
    inputStream.close();

    Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings();
    PGPPublicKeyRing pgpPublicKeyRing;
    if (iterator.hasNext()) {
        pgpPublicKeyRing = iterator.next();
    } else {
        throw new PGPException("Could not find public keyring in provided key file");
    }

    // Would be the solution for multiple keys in one file
    //        Iterator<PGPPublicKey> kIt;
    //        kIt = pgpPublicKeyRing.getPublicKeys();
    //        publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L);

    // Read signature from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile));
    PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator());
    Object o = pgpObjectFactory.nextObject();
    if (o instanceof PGPSignatureList) {
        PGPSignatureList signatureList = (PGPSignatureList) o;
        checkArgument(!signatureList.isEmpty(), "signatureList must not be empty");
        pgpSignature = signatureList.get(0);
    } else if (o instanceof PGPSignature) {
        pgpSignature = (PGPSignature) o;
    } else {
        throw new SignatureException("Could not find signature in provided signature file");
    }
    inputStream.close();
    log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID());
    publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID());

    // If signature is not matching the key used for signing we fail
    if (publicKey == null)
        return VerifyStatusEnum.FAIL;

    log.debug("The ID of the selected key is %X\n", publicKey.getKeyID());
    pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

    // Read file to verify
    byte[] data = new byte[1024];
    inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
    while (true) {
        bytesRead = inputStream.read(data, 0, 1024);
        if (bytesRead == -1)
            break;
        pgpSignature.update(data, 0, bytesRead);
    }
    inputStream.close();

    // Verify the signature
    result = pgpSignature.verify();
    return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL;
}

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 {//from   w  w w  .  j  a  va2s  . com
        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.arcusx.simplepgp.PgpDataDecryptor.java

public void decrypt(InputStream encryptedIn, InputStream privateKeyIn, InputStream publicKeyIn,
        OutputStream plainOut, boolean signatureRequired) throws PGPException, IOException {
    encryptedIn = PGPUtil.getDecoderStream(encryptedIn);

    try {/*from w  w  w . j  av a  2 s.c  o m*/
        JcaPGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory(encryptedIn);

        Object o = pgpObjectFactory.nextObject();

        //
        // the first object might be a PGP marker packet.
        //
        PGPEncryptedDataList enc;
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
        }

        //
        // find the secret key
        //
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey privateKey = null;
        PGPPublicKeyEncryptedData publicKeyEncryptedData = null;
        PGPSecretKeyRingCollection privateKeyRingCollection = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(privateKeyIn), new JcaKeyFingerprintCalculator());

        while (privateKey == null && it.hasNext()) {
            publicKeyEncryptedData = (PGPPublicKeyEncryptedData) it.next();
            privateKey = findSecretKey(privateKeyRingCollection, publicKeyEncryptedData.getKeyID(),
                    "".toCharArray());
        }

        if (privateKey == null) {
            throw new IllegalArgumentException("Secret key for message not found.");
        }

        PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder()
                .setProvider("BC").build(privateKey);
        InputStream clearTextIn = publicKeyEncryptedData.getDataStream(decryptorFactory);

        PGPOnePassSignature onePassSignature = null;
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clearTextIn);

        Object message = pgpFact.nextObject();
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());

            message = pgpFact.nextObject();
        }

        if (message instanceof PGPOnePassSignatureList) {
            PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) message;
            onePassSignature = onePassSignatureList.get(0);
            message = pgpFact.nextObject();
        }

        if (onePassSignature == null && signatureRequired) {
            throw new SecurityException("No signature object found.");
        }

        if (message instanceof PGPLiteralData) {
            PGPLiteralData literalData = (PGPLiteralData) message;
            InputStream literalDataIn = literalData.getInputStream();

            PGPPublicKey publicKey = PgpKeyUtils.readPublicKey(publicKeyIn);
            if (onePassSignature != null) {
                onePassSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
            }

            int len = 0;
            byte[] buf = new byte[BUFFER_SIZE];
            while ((len = literalDataIn.read(buf, 0, buf.length)) >= 0) {
                if (onePassSignature != null) {
                    onePassSignature.update(buf, 0, len);
                }

                plainOut.write(buf, 0, len);
            }

            if (onePassSignature != null) {
                PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
                PGPSignature signature = p3.get(0);
                if (!onePassSignature.verify(signature))
                    throw new PGPException("Signature invalid.");
            }

            plainOut.close();
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown." + message);
        }

        if (!publicKeyEncryptedData.isIntegrityProtected())
            throw new IllegalStateException("Message is not integrity protected.");

        if (!publicKeyEncryptedData.verify())
            throw new IllegalStateException("Message is integrity protected but integrity check failed.");
    } catch (NoSuchProviderException ex) {
        throw new PGPException("Decryption failed.", ex);
    } finally {
        IOUtils.closeQuietly(encryptedIn);
        IOUtils.closeQuietly(privateKeyIn);
        IOUtils.closeQuietly(publicKeyIn);
        IOUtils.closeQuietly(plainOut);
    }
}

From source file:com.github.s4u.plugins.PGPVerifyMojo.java

License:Apache License

private boolean verifyPGPSignature(Artifact artifact, File artifactFile, File signatureFile)
        throws MojoFailureException {

    final Map<Integer, String> weakSignatures = ImmutableMap.<Integer, String>builder().put(1, "MD5")
            .put(4, "DOUBLE_SHA").put(5, "MD2").put(6, "TIGER_192").put(7, "HAVAL_5_160").put(11, "SHA224")
            .build();/*from   w  ww .  j a va2  s  .  co m*/

    getLog().debug("Artifact file: " + artifactFile);
    getLog().debug("Artifact sign: " + signatureFile);

    try {
        InputStream sigInputStream = PGPUtil.getDecoderStream(new FileInputStream(signatureFile));
        PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream,
                new BcKeyFingerprintCalculator());
        PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject();
        if (sigList == null) {
            throw new MojoFailureException("Invalid signature file: " + signatureFile);
        }
        PGPSignature pgpSignature = sigList.get(0);

        PGPPublicKey publicKey = pgpKeysCache.getKey(pgpSignature.getKeyID());

        if (!keysMap.isValidKey(artifact, publicKey)) {
            String msg = String.format("%s=0x%X", ArtifactUtils.key(artifact), publicKey.getKeyID());
            String keyUrl = pgpKeysCache.getUrlForShowKey(publicKey.getKeyID());
            getLog().error(String.format("Not allowed artifact %s and keyID:\n\t%s\n\t%s\n", artifact.getId(),
                    msg, keyUrl));
            return false;
        }

        pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

        try (InputStream inArtifact = new BufferedInputStream(new FileInputStream(artifactFile))) {

            int t;
            while ((t = inArtifact.read()) >= 0) {
                pgpSignature.update((byte) t);
            }
        }

        String msgFormat = "%s PGP Signature %s\n       KeyId: 0x%X UserIds: %s";
        if (pgpSignature.verify()) {
            getLog().info(String.format(msgFormat, artifact.getId(), "OK", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            if (weakSignatures.containsKey(pgpSignature.getHashAlgorithm())) {
                if (failWeakSignature) {
                    getLog().error("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                    throw new MojoFailureException("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                } else {
                    getLog().warn("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                }
            }
            return true;
        } else {
            getLog().warn(String.format(msgFormat, artifact.getId(), "ERROR", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            getLog().warn(artifactFile.toString());
            getLog().warn(signatureFile.toString());
            return false;
        }

    } catch (IOException | PGPException e) {
        throw new MojoFailureException(e.getMessage(), 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  v  a  2  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 isGoodSubkeySignature(PGPSignature sig, PGPPublicKey primary, PGPPublicKey subkey,
        StringBuilder errors) throws PGPException, SignatureException, IOException {

    sig.init(new BcPGPContentVerifierBuilderProvider(), primary);

    return sig.verifyCertification(primary, subkey) && isSignatureCurrent(sig, errors);
}

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

License:Apache License

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

    sig.init(new BcPGPContentVerifierBuilderProvider(), signer);

    boolean ok;//  w  w w  . j a va  2s  .  co m

    // There's a bug that prevents sig.verifyCertification(signer)
    // working for DIRECT_KEY signatures.
    //
    // So, re-implement the code again here.
    if (sig.getSignatureType() == PGPSignature.DIRECT_KEY) {
        byte[] bytes = target.getPublicKeyPacket().getEncodedContents();
        sig.update((byte) 0x99);
        sig.update((byte) (bytes.length >> 8));
        sig.update((byte) (bytes.length));
        sig.update(bytes);
        ok = sig.verify();
    } else {
        ok = sig.verifyCertification(target);
    }

    // If we have a good signature, also ensure the signature
    // hasn't expired.
    return ok && isSignatureCurrent(sig, errors);
}

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 w w  w .j  ava2s .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.google.e2e.bcdriver.KeyChecker.java

License:Apache License

private static final boolean isGoodUIDSignature(PGPSignature sig, PGPPublicKey masterpk, String uid,
        StringBuilder errors) throws PGPException, SignatureException, IOException {

    sig.init(new BcPGPContentVerifierBuilderProvider(), masterpk);
    if (!sig.verifyCertification(uid, masterpk)) {
        errors.append("Skipping certification " + niceSig(sig) + " for '" + uid
                + "' because the signature is invalid.\n");
        return false;
    }/*www.j  a  v  a 2s . c o  m*/
    return isSignatureCurrent(sig, errors);
}