Example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentVerifierBuilderProvider JcaPGPContentVerifierBuilderProvider

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentVerifierBuilderProvider JcaPGPContentVerifierBuilderProvider

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentVerifierBuilderProvider JcaPGPContentVerifierBuilderProvider.

Prototype

public JcaPGPContentVerifierBuilderProvider() 

Source Link

Usage

From source file:cc.arduino.packages.security.ClearSignedVerifier.java

License:Open Source License

/**
 * Verify a PGP clearText-signature./* w w  w. j  a v a  2s. co 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.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();
        }// ww w.ja va 2  s . co  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));
}

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//w w  w. j  a v  a 2 s.  com
 */
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:crypttools.PGPCryptoBC.java

License:Open Source License

public boolean validateData(String data, String publicKey) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    File fileToVerify = File.createTempFile("temp", ".privateScrap");
    FileUtils.writeStringToFile(fileToVerify, data);

    File publicKeyFile = File.createTempFile("temp", ".publicScrap");
    // Creates an exception
    //        System.out.println(this.armoredPublicKey);
    //        String armoredKeyString = getPublicKey();
    //        System.out.println(armoredKeyString);
    FileUtils.writeStringToFile(publicKeyFile, publicKey);
    //FileUtils.writeStringToFile(publicKeyFile, new String(this.armoredPublicKey, "UTF-8"));

    try {//from  w  w w.  j a v  a 2s .  co m
        InputStream in = PGPUtil.getDecoderStream(new FileInputStream(fileToVerify));

        PGPObjectFactory pgpObjFactory = new PGPObjectFactory(in);
        PGPCompressedData compressedData = (PGPCompressedData) pgpObjFactory.nextObject();

        //Get the signature from the file

        pgpObjFactory = new PGPObjectFactory(compressedData.getDataStream());
        PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) pgpObjFactory.nextObject();
        PGPOnePassSignature onePassSignature = onePassSignatureList.get(0);

        //Get the literal data from the file

        PGPLiteralData pgpLiteralData = (PGPLiteralData) pgpObjFactory.nextObject();
        InputStream literalDataStream = pgpLiteralData.getInputStream();

        InputStream keyIn = new FileInputStream(publicKeyFile);
        PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
        PGPPublicKey key = pgpRing.getPublicKey(onePassSignature.getKeyID());

        FileOutputStream literalDataOutputStream = new FileOutputStream(pgpLiteralData.getFileName());
        onePassSignature.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), key);

        int ch;
        while ((ch = literalDataStream.read()) >= 0) {
            onePassSignature.update((byte) ch);
            literalDataOutputStream.write(ch);
        }

        literalDataOutputStream.close();

        //Get the signature from the written out file

        PGPSignatureList p3 = (PGPSignatureList) pgpObjFactory.nextObject();
        PGPSignature signature = p3.get(0);

        //Verify the two signatures
        boolean valid = onePassSignature.verify(signature);
        return valid;
    } catch (Exception e) {
        System.out.println("Got an Exception: " + e.getMessage());
        return false;
        //do something clever with the exception
    } finally {
        fileToVerify.delete();
        publicKeyFile.delete();
    }
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public boolean verifyFileDetached(String data, String signature, String publicKey) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    InputStream keyInputStream = new BufferedInputStream(IOUtils.toInputStream(publicKey, "UTF-8"));
    InputStream sigInputStream = PGPUtil
            .getDecoderStream(new BufferedInputStream(IOUtils.toInputStream(signature, "UTF-8")));

    PGPObjectFactory pgpObjFactory = new PGPObjectFactory(sigInputStream);
    PGPSignatureList pgpSigList = null;/* w  w w.  j  a v a 2  s .  c  o  m*/

    Object obj = pgpObjFactory.nextObject();
    if (obj instanceof PGPCompressedData) {
        PGPCompressedData c1 = (PGPCompressedData) obj;
        pgpObjFactory = new PGPObjectFactory(c1.getDataStream());
        pgpSigList = (PGPSignatureList) pgpObjFactory.nextObject();
    } else {
        pgpSigList = (PGPSignatureList) obj;
    }

    PGPPublicKeyRingCollection pgpPubRingCollection = new PGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(keyInputStream));
    InputStream fileInputStream = new BufferedInputStream(IOUtils.toInputStream(data, "UTF-8"));
    PGPSignature sig = pgpSigList.get(0);
    PGPPublicKey pubKey = pgpPubRingCollection.getPublicKey(sig.getKeyID());
    sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), pubKey);

    int ch;
    while ((ch = fileInputStream.read()) >= 0) {
        sig.update((byte) ch);
    }

    fileInputStream.close();
    keyInputStream.close();
    sigInputStream.close();

    if (sig.verify()) {
        return true;
    } else {
        return false;
    }
}

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

License:Apache License

protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList)
        throws IOException, PGPException, NoSuchProviderException {

    for (int i = 0; i < signatureList.size(); i++) {
        PGPOnePassSignature signature = signatureList.get(i);
        // Determine public key from signature keyId
        PGPPublicKey sigPublicKey = PGPDataFormatUtil.findPublicKeyWithKeyId(exchange.getContext(),
                findSignatureKeyFileName(exchange), findSignatureKeyRing(exchange), signature.getKeyID(),
                false);/*  ww w . j  av  a  2 s . c  o m*/
        if (sigPublicKey == null) {
            continue;
        }
        // choose that signature for which a public key exists!
        signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey);
        return signature;
    }
    if (signatureList.isEmpty()) {
        return null;
    } else {
        throw new IllegalArgumentException(
                "No public key found fitting to the signature key Id; cannot verify the signature");
    }

}

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

License:Apache License

protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList)
        throws Exception {
    if (SIGNATURE_VERIFICATION_OPTION_IGNORE.equals(getSignatureVerificationOption())) {
        return null;
    }//from w  w w  .j  a  v  a2s  . c  o m
    if (SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED.equals(getSignatureVerificationOption())) {
        throw new PGPException(
                "PGP message contains a signature although a signature is not expected. Either change the configuration of the PGP decryptor or send a PGP message with no signature.");
    }
    List<String> allowedUserIds = determineSignaturenUserIds(exchange);
    for (int i = 0; i < signatureList.size(); i++) {
        PGPOnePassSignature signature = signatureList.get(i);
        // Determine public key from signature keyId
        PGPPublicKey sigPublicKey = publicKeyAccessor.getPublicKey(exchange, signature.getKeyID(),
                allowedUserIds);
        if (sigPublicKey == null) {
            continue;
        }
        // choose that signature for which a public key exists!
        signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey);
        return signature;
    }
    if (signatureList.isEmpty()) {
        return null;
    } else {
        throw new IllegalArgumentException(
                "Cannot verify the PGP signature: No public key found for the key ID(s) contained in the PGP signature(s). "
                        + "Either the received PGP message contains a signature from an unexpected sender or the Public Keyring does not contain the public key of the sender.");
    }

}

From source file:org.elasticsearch.plugins.InstallPluginCommand.java

License:Apache License

/**
 * Verify the signature of the downloaded plugin ZIP. The signature is obtained from the source of the downloaded plugin by appending
 * ".asc" to the URL. It is expected that the plugin is signed with the Elastic signing key with ID D27D666CD88E42B4.
 *
 * @param zip       the path to the downloaded plugin ZIP
 * @param urlString the URL source of the downloade plugin ZIP
 * @throws IOException  if an I/O exception occurs reading from various input streams
 * @throws PGPException if the PGP implementation throws an internal exception during verification
 *///from  w w w .jav  a  2 s  .c o  m
void verifySignature(final Path zip, final String urlString) throws IOException, PGPException {
    final String ascUrlString = urlString + ".asc";
    final URL ascUrl = openUrl(ascUrlString);
    try (
            // fin is a file stream over the downloaded plugin zip whose signature to verify
            InputStream fin = pluginZipInputStream(zip);
            // sin is a URL stream to the signature corresponding to the downloaded plugin zip
            InputStream sin = urlOpenStream(ascUrl);
            // ain is a input stream to the public key in ASCII-Armor format (RFC4880)
            InputStream ain = new ArmoredInputStream(getPublicKey())) {
        final JcaPGPObjectFactory factory = new JcaPGPObjectFactory(PGPUtil.getDecoderStream(sin));
        final PGPSignature signature = ((PGPSignatureList) factory.nextObject()).get(0);

        // validate the signature has key ID matching our public key ID
        final String keyId = Long.toHexString(signature.getKeyID()).toUpperCase(Locale.ROOT);
        if (getPublicKeyId().equals(keyId) == false) {
            throw new IllegalStateException(
                    "key id [" + keyId + "] does not match expected key id [" + getPublicKeyId() + "]");
        }

        // compute the signature of the downloaded plugin zip
        final PGPPublicKeyRingCollection collection = new PGPPublicKeyRingCollection(ain,
                new JcaKeyFingerprintCalculator());
        final PGPPublicKey key = collection.getPublicKey(signature.getKeyID());
        signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(new BouncyCastleProvider()), key);
        final byte[] buffer = new byte[1024];
        int read;
        while ((read = fin.read(buffer)) != -1) {
            signature.update(buffer, 0, read);
        }

        // finally we verify the signature of the downloaded plugin zip matches the expected signature
        if (signature.verify() == false) {
            throw new IllegalStateException("signature verification for [" + urlString + "] failed");
        }
    }
}

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  w ww.j  a v  a  2  s.  com
    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;
}

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

License:Open Source License

public static int checkLicense() {
    int rc = 0x80000;
    boolean newl = false;
    int ch;//w  w w.java 2  s  .c o m

    try {
        InputStream in = Q2.class.getClassLoader().getResourceAsStream(Q2.LICENSEE);
        InputStream ks = Q2.class.getClassLoader().getResourceAsStream(PUBRING);
        PGPPublicKey pk = readPublicKey(ks, SIGNER);
        ArmoredInputStream ain = new ArmoredInputStream(in, true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(pk.getFingerprint(), "HmacSHA256"));

        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());
                if (sig.verify()) {
                    rc &= 0x7FFFF;
                    ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
                    String s;
                    Pattern p1 = Pattern.compile("\\s(valid through:)\\s(\\d\\d\\d\\d-\\d\\d-\\d\\d)?",
                            Pattern.CASE_INSENSITIVE);
                    Pattern p2 = Pattern.compile("\\s(instances:)\\s([\\d]{0,4})?", Pattern.CASE_INSENSITIVE);
                    while ((s = reader.readLine()) != null) {
                        Matcher matcher = p1.matcher(s);
                        if (matcher.find() && matcher.groupCount() == 2) {
                            String lDate = matcher.group(2);
                            if (lDate.compareTo(Q2.getBuildTimestamp().substring(0, 10)) < 0) {
                                rc |= 0x40000;
                            }
                        }
                        matcher = p2.matcher(s);
                        if (matcher.find() && matcher.groupCount() == 2) {
                            rc |= Integer.parseInt(matcher.group(2));
                        }
                    }
                }
            }
            if (!Arrays.equals(Q2.PUBKEYHASH, mac.doFinal(pk.getEncoded())))
                rc |= 0x20000;
        }
    } catch (Exception ignored) {
        // NOPMD: signature isn't good
    }
    return rc;
}