Example usage for org.bouncycastle.bcpg ArmoredInputStream ArmoredInputStream

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

Introduction

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

Prototype

public ArmoredInputStream(InputStream in) throws IOException 

Source Link

Document

Create a stream for reading a PGP armoured message, parsing up to a header and then reading the data that follows.

Usage

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

License:Open Source License

/**
 * Verify a PGP clearText-signature./* www.j  a va2 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.goodvikings.cryptim.api.CryptimUtils.java

License:BEER-WARE LICENSE

/**
 * Parse a PGP public key from a string//from  www  . ja  v a2  s.co m
 * @param keyString The String holding the PGP public key
 * @return PGPPublicKey
 * @throws IOException on an IO exception
 */
public static PGPPublicKey parsePublicKey(String keyString) throws IOException {
    return new PGPPublicKeyRing(new ArmoredInputStream(new ByteArrayInputStream(keyString.getBytes())),
            new BcKeyFingerprintCalculator()).getPublicKey();
}

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();
        }/*from   w  w  w .j av a 2s.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.google.gerrit.gpg.PublicKeyStore.java

License:Apache License

/**
 * Read public keys with the given key ID.
 * <p>//  w  ww .  j a va  2  s  .c om
 * Keys should not be trusted unless checked with {@link PublicKeyChecker}.
 * <p>
 * Multiple calls to this method use the same state of the key ref; to reread
 * the ref, call {@link #close()} first.
 *
 * @param keyId key ID.
 * @return any keys found that could be successfully parsed.
 * @throws PGPException if an error occurred parsing the key data.
 * @throws IOException if an error occurred reading the repository data.
 */
public PGPPublicKeyRingCollection get(long keyId) throws PGPException, IOException {
    if (reader == null) {
        load();
    }
    if (notes == null) {
        return empty();
    }
    Note note = notes.getNote(keyObjectId(keyId));
    if (note == null) {
        return empty();
    }

    List<PGPPublicKeyRing> keys = new ArrayList<>();
    try (InputStream in = reader.open(note.getData(), OBJ_BLOB).openStream()) {
        while (true) {
            @SuppressWarnings("unchecked")
            Iterator<Object> it = new BcPGPObjectFactory(new ArmoredInputStream(in)).iterator();
            if (!it.hasNext()) {
                break;
            }
            Object obj = it.next();
            if (obj instanceof PGPPublicKeyRing) {
                keys.add((PGPPublicKeyRing) obj);
            }
            checkState(!it.hasNext(), "expected one PGP object per ArmoredInputStream");
        }
        return new PGPPublicKeyRingCollection(keys);
    }
}

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

License:Apache License

private PGPSignature readSignature(PushCertificate cert) throws IOException {
    ArmoredInputStream in = new ArmoredInputStream(
            new ByteArrayInputStream(Constants.encode(cert.getSignature())));
    PGPObjectFactory factory = new BcPGPObjectFactory(in);
    Object obj;/*from   w w w.j  a va  2 s.  com*/
    while ((obj = factory.nextObject()) != null) {
        if (obj instanceof PGPSignatureList) {
            PGPSignatureList sigs = (PGPSignatureList) obj;
            if (!sigs.isEmpty()) {
                return sigs.get(0);
            }
        }
    }
    return null;
}

From source file:com.google.gerrit.gpg.server.PostGpgKeys.java

License:Apache License

private List<PGPPublicKeyRing> readKeysToAdd(Input input, Set<Fingerprint> toRemove)
        throws BadRequestException, IOException {
    if (input.add == null || input.add.isEmpty()) {
        return ImmutableList.of();
    }/*  www .jav a 2  s.  co  m*/
    List<PGPPublicKeyRing> keyRings = new ArrayList<>(input.add.size());
    for (String armored : input.add) {
        try (InputStream in = new ByteArrayInputStream(armored.getBytes(UTF_8));
                ArmoredInputStream ain = new ArmoredInputStream(in)) {
            @SuppressWarnings("unchecked")
            List<Object> objs = Lists.newArrayList(new BcPGPObjectFactory(ain));
            if (objs.size() != 1 || !(objs.get(0) instanceof PGPPublicKeyRing)) {
                throw new BadRequestException("Expected exactly one PUBLIC KEY BLOCK");
            }
            PGPPublicKeyRing keyRing = (PGPPublicKeyRing) objs.get(0);
            if (toRemove.contains(new Fingerprint(keyRing.getPublicKey().getFingerprint()))) {
                throw new BadRequestException(
                        "Cannot both add and delete key: " + keyToString(keyRing.getPublicKey()));
            }
            keyRings.add(keyRing);
        }
    }
    return keyRings;
}

From source file:com.google.gerrit.gpg.testutil.TestKey.java

License:Apache License

private static ArmoredInputStream newStream(String armored) throws IOException {
    return new ArmoredInputStream(new ByteArrayInputStream(Constants.encode(armored)));
}

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  . j  a v a  2 s .  c  om*/
 */
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:com.playonlinux.core.gpg.SignatureChecker.java

License:Open Source License

public Boolean check() {
    final PGPPublicKey pgpSigningKey = readPublicKey(new ByteArrayInputStream(publicKey.getBytes()));

    final ArmoredInputStream armoredInputStream;
    try {//from ww w  .  ja v a  2s  .com
        armoredInputStream = new ArmoredInputStream(new ByteArrayInputStream(signature.getBytes()));
    } catch (IOException e) {
        throw new SignatureException("Failed to verify signature", e);
    }

    final PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(armoredInputStream);

    try {
        final Object nextObject = pgpObjectFactory.nextObject();
        PGPSignature pgpSignature = null;
        if (nextObject instanceof PGPSignatureList) {
            PGPSignatureList list = (PGPSignatureList) nextObject;
            if (!list.isEmpty()) {
                pgpSignature = list.get(0);
            }
        }

        if (pgpSignature == null) {
            return false;
        }

        initVerify(pgpSignature, pgpSigningKey);

        pgpSignature.update(signedData.getBytes());
        return pgpSignature.verify();
    } catch (IOException | PGPException | NoSuchProviderException | java.security.SignatureException e) {
        throw new SignatureException("Failed to verify signature", e);
    }
}

From source file:com.playonlinux.utils.SignatureChecker.java

License:Open Source License

public Boolean check()
        throws IOException, CMSException, PGPException, NoSuchProviderException, SignatureException {
    PGPPublicKey pgpSigningKey = readPublicKey(new ByteArrayInputStream(publicKey.getBytes()));

    ArmoredInputStream armoredInputStream = new ArmoredInputStream(
            new ByteArrayInputStream(signature.getBytes()));

    PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(armoredInputStream);

    Object nextObject = pgpObjectFactory.nextObject();
    PGPSignature pgpSignature = null;/*from  www  .j a v  a2  s . c  o m*/
    if (nextObject instanceof PGPSignatureList) {
        PGPSignatureList list = (PGPSignatureList) nextObject;
        if (!list.isEmpty()) {
            pgpSignature = list.get(0);
        }
    }

    if (pgpSignature == null) {
        return false;
    }

    try {
        pgpSignature.initVerify(pgpSigningKey, "BC");
    } catch (NoSuchProviderException e) {
        logger.info("No security provider found. Adding bouncy castle", e);
        Security.addProvider(new BouncyCastleProvider());
        pgpSignature.initVerify(pgpSigningKey, "BC");
    }

    pgpSignature.update(signedData.getBytes());
    return pgpSignature.verify();
}