Example usage for org.bouncycastle.openpgp PGPPublicKey getKeyID

List of usage examples for org.bouncycastle.openpgp PGPPublicKey getKeyID

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPPublicKey getKeyID.

Prototype

public long getKeyID() 

Source Link

Document

Return the keyID associated with the public key.

Usage

From source file:SELSKeyGen.java

License:Open Source License

private static void CKeyGen(String userid, String randomStr, String LSPass, int expsec) throws Exception {
    KeyPairGenerator dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
    KeyPair dsaKp;/*from   w ww  . j a  v  a2  s . co  m*/
    //KeyPairGenerator    elgKpg;           
    ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g);
    KeyPair elgKp;

    System.out.println(userid);
    System.out.println(randomStr);
    System.out.println(LSPass);
    // read a random BigInteger
    BigInteger r = new BigInteger(randomStr);

    //   LS
    PGPPublicKey pgpPubKey = readPublicKey(new FileInputStream(SELS_LIST_PATH + "/LS_pub.asc"));
    PGPPrivateKey pgpSecKey = findSecretKey(new FileInputStream(SELS_LIST_PATH + "/LS_secret.asc"),
            pgpPubKey.getKeyID(), LSPass.toCharArray());

    secKeyLS = (ElGamalPrivateKey) pgpSecKey.getKey();
    BigInteger K_LS = secKeyLS.getX();

    //   User A's correspoding
    FileOutputStream out1 = new FileOutputStream(SELS_LIST_PATH + "/" + userid + "_secret.asc");
    FileOutputStream out2 = new FileOutputStream(SELS_LIST_PATH + "/" + userid + "_pub.asc");

    dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
    dsaKpg.initialize(1024);
    dsaKp = dsaKpg.generateKeyPair();
    BigInteger x;

    if (paramFlag == 1)
        x = K_LS.subtract(r).mod(p);
    else
        x = K_LS.subtract(r).mod(q);
    BigInteger y = g.modPow(x, p);

    ElGamalPrivateKeySpec privSpec = new ElGamalPrivateKeySpec(x, elParams);
    ElGamalPublicKeySpec pubSpec = new ElGamalPublicKeySpec(y, elParams);

    ElGamalPublicPGKey pubKey = new ElGamalPublicPGKey(pubSpec);
    ElGamalPrivatePGKey secKey = new ElGamalPrivatePGKey(privSpec);

    elgKp = new KeyPair(pubKey, secKey);
    exportKeyPair(out1, out2, dsaKp, elgKp, userid, LSPass.toCharArray(), true, expsec);

}

From source file:SELSKeyGen.java

License:Open Source License

private static void userKeyGen(String subuserid, String servuserid, String subuserIdHash, String servuserIdHash,
        String LMPass, String userPass, int expsec) throws Exception {

    // this takes a while as the key generator has to generate 
    // some DSA params
    // before it generates the key.
    KeyPairGenerator dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
    KeyPair dsaKp;// ww  w  .  j  a va2 s  .  c o m
    //KeyPairGenerator    elgKpg;           
    ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g);

    // this is quicker because we are using pregenerated parameters.
    KeyPair elgKp;// = elgKpg.generateKeyPair();

    System.out.println(subuserid);
    System.out.println(servuserid);
    // generate a random BigInteger
    BigInteger r = genRandom();

    //   LM
    PGPPublicKey pgpPubKey = readPublicKey(new FileInputStream(SELS_LIST_PATH + "/LM_pub.asc"));
    PGPPrivateKey pgpSecKey = findSecretKey(new FileInputStream(SELS_LIST_PATH + "/LM_secret.asc"),
            pgpPubKey.getKeyID(), LMPass.toCharArray());

    secKeyLM = (ElGamalPrivateKey) pgpSecKey.getKey();
    BigInteger K_LM = secKeyLM.getX();

    //   User A's sub key
    FileOutputStream out1 = new FileOutputStream(SELS_LIST_PATH + "/" + subuserIdHash + "_subsecret.asc");
    FileOutputStream out2 = new FileOutputStream(SELS_LIST_PATH + "/" + subuserIdHash + "_subpub.asc");

    //    User A's serv key
    FileOutputStream out3 = new FileOutputStream(SELS_LIST_PATH + "/" + servuserIdHash + "_servsecret.asc");
    FileOutputStream out4 = new FileOutputStream(SELS_LIST_PATH + "/" + servuserIdHash + "_servpub.asc");

    dsaKpg = KeyPairGenerator.getInstance("DSA", "BC");
    dsaKpg.initialize(1024);
    dsaKp = dsaKpg.generateKeyPair();
    BigInteger x;
    if (paramFlag == 1)
        x = K_LM.add(r).mod(p);
    else
        x = K_LM.add(r).mod(q);

    BigInteger y = g.modPow(x, p);

    ElGamalPrivateKeySpec privSpec = new ElGamalPrivateKeySpec(x, elParams);
    ElGamalPublicKeySpec pubSpec = new ElGamalPublicKeySpec(y, elParams);

    ElGamalPublicPGKey pubKey = new ElGamalPublicPGKey(pubSpec);
    ElGamalPrivatePGKey secKey = new ElGamalPrivatePGKey(privSpec);

    elgKp = new KeyPair(pubKey, secKey);
    exportKeyPair(out1, out2, dsaKp, elgKp, subuserid, userPass.toCharArray(), true, expsec);
    exportKeyPair(out3, out4, dsaKp, elgKp, servuserid, userPass.toCharArray(), true, expsec);

}

From source file:bisq.common.crypto.PGP.java

License:Open Source License

@Nullable
public static PGPPublicKey getPubKeyFromPem(@Nullable String pem) {
    if (pem != null) {
        InputStream inputStream = new ByteArrayInputStream(pem.getBytes(Charsets.UTF_8));
        try {//  w ww .j  a va  2 s .  c  o  m
            inputStream = PGPUtil.getDecoderStream(inputStream);
            try {
                JcaPGPPublicKeyRingCollection ringCollection = new JcaPGPPublicKeyRingCollection(inputStream);
                Iterator<PGPPublicKeyRing> keyRingsIterator = ringCollection.getKeyRings();
                while (keyRingsIterator.hasNext()) {
                    PGPPublicKeyRing pgpPublicKeyRing = keyRingsIterator.next();
                    Iterator<PGPPublicKey> pubKeysIterator = pgpPublicKeyRing.getPublicKeys();
                    while (pubKeysIterator.hasNext()) {
                        final PGPPublicKey pgpPublicKey = pubKeysIterator.next();
                        if ((pgpPublicKey).isEncryptionKey()) {
                            log.debug(pgpPublicKey.getClass().getName() + " KeyID: "
                                    + Long.toHexString(pgpPublicKey.getKeyID()) + " type: "
                                    + pgpPublicKey.getAlgorithm() + " fingerprint: "
                                    + new String(Hex.encode(pgpPublicKey.getFingerprint())));

                            BCPGKey bcKey = pgpPublicKey.getPublicKeyPacket().getKey();
                            log.debug(bcKey.getClass().getName());
                            if (bcKey instanceof RSAPublicBCPGKey) {
                                RSAPublicBCPGKey bcRSA = (RSAPublicBCPGKey) bcKey;
                                RSAPublicKeySpec specRSA = new RSAPublicKeySpec(bcRSA.getModulus(),
                                        bcRSA.getPublicExponent());
                                PublicKey jceKey = KeyFactory.getInstance("RSA").generatePublic(specRSA);
                                // if you want to use the key in JCE, use jceKey
                                // if you want to write "X.509" (SPKI) DER format to a file:
                                //Files.write(new File(pubKeyAsString).toPath(), jceKey.getEncoded());
                                // if you want to write in PEM, bouncycastle can do that
                                // or you can just do base64 and add BEGIN/END lines
                                // return pubKeyAsString; // assume only one key; if need to handle multiple keys
                                // or select other than the first, specify more clearly
                            }

                            return pgpPublicKey;
                        }
                    }
                }
                return null;
            } catch (PGPException | InvalidKeySpecException | NoSuchAlgorithmException e) {
                log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
                e.printStackTrace();
                throw new KeyConversionException(e);
            }

        } catch (IOException e) {
            log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
            e.printStackTrace();
            throw new KeyConversionException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ignore) {
            }
        }
    } else {
        log.warn("Error creating publicKey from pem. pem=null");
        return null;
    }
}

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>
 *//*from  www  .j av a 2 s  .c o  m*/
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

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

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

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Encrypt and sign the specified input file.  If you pass in a seed, you
 * will get the same encrypted output for the same file + same seed + same signor.
 * /*from w  w w .j a v a 2  s . com*/
 * DANGER!  If you use the same seed for multiple different messages, you are
 * making your key stream vulnerable to hacking, and your encryption is near
 * meaningless!  Make sure to use different seeds for different contents!
 *  
 * @param seed 
 */
public void encryptAndSignFile(String outputFilename, File inFile, InputStream publicRing,
        InputStream secretRing, String recipient, String signor, char[] passwd, boolean armor,
        boolean withIntegrityCheck, boolean oldFormat, byte[] seed) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the recipient's key
        PGPPublicKey encKey = readPublicKey(pubRing, recipient, true);
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Find the signing key
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        // Sign the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        if (oldFormat) {
            signDataV3(inFile, bOut, publicKey, privateKey);
        } else {
            signData(inFile, bOut, publicKey, privateKey);
        }

        SecureRandom secRand = makeSecureRandom(seed);

        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Encrypt the specified input file//from   www  . ja v  a 2 s  .c o m
 * @param seed 
 */
public void encryptFile(OutputStream out, InputStream in, String inName, long inLength, Date inDate,
        PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck, boolean oldFormat, char[] passphrase,
        byte[] seed) throws PGPException {
    try {
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Compress the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        compressData(in, bOut, inName, inLength, inDate, oldFormat, Format.UNCOMPRESSED);

        // Now encrypt the result
        SecureRandom secRand = makeSecureRandom(seed);

        // Now encrypt the result
        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Sign the specified file//from  ww  w .j a va  2  s  .c  om
 */
public void signFile(String outputFilename, File inFile, InputStream publicRing, InputStream secretRing,
        String signor, char[] passwd, boolean armor, boolean oldFormat) throws PGPException {
    try {
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;

        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the signing key
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;

        // Sign the data
        if (oldFormat) {
            signDataV3(inFile, aOut, publicKey, privateKey);
        } else {
            signData(inFile, aOut, publicKey, privateKey);
        }

        if (armor) {
            // close() just finishes and flushes the stream but does not close it
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Decrypt the specified (PKE) input file.
 * /*from w  w w  . j a  v a2s. c o  m*/
 * Either pubRing and secRing should be null, or pgpSecKey should be null, but not both.
 * 
 * @param out
 * @param inFile
 * @param pubRing
 * @param secRing
 * @param pgpSecKey
 * @param encKey
 * @param passwd
 * @param mdcRequired
 * @throws PGPException
 */
private void decryptKeyBasedFile(OutputStream out, InputStream inFile, PGPPublicKeyRingCollection pubRing,
        PGPSecretKeyRingCollection secRing, PGPSecretKey pgpSecKey, char[] passwd, boolean mdcRequired)
        throws PGPException {
    try {
        InputStream fileToDecrypt = PGPUtil.getDecoderStream(inFile);

        PGPObjectFactory pgpFact = new PGPObjectFactory(fileToDecrypt);

        Object message = pgpFact.nextObject();

        PGPPublicKeyEncryptedData pked = null;
        //            PGPCompressedData cData;

        // Check for signed only
        if (!(message instanceof PGPCompressedData)) {
            //
            // Encrypted - the first object might be a PGP marker packet.
            //
            if (!(message instanceof PGPEncryptedDataList)) {
                message = pgpFact.nextObject();
                if (!(message instanceof PGPEncryptedDataList)) {
                    throw new PGPException("Unrecognised PGP message type: " + message.getClass());
                }
            }

            PGPEncryptedDataList enc = (PGPEncryptedDataList) message;

            int count = 0;

            // find the secret key that is needed
            while (count != enc.size()) {
                if (enc.get(count) instanceof PGPPublicKeyEncryptedData) {
                    pked = (PGPPublicKeyEncryptedData) enc.get(count);
                    if (pgpSecKey == null) {
                        pgpSecKey = secRing.getSecretKey(pked.getKeyID());
                        if (pgpSecKey != null) {
                            break;
                        }
                    } else {
                        if (pgpSecKey.getKeyID() == pked.getKeyID()) {
                            break;
                        }
                    }
                }

                count++;
            }

            if (pgpSecKey == null) {
                throw new PGPException("Corresponding secret key not found");
            }

            // Check for revoked key
            PGPPublicKey encKey = pgpSecKey.getPublicKey();

            if (encKey == null) {
                encKey = findPublicKey(pubRing, pgpSecKey.getKeyID(), true);
            }

            if (encKey.isRevoked()) {
                String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
                System.out.println("Warning: Encryption key (0x" + keyId + ") has been revoked");
                // throw new PGPException("Encryption key (0x"+keyId+") has been revoked");
            }

            InputStream clear = pked.getDataStream(pgpSecKey.extractPrivateKey(passwd, "BC"), "BC");

            PGPObjectFactory pgpClearFact = new PGPObjectFactory(clear);

            message = pgpClearFact.nextObject();

            if (message == null) {
                message = pgpFact.nextObject();
            }
            //
            //                cData = (PGPCompressedData) pgpFact.nextObject();
            //            }
            //            else {
            //                cData = (PGPCompressedData) message;
        }

        if (message instanceof PGPCompressedData) {
            PGPCompressedData compressedData = (PGPCompressedData) message;
            pgpFact = new PGPObjectFactory(compressedData.getDataStream());

            message = pgpFact.nextObject();
        }

        // Plain file
        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;

            InputStream dataIn = ld.getInputStream();

            int ch;
            while ((ch = dataIn.read()) >= 0) {
                out.write(ch);
            }
            out.close();
        } else if (message instanceof PGPOnePassSignatureList) {
            // One-pass signature
            if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) {
                throw new PGPException("Signature verification failed");
            }

            System.out.println("Signature verified");
        } else if (message instanceof PGPSignatureList) {
            // Signature list
            if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) {
                throw new PGPException("Signature verification failed");
            }

            System.out.println("Signature verified");
        } else {
            // what?
            // System.out.println("Unrecognised message type");
            throw new PGPException("Unrecognised PGP message type: " + message.getClass());
        }

        if (pked != null) {
            if (pked.isIntegrityProtected()) {
                if (!pked.verify()) {
                    throw new PGPException("Message failed integrity check");
                }

                if (_verbose) {
                    System.out.println("Message integrity check passed");
                }
            } else {
                if (_verbose) {
                    System.out.println("No message integrity check");
                }

                if (mdcRequired) {
                    throw new PGPException("Missing required message integrity check");
                }
            }
        }
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in decryption", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check the signature in clear-signed data
 *///from   ww w .  j av  a2s. 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);
    }
}