Example usage for org.bouncycastle.openpgp.operator.bc BcKeyFingerprintCalculator BcKeyFingerprintCalculator

List of usage examples for org.bouncycastle.openpgp.operator.bc BcKeyFingerprintCalculator BcKeyFingerprintCalculator

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.bc BcKeyFingerprintCalculator BcKeyFingerprintCalculator.

Prototype

BcKeyFingerprintCalculator

Source Link

Usage

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 {/*  www  . j ava  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.contributions.GPGDetachedSignatureVerifier.java

License:Open Source License

private PGPPublicKey readPublicKey(InputStream input, String keyId) throws IOException, PGPException {
    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input),
            new BcKeyFingerprintCalculator());

    Iterator keyRingIter = pgpPub.getKeyRings();
    while (keyRingIter.hasNext()) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();

        Iterator keyIter = keyRing.getPublicKeys();
        while (keyIter.hasNext()) {
            PGPPublicKey key = (PGPPublicKey) keyIter.next();

            if (Long.toHexString(key.getKeyID()).toUpperCase().endsWith(keyId)) {
                return key;
            }/* www  .  java 2  s . com*/
        }
    }

    throw new IllegalArgumentException("Can't find encryption key in key ring.");
}

From source file:com.bekwam.resignator.util.CryptUtils.java

License:Apache License

private byte[] decrypt(byte[] encrypted, char[] passPhrase)
        throws IOException, PGPException, NoSuchProviderException {
    try (InputStream in = new ByteArrayInputStream(encrypted)) {
        InputStream decoderIn = PGPUtil.getDecoderStream(in);

        PGPObjectFactory pgpF = new PGPObjectFactory(decoderIn, new BcKeyFingerprintCalculator());
        PGPEncryptedDataList enc;//from ww w.  j a v a2  s.c  o m
        Object o = pgpF.nextObject();

        if (o == null) { // decryption failed; there is no next object

            //
            // This could arise if there is a problem with the underlying file.
            //

            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Field could not be decrypted. (Config file modified outside of app?)  Returning input bytes as encrypted bytes.");
            }

            return encrypted;
        }

        //
        // the first object might be a PGP marker packet.
        //

        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpF.nextObject(); // i don't think this will be used
        }

        PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);

        InputStream clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(
                new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC")
                        .build(passPhrase));

        return Streams.readAll(clear);
    }
}

From source file:com.github.s4u.plugins.PGPKeysCache.java

License:Apache License

PGPPublicKey getKey(long keyID) throws IOException, PGPException {

    File keyFile = null;//from   www.  j  a  v a2s .  c  o  m
    PGPPublicKey key = null;

    try {
        String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff),
                keyID);

        keyFile = new File(cachePath, path);
        if (!keyFile.exists()) {
            receiveKey(keyFile, keyID);
        }

        InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile));
        PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn,
                new BcKeyFingerprintCalculator());
        key = pgpRing.getPublicKey(keyID);
    } finally {
        if (key == null) {
            deleteFile(keyFile);
        }
    }
    return key;
}

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 .  j ava  2s. 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.CryptimUtils.java

License:BEER-WARE LICENSE

/**
 * Parse a PGP public key from a string/*w  ww.  j  ava2 s  . c  om*/
 * @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.google.e2e.bcdriver.Decryptor.java

License:Apache License

static final Result decrypt(InputStream in, PGPPrivateKey decryptKey, KeyChecker.PKR verify)
        throws IOException, PGPException, SignatureException {
    PGPObjectFactory pgpf = new PGPObjectFactory(PGPUtil.getDecoderStream(in),
            new BcKeyFingerprintCalculator());
    Object o = pgpf.nextObject();
    if (o == null) {
        throw new IOException("No encrypted content");
    }//from ww w  . java  2s. c  o  m
    PGPEncryptedDataList enclist;
    if (o instanceof PGPEncryptedDataList) {
        enclist = (PGPEncryptedDataList) o;
    } else {
        enclist = (PGPEncryptedDataList) (pgpf.nextObject());
    }
    Iterator<PGPPublicKeyEncryptedData> pkedi = Util.getTypedIterator(enclist.getEncryptedDataObjects(),
            PGPPublicKeyEncryptedData.class);

    if (pkedi == null) {
        throw new IOException("no encrypted data found!");
    }
    while (pkedi.hasNext()) {
        PGPPublicKeyEncryptedData pked = pkedi.next();
        if (pked.getKeyID() == decryptKey.getKeyID()) {
            return decryptSignedContent(pked, decryptKey, verify);
        }
    }
    return null;
}

From source file:com.google.e2e.bcdriver.Decryptor.java

License:Apache License

private static final Result verifySignedContent(InputStream inp, KeyChecker.PKR verify)
        throws IOException, PGPException, SignatureException {
    PGPObjectFactory plainFact = new PGPObjectFactory(inp, new BcKeyFingerprintCalculator());

    Object msg = plainFact.nextObject();

    // swap in uncompressed data if necessary
    if (msg instanceof PGPCompressedData) {
        PGPCompressedData cData = (PGPCompressedData) msg;
        plainFact = new PGPObjectFactory(cData.getDataStream(), new BcKeyFingerprintCalculator());
        msg = plainFact.nextObject();//from ww w.  j  a v a2  s .  c o  m
    }

    PGPOnePassSignatureList onePassSigList;
    PGPLiteralData lData;
    if (msg instanceof PGPOnePassSignatureList) {
        onePassSigList = (PGPOnePassSignatureList) msg;
        lData = (PGPLiteralData) plainFact.nextObject();
    } else {
        onePassSigList = null;
        lData = (PGPLiteralData) msg;
    }

    if ((verify != null) && (onePassSigList == null)) {
        throw new IOException("Message is unsigned");
    }

    PGPOnePassSignature onePassSig = null;
    int onePassStartIndex = -1;
    PGPPublicKey verifyKey = null;
    if (verify != null) {
        for (int i = 0; i < onePassSigList.size(); i++) {
            List<PGPPublicKey> candidates = verify.getSigningKeysByKeyID(onePassSigList.get(i).getKeyID());
            if (candidates.size() == 1) {
                onePassSig = onePassSigList.get(i);
                onePassStartIndex = i;
                verifyKey = candidates.get(0);
                break;
            }
        }
    }

    if ((verify != null) && (onePassSig == null)) {
        throw new IOException("Failed to find a signature from verifying key");
    }

    if (onePassSig != null) {
        onePassSig.init(new BcPGPContentVerifierBuilderProvider(), verifyKey);
    }
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    InputStream lin = lData.getInputStream();
    byte buf[] = new byte[8192];
    int nread;
    while ((nread = lin.read(buf)) > 0) {
        baout.write(buf, 0, nread);
        if (onePassSig != null) {
            onePassSig.update(buf, 0, nread);
        }
    }
    baout.close();
    if (onePassSig != null) {
        PGPSignatureList sigList = (PGPSignatureList) plainFact.nextObject();
        // One pass signature trailers occur in LIFO order compared to their
        // location in the header.
        PGPSignature sig = sigList.get(sigList.size() - 1 - onePassStartIndex);
        if (!onePassSig.verify(sig)) {
            throw new IOException("Invalid signature in message");
        }
    }
    return new Result(baout.toByteArray(), lData.getFileName());
}

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 ww.ja  va2  s . 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.Util.java

License:Apache License

static final PGPPublicKeyRing readPublicKeyRing(File path) throws IOException, PGPException {
    InputStream in = null;// w  ww  . ja v  a2 s .  com
    try {
        in = PGPUtil.getDecoderStream(new BufferedInputStream(new FileInputStream(path)));
        return new PGPPublicKeyRing(in, new BcKeyFingerprintCalculator());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignore) {
                ; // do nothing
            }
        }
    }
}