Example usage for org.bouncycastle.bcpg ArmoredInputStream isClearText

List of usage examples for org.bouncycastle.bcpg ArmoredInputStream isClearText

Introduction

In this page you can find the example usage for org.bouncycastle.bcpg ArmoredInputStream isClearText.

Prototype

public boolean isClearText() 

Source Link

Usage

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

License:Open Source License

/**
 * Verify a PGP clearText-signature.//www  .  j av  a2  s.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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check the signature in clear-signed data
 *///from   w w  w .  j  a v a 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.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  w  w  w .ja v  a2  s.co  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:net.staticsnow.nexus.repository.apt.internal.snapshot.AptSnapshotFacetSupport.java

License:Open Source License

protected Iterable<SnapshotItem> collectSnapshotItems(SnapshotComponentSelector selector) throws IOException {
    AptFacet aptFacet = getRepository().facet(AptFacet.class);

    List<SnapshotItem> result = new ArrayList<>();
    List<SnapshotItem> releaseIndexItems = fetchSnapshotItems(FacetHelper.getReleaseIndexSpecifiers(aptFacet));
    Map<SnapshotItem.Role, SnapshotItem> itemsByRole = new HashMap<>(releaseIndexItems.stream()
            .collect(Collectors.toMap((SnapshotItem item) -> item.specifier.role, item -> item)));
    InputStream releaseStream = null;
    if (itemsByRole.containsKey(SnapshotItem.Role.RELEASE_INDEX)) {
        releaseStream = itemsByRole.get(SnapshotItem.Role.RELEASE_INDEX).content.openInputStream();
    } else {//  w  w  w .j  av a 2 s .  c  om
        InputStream is = itemsByRole.get(SnapshotItem.Role.RELEASE_INLINE_INDEX).content.openInputStream();
        if (is != null) {
            ArmoredInputStream aIs = new ArmoredInputStream(is);
            releaseStream = new FilterInputStream(aIs) {
                boolean done = false;

                public int read() throws IOException {
                    if (done) {
                        return -1;
                    }
                    int c = aIs.read();
                    if (c < 0 || !aIs.isClearText()) {
                        done = true;
                        return -1;
                    }
                    return c;
                }
            };
        }
    }

    if (releaseStream == null) {
        throw new IOException("Invalid upstream repository:  no release index present");
    }

    Release release;
    try {
        ControlFile index = new ControlFileParser().parseControlFile(releaseStream);
        release = new Release(index);
    } finally {
        releaseStream.close();
    }

    result.addAll(releaseIndexItems);

    if (aptFacet.isFlat()) {
        result.addAll(fetchSnapshotItems(FacetHelper.getReleasePackageIndexes(aptFacet, null, null)));
    } else {
        List<String> archs = selector.getArchitectures(release);
        List<String> comps = selector.getComponents(release);
        for (String arch : archs) {
            for (String comp : comps) {
                result.addAll(fetchSnapshotItems(FacetHelper.getReleasePackageIndexes(aptFacet, comp, arch)));
            }
        }
    }

    // TODO: Verify checksums and redownload if needed.
    return result;
}

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;//w w w. jav  a 2 s.co  m
    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;// www.ja  v a2  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;
}

From source file:org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyOperation.java

License:Open Source License

@NonNull
private DecryptVerifyResult executeInternal(PgpDecryptVerifyInputParcel input, CryptoInputParcel cryptoInput,
        InputData inputData, OutputStream outputStream) {
    try {/*from   w ww  . j a v  a  2  s  . c o m*/
        if (input.getDetachedSignature() != null) {
            Log.d(Constants.TAG, "Detached signature present, verifying with this signature only");

            return verifyDetachedSignature(input, inputData, outputStream, 0);
        } else {
            // automatically works with PGP ascii armor and PGP binary
            InputStream inputStream = PGPUtil.getDecoderStream(inputData.getInputStream());

            if (inputStream instanceof ArmoredInputStream) {
                ArmoredInputStream aIn = (ArmoredInputStream) inputStream;
                // it is ascii armored
                Log.d(Constants.TAG, "ASCII Armor Header Line: " + aIn.getArmorHeaderLine());

                if (aIn.isClearText()) {
                    // a cleartext signature, verify it with the other method
                    return verifyCleartextSignature(input, aIn, outputStream, 0);
                } else {
                    // else: ascii armored encryption! go on...
                    return decryptVerify(input, cryptoInput, inputData, inputStream, outputStream, 0);
                }
            } else {
                return decryptVerify(input, cryptoInput, inputData, inputStream, outputStream, 0);
            }
        }
    } catch (PGPException e) {
        Log.d(Constants.TAG, "PGPException", e);
        OperationLog log = new OperationLog();
        log.add(LogType.MSG_DC_ERROR_PGP_EXCEPTION, 1);
        return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
    } catch (DecoderException | ArrayIndexOutOfBoundsException e) {
        // these can happen if assumptions in JcaPGPObjectFactory.nextObject() aren't
        // fulfilled, so we need to catch them here to handle this gracefully
        Log.d(Constants.TAG, "data error", e);
        OperationLog log = new OperationLog();
        log.add(LogType.MSG_DC_ERROR_IO, 1);
        return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
    } catch (IOException e) {
        Log.d(Constants.TAG, "IOException", e);
        OperationLog log = new OperationLog();
        log.add(LogType.MSG_DC_ERROR_IO, 1);
        return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
    }
}

From source file:org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyOperation.java

License:Open Source License

/**
 * This method verifies cleartext signatures
 * as defined in http://tools.ietf.org/html/rfc4880#section-7
 * <p/>/*  w w  w .  j  a  va  2s  .  co  m*/
 * The method is heavily based on
 * pg/src/main/java/org/bouncycastle/openpgp/examples/ClearSignedFileProcessor.java
 */
@NonNull
private DecryptVerifyResult verifyCleartextSignature(PgpDecryptVerifyInputParcel input, ArmoredInputStream aIn,
        OutputStream outputStream, int indent) throws IOException, PGPException {

    OperationLog log = new OperationLog();

    byte[] clearText;
    { // read cleartext
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        updateProgress(R.string.progress_reading_data, 0, 100);

        ByteArrayOutputStream lineOut = new ByteArrayOutputStream();
        int lookAhead = readInputLine(lineOut, aIn);
        byte[] lineSep = getLineSeparator();

        byte[] line = lineOut.toByteArray();
        out.write(line, 0, getLengthWithoutSeparator(line));
        out.write(lineSep);

        while (lookAhead != -1 && aIn.isClearText()) {
            lookAhead = readInputLine(lineOut, lookAhead, aIn);
            line = lineOut.toByteArray();
            out.write(line, 0, getLengthWithoutSeparator(line));
            out.write(lineSep);
        }

        out.close();
        clearText = out.toByteArray();
    }

    if (outputStream != null) {
        outputStream.write(clearText);
        outputStream.close();
    }

    updateProgress(R.string.progress_processing_signature, 60, 100);
    JcaSkipMarkerPGPObjectFactory pgpFact = new JcaSkipMarkerPGPObjectFactory(aIn);

    PgpSignatureChecker signatureChecker = new PgpSignatureChecker(mProviderHelper, input.getSenderAddress());

    Object o = pgpFact.nextObject();
    if (!signatureChecker.initializeSignature(o, log, indent + 1)) {
        log.add(LogType.MSG_DC_ERROR_INVALID_DATA, 0);
        return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
    }

    if (signatureChecker.isInitialized()) {
        try {
            updateProgress(R.string.progress_verifying_signature, 90, 100);

            signatureChecker.updateSignatureWithCleartext(clearText);
            signatureChecker.verifySignature(log, indent);

        } catch (SignatureException e) {
            Log.d(Constants.TAG, "SignatureException", e);
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        }
    }

    updateProgress(R.string.progress_done, 100, 100);

    log.add(LogType.MSG_DC_OK, indent);

    OpenPgpMetadata metadata = new OpenPgpMetadata("", "text/plain", -1, clearText.length, "utf-8");

    DecryptVerifyResult result = new DecryptVerifyResult(DecryptVerifyResult.RESULT_OK, log);
    result.setSignatureResult(signatureChecker.getSignatureResult());
    result.setDecryptionResult(new OpenPgpDecryptionResult(OpenPgpDecryptionResult.RESULT_NOT_ENCRYPTED));
    result.setDecryptionMetadata(metadata);
    return result;
}

From source file:tests.Strings.Licensee.java

public static int checkLicense() {
    int rc = 0x80000;
    System.out.println("int rc = 0x80000: " + rc);
    boolean newl = false;
    int ch;/*from w  w w. j  av  a  2  s . co  m*/

    try {
        InputStream in = new FileInputStream(new File(LICENSEE));
        InputStream ks = new FileInputStream(new File(PUBRING));
        PGPPublicKey pk = PGPHelper.readPublicKey(ks, SIGNER);
        ArmoredInputStream ain = new ArmoredInputStream(in, true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(ain));
        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 == '\r' || ch == '\n') {
                newl = true;
                continue;
            }
            out.write((byte) ch);
        }
        String line;
        //            while ((line = br.readLine()) != null) {
        //                out.write(line.getBytes(Charset.forName("UTF-8")));
        //                out.write('\n');
        //            }

        //            ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //            if (ain != null) {
        //                br = new BufferedReader(new InputStreamReader(ain));
        //                PrintStream p = new PrintStream(baos);
        //                p.println();
        //                p.println();
        //                try {
        //                    while (br.ready() && ain.isClearText())
        //                        p.println(br.readLine());
        //                } catch (Exception ignored) {
        //                    // NOPMD ignore error
        //                }
        //            }
        PGPObjectFactory pgpf = new PGPObjectFactory(ain, new BcKeyFingerprintCalculator());
        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);
                }
                //                    while ((line = br.readLine()) != null) {
                //                        out.write(line.getBytes());
                //                        out.write('\n');
                //                    }
                sig.update(out.toByteArray());
                if (sig.verify()) {
                    rc &= 0x7FFFF;
                    System.out.println("sig.verify(): " + rc);
                    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;
                                System.out.println("rc |= 0x40000: " + rc);
                            }
                        }
                        matcher = p2.matcher(s);
                        if (matcher.find() && matcher.groupCount() == 2) {
                            rc |= Integer.parseInt(matcher.group(2));
                            System.out.println("rc |= Integer.parseInt(matcher.group(2)): " + rc);
                        }
                    }
                }
            }
            if (!Arrays.equals(Q2.PUBKEYHASH, mac.doFinal(pk.getEncoded()))) {
                rc |= 0x20000;
                System.out.println("rc |= 0x20000: " + rc);
            }

        }
    } catch (Exception ignored) {
        // NOPMD: signature isn't good
    }
    return rc;
}