Example usage for org.bouncycastle.openpgp PGPSignature init

List of usage examples for org.bouncycastle.openpgp PGPSignature init

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPSignature init.

Prototype

public void init(PGPContentVerifierBuilderProvider verifierBuilderProvider, PGPPublicKey pubKey)
            throws PGPException 

Source Link

Usage

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>
 *//*  w ww.j av  a2s  .co m*/
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  ww. ja  v a 2  s  . c om
        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:cc.arduino.packages.security.ClearSignedVerifier.java

License:Open Source License

/**
 * Verify a PGP clearText-signature.//from  www . j  av a2  s .c o m
 *
 * @param signedTextFile A File containing the clearText signature
 * @param pubKeyRing     A public key-ring containing the public key needed for the
 *                       signature verification
 * @return A VerifyResult class with the clearText and the signature
 * verification status
 * @throws FileNotFoundException
 */
public static VerifyResult verify(File signedTextFile, PGPPublicKeyRingCollection pubKeyRing) {
    // Create the result object
    VerifyResult result = new VerifyResult();
    result.clearText = null;
    result.verified = false;
    result.error = null;

    ArmoredInputStream in = null;
    try {
        // Extract clear text.
        // Dash-encoding is removed by ArmoredInputStream.
        in = new ArmoredInputStream(new FileInputStream(signedTextFile));
        ByteArrayOutputStream temp = new ByteArrayOutputStream(in.available());
        while (true) {
            int c = in.read();
            if (c == -1)
                throw new IOException("Unexpected end of file");
            if (!in.isClearText())
                break;
            temp.write(c);
        }
        byte clearText[] = temp.toByteArray();
        result.clearText = clearText;

        // Extract signature from clear-signed text
        PGPObjectFactory pgpFact = new PGPObjectFactory(in);
        PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
        PGPSignature sig = p3.get(0);

        // Decode public key
        PGPPublicKey publicKey = pubKeyRing.getPublicKey(sig.getKeyID());

        // Verify signature
        Security.addProvider(new BouncyCastleProvider());
        sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
        // RFC 4880, section 7: http://tools.ietf.org/html/rfc4880#section-7
        // The signature must be validated using clear text:
        // - without trailing white spaces on every line
        // - using CR LF line endings, no matter what the original line ending is
        // - without the latest line ending
        BufferedReader textIn = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(clearText)));
        while (true) {
            // remove trailing whitespace and line endings
            String line = StringUtils.rtrim(textIn.readLine());
            sig.update(line.getBytes());
            if (!textIn.ready()) // skip latest line ending
                break;
            // always use CR LF
            sig.update((byte) '\r');
            sig.update((byte) '\n');
        }

        // Prepare the result
        result.verified = sig.verify();
    } catch (Exception e) {
        result.error = e;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
                // ignored
            }
    }
    return result;
}

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 .  ja v a 2 s .  c om

    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.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;//from ww  w .ja  va2 s  .c  o  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 a va2s. 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;
    }//from w  ww.j a v  a  2s  . c  o  m
    return isSignatureCurrent(sig, errors);
}

From source file:com.google.gerrit.gpg.GerritPublicKeyChecker.java

License:Apache License

private static boolean isValidCertification(PGPPublicKey key, PGPSignature sig, String userId)
        throws PGPException {
    if (sig.getSignatureType() != PGPSignature.DEFAULT_CERTIFICATION
            && sig.getSignatureType() != PGPSignature.POSITIVE_CERTIFICATION) {
        return false;
    }//w  ww  .  ja v a  2  s  .com
    if (sig.getKeyID() != key.getKeyID()) {
        return false;
    }
    // TODO(dborowitz): Handle certification revocations:
    // - Is there a revocation by either this key or another key trusted by the
    //   server?
    // - Does such a revocation postdate all other valid certifications?

    sig.init(new BcPGPContentVerifierBuilderProvider(), key);
    return sig.verifyCertification(userId, key);
}

From source file:com.google.gerrit.gpg.PublicKeyStore.java

License:Apache License

/**
 * Choose the public key that produced a signature.
 * <p>/*ww  w. ja va2 s.c o  m*/
 * @param keyRings candidate keys.
 * @param sig signature object.
 * @param data signed payload.
 * @return the key chosen from {@code keyRings} that was able to verify the
 *     signature, or null if none was found.
 * @throws PGPException if an error occurred verifying the signature.
 */
public static PGPPublicKey getSigner(Iterable<PGPPublicKeyRing> keyRings, PGPSignature sig, byte[] data)
        throws PGPException {
    for (PGPPublicKeyRing kr : keyRings) {
        PGPPublicKey k = kr.getPublicKey();
        sig.init(new BcPGPContentVerifierBuilderProvider(), k);
        sig.update(data);
        if (sig.verify()) {
            return k;
        }
    }
    return null;
}