Example usage for org.bouncycastle.openpgp PGPSignatureList get

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

Introduction

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

Prototype

public PGPSignature get(int index) 

Source Link

Usage

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

License:Apache License

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

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

License:Open Source License

/**
 * Verify a PGP clearText-signature.//  w  ww  .j a va  2 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.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 {/*  w ww.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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check the signature in clear-signed data
 *//*w w  w . j a  v  a  2 s .c om*/
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 one-pass signature//from  www.j  a  v  a 2s  .c o m
 */
private boolean checkOnePassSignature(OutputStream out, PGPOnePassSignatureList p1, PGPObjectFactory pgpFact,
        PGPPublicKeyRingCollection pgpRing) throws PGPException {
    try {
        PGPOnePassSignature ops = null;
        PGPPublicKey key = null;

        int count = 0;
        while (count < p1.size()) {
            ops = p1.get(count);
            key = pgpRing.getPublicKey(ops.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();

        ops.initVerify(key, "BC");

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

        out.close();

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

        return ops.verify(p3.get(0));
    } 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  ww  . j  a v a 2 s .  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.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 w w  . ja  v  a2  s . c  o  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.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

public boolean decryptVerifyMessage(InputStream in, OutputStream out, String jid)
        throws IOException, PGPException, SignatureException {
    in = new ArmoredInputStream(in);

    PGPObjectFactory plainFact = new PGPObjectFactory(
            ((PGPPublicKeyEncryptedData) ((PGPEncryptedDataList) new PGPObjectFactory(in).nextObject())
                    .getEncryptedDataObjects().next())
                            .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(PROVIDER)
                                    .build(kp.getPrivateKey())));

    PGPOnePassSignatureList onePassSignatureList = null;
    PGPSignatureList signatureList = null;
    PGPCompressedData compressedData = null;

    Object obj = plainFact.nextObject();
    ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();

    while (obj != null) {
        if (obj instanceof PGPCompressedData) {
            compressedData = (PGPCompressedData) obj;
            plainFact = new PGPObjectFactory(compressedData.getDataStream());
            obj = plainFact.nextObject();
        }/*w w w. j a  va2 s  . c  o m*/
        if (obj instanceof PGPLiteralData) {
            Streams.pipeAll(((PGPLiteralData) obj).getInputStream(), actualOutput);
        } else if (obj instanceof PGPOnePassSignatureList) {
            onePassSignatureList = (PGPOnePassSignatureList) obj;
        } else if (obj instanceof PGPSignatureList) {
            signatureList = (PGPSignatureList) obj;
        } else {
            throw new PGPException("message unknown message type.");
        }
        obj = plainFact.nextObject();
    }

    actualOutput.close();
    byte[] output = actualOutput.toByteArray();

    PGPOnePassSignature ops = onePassSignatureList.get(0);
    ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER), keys.get(jid));
    ops.update(output);

    out.write(output);
    out.flush();
    out.close();

    return ops.verify(signatureList.get(0));
}