Example usage for org.bouncycastle.openpgp PGPLiteralData getInputStream

List of usage examples for org.bouncycastle.openpgp PGPLiteralData getInputStream

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPLiteralData getInputStream.

Prototype

public InputStream getInputStream() 

Source Link

Document

Return the raw input stream for the data packet.

Usage

From source file:org.brownsocks.payments.gateways.enets.pgp.BCPGPProvider.java

@Override
public String decryptAndVerify(String messageIn) throws IOException, SignatureVerificationException {

    try {/*  ww  w.j av  a 2s  . com*/
        /* Stage zero: Convert to ASCII armored format and open a decoding stream */
        InputStream is = new ByteArrayInputStream(Base64.decode(messageIn));
        InputStream decoderStream = PGPUtil.getDecoderStream(is);

        /* Stage one: Init a decrypting stream */
        PGPObjectFactory pgpFactory = new PGPObjectFactory(decoderStream);
        PGPEncryptedDataList cryptedDataList = (PGPEncryptedDataList) pgpFactory.nextObject();
        PGPPublicKeyEncryptedData cryptedData = (PGPPublicKeyEncryptedData) cryptedDataList.get(0);
        InputStream clearStream = cryptedData.getDataStream(getCryptingPrivateKey(), _provider);

        /* Stage two: Seperate the XML data from the signatures */
        PGPObjectFactory plainFact = new PGPObjectFactory(clearStream);

        PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) plainFact.nextObject();
        PGPLiteralData literalData = (PGPLiteralData) plainFact.nextObject();

        String xmlMessage = IOUtils.toString(literalData.getInputStream());
        PGPSignatureList signatureList = (PGPSignatureList) plainFact.nextObject();

        /* Stage three: Verify signature */
        PGPOnePassSignature ops = onePassSignatureList.get(0);
        PGPPublicKey key = _remotePublicKeyRing.getPublicKey(ops.getKeyID());
        ops.initVerify(key, _provider);
        ops.update(xmlMessage.getBytes());

        if (!ops.verify(signatureList.get(0))) {
            throw new SignatureVerificationException(
                    "Failed to verify message signature. Message authenticity cannot be thrusted.");
        }

        return xmlMessage;

    } catch (PGPException pgpException) {
        throw new IOException("PGP subsystem problem.", pgpException);

    } catch (SignatureException signException) {
        throw new IOException("PGP subsystem problem.", signException);

    } catch (Throwable t) {
        throw new IOException("Unknown error occured in PGP subsystem: " + t.getMessage(), t);

    }

}

From source file:org.kontalk.crypto.Coder.java

License:Open Source License

private static DecryptionResult decryptAndVerify(InputStream encryptedStream, PersonalKey myKey,
        PGPPublicKey senderKey) {//w  ww  . jav  a 2 s  .c  o  m
    // note: the signature is inside the encrypted data

    DecryptionResult result = new DecryptionResult();

    PGPObjectFactory pgpFactory = new PGPObjectFactory(encryptedStream);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try { // catch all IO and PGP exceptions

        // the first object might be a PGP marker packet
        Object o = pgpFactory.nextObject(); // nullable
        if (!(o instanceof PGPEncryptedDataList)) {
            o = pgpFactory.nextObject(); // nullable
        }

        if (!(o instanceof PGPEncryptedDataList)) {
            LOGGER.warning("can't find encrypted data list in data");
            result.errors.add(Error.INVALID_DATA);
            return result;
        }
        PGPEncryptedDataList encDataList = (PGPEncryptedDataList) o;

        // check if secret key matches our encryption keyID
        Iterator<?> it = encDataList.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        long myKeyID = myKey.getPrivateEncryptionKey().getKeyID();
        while (sKey == null && it.hasNext()) {
            Object i = it.next();
            if (!(i instanceof PGPPublicKeyEncryptedData))
                continue;
            pbe = (PGPPublicKeyEncryptedData) i;
            if (pbe.getKeyID() == myKeyID)
                sKey = myKey.getPrivateEncryptionKey();
        }
        if (sKey == null || pbe == null) {
            LOGGER.warning("private key for message not found");
            result.errors.add(Error.INVALID_PRIVATE_KEY);
            return result;
        }

        InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));

        PGPObjectFactory plainFactory = new PGPObjectFactory(clear);

        Object object = plainFactory.nextObject(); // nullable

        if (!(object instanceof PGPCompressedData)) {
            LOGGER.warning("data packet not compressed");
            result.errors.add(Error.INVALID_DATA);
            return result;
        }

        PGPCompressedData cData = (PGPCompressedData) object;
        PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());

        object = pgpFact.nextObject(); // nullable

        // the first object could be the signature list
        // get signature from it
        PGPOnePassSignature ops = null;
        if (object instanceof PGPOnePassSignatureList) {
            PGPOnePassSignatureList signatureList = (PGPOnePassSignatureList) object;
            // there is a signature list, so we assume the message is signed
            // (makes sense)
            result.signing = Signing.SIGNED;

            if (signatureList.isEmpty()) {
                LOGGER.warning("signature list is empty");
                result.errors.add(Error.INVALID_SIGNATURE_DATA);
            } else {
                ops = signatureList.get(0);
                ops.init(new BcPGPContentVerifierBuilderProvider(), senderKey);
            }
            object = pgpFact.nextObject(); // nullable
        } else {
            LOGGER.warning("signature list not found");
            result.signing = Signing.NOT;
        }

        if (!(object instanceof PGPLiteralData)) {
            LOGGER.warning("unknown packet type: " + object.getClass().getName());
            result.errors.add(Error.INVALID_DATA);
            return result;
        }

        PGPLiteralData ld = (PGPLiteralData) object;
        InputStream unc = ld.getInputStream();
        int ch;
        while ((ch = unc.read()) >= 0) {
            outputStream.write(ch);
            if (ops != null)
                try {
                    ops.update((byte) ch);
                } catch (SignatureException ex) {
                    LOGGER.log(Level.WARNING, "can't read signature", ex);
                }
        }

        result.decryptedStream = Optional.of(outputStream);

        if (ops != null) {
            result = verifySignature(result, pgpFact, ops);
        }

        // verify message integrity
        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                LOGGER.warning("message integrity check failed");
                result.errors.add(Error.INVALID_INTEGRITY);
            }
        } else {
            LOGGER.warning("message is not integrity protected");
            result.errors.add(Error.NO_INTEGRITY);
        }

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't decrypt message", ex);
        result.errors.add(Error.UNKNOWN_ERROR);
    }

    return result;
}

From source file:org.mule.module.pgp.DecryptStreamTransformer.java

License:Open Source License

/**
 * {@inheritDoc}/*from w  w w.  jav  a2s.c  o  m*/
 */
@Override
public void initialize(OutputStream out) throws Exception {
    InputStream decodedInputStream = PGPUtil.getDecoderStream(this.toBeDecrypted);
    PGPObjectFactory pgpF = new PGPObjectFactory(decodedInputStream);
    Object o = pgpF.nextObject();

    if (o == null) {
        throw new IllegalArgumentException("Invalid PGP message");
    }

    // the first object might be a PGP marker packet.
    PGPEncryptedDataList enc;
    if (o instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) o;

    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    // This loop looks like it is ready for multiple encrypted
    // objects, but really only one is expected.
    Iterator<?> it = enc.getEncryptedDataObjects();
    PGPPublicKeyEncryptedData pbe = null;
    PGPPrivateKey privateKey = null;
    while (privateKey == null && it.hasNext()) {
        pbe = (PGPPublicKeyEncryptedData) it.next();
        privateKey = getPrivateKey(pbe.getKeyID(), this.password);
        if (privateKey == null) {
            throw new IllegalArgumentException("Failed to find private key with ID " + pbe.getKeyID());
        }
    }

    clearStream = pbe.getDataStream(privateKey, "BC");
    PGPObjectFactory plainFact = new PGPObjectFactory(clearStream);

    o = plainFact.nextObject();
    PGPOnePassSignature signature = null;
    if (o instanceof PGPOnePassSignatureList) {
        PGPOnePassSignatureList list = (PGPOnePassSignatureList) o;
        signature = list.get(0);
        signature.initVerify(this.publicKey, "BC");
        // TODO verify signature
        // signature.verify(null);
        o = plainFact.nextObject();
    }

    compressedStream = null;
    if (o instanceof PGPCompressedData) {
        PGPCompressedData cData = (PGPCompressedData) o;
        compressedStream = new BufferedInputStream(cData.getDataStream());
        PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
        Object streamData = pgpFact.nextObject();
        o = streamData;
    }

    if (o instanceof PGPLiteralData) {
        PGPLiteralData ld = (PGPLiteralData) o;
        uncStream = ld.getInputStream();
    } else {
        throw new PGPException("input is not PGPLiteralData - type unknown.");
    }
}

From source file:org.pgptool.gui.encryption.implpgp.EncryptionServicePgpImpl.java

License:Open Source License

/**
 * decrypt the passed in message stream.
 * //from ww  w.java2  s .  co m
 * Inspired by
 * https://github.com/bcgit/bc-java/blob/master/pg/src/main/java/org/bouncycastle/openpgp/examples/KeyBasedFileProcessor.java
 * 
 * @param countingStream
 *            this stream is passed for progress reporting only, must not be
 *            used to actually read data
 */
private void decryptStream(PGPPublicKeyEncryptedData pbe, PGPPrivateKey privateKey, OutputStream outputStream,
        Updater optionalProgress, CountingInputStream countingStream)
        throws UserRequestedCancellationException {
    try {
        InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey));

        BcPGPObjectFactory plainFact = new BcPGPObjectFactory(clear);
        Object message = plainFact.nextObject();
        if (message instanceof PGPMarker) {
            message = plainFact.nextObject();
        }

        BcPGPObjectFactory pgpFactory = null;
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            pgpFactory = new BcPGPObjectFactory(cData.getDataStream());
            message = pgpFactory.nextObject();
        }

        int watchDog = 0;
        while (message != null) {
            Preconditions.checkState(watchDog++ < 100, "Inifinite loop watch dog just hit");

            if (message instanceof PGPLiteralData) {
                PGPLiteralData ld = (PGPLiteralData) message;

                // NOTE: We know initial file name (in case we need it):
                // ld.getFileName();
                InputStream unc = ld.getInputStream();
                OutputStream fOut = new BufferedOutputStream(outputStream);
                if (optionalProgress != null) {
                    optionalProgress.updateStepInfo("progress.decrypting");
                }

                pipeStream(unc, fOut, BUFFER_SIZE, optionalProgress, countingStream);
                fOut.close();
                unc.close();

                if (pbe.isIntegrityProtected()) {
                    if (!pbe.verify()) {
                        throw new RuntimeException("message failed integrity check");
                    }
                }
                return;
            } else if (message instanceof PGPOnePassSignatureList) {
                log.info("PGPOnePassSignatureList is not implemented yet. Skipping signature validation");
                // NOTE: Here is a place to copyright from
                // http://stackoverflow.com/questions/19173181/bouncycastle-pgp-decrypt-and-verify
                Preconditions.checkArgument(pgpFactory != null,
                        "File format is not supported. pgpFact is supposed to be initialized by that time");
                message = pgpFactory.nextObject();
            } else if (message instanceof PGPSignatureList) {
                log.info("PGPSignatureList is not implemented yet. Skipping signature validation");
                Preconditions.checkArgument(pgpFactory != null,
                        "File format is not supported. pgpFact is supposed to be initialized by that time");
                message = pgpFactory.nextObject();
            } else {
                throw new PGPException(
                        "Don't know how to decrypt the input file. Encountered unexpected block: " + message);
            }
        }
    } catch (Throwable e) {
        Throwables.throwIfInstanceOf(e, UserRequestedCancellationException.class);
        throw new RuntimeException("Decryption failed", e);
    }
}

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

License:Open Source License

/** Decrypt and/or verify binary or ascii armored pgp data. */
@NonNull/*from w w w.j a  v  a2s .  c  om*/
private DecryptVerifyResult decryptVerify(PgpDecryptVerifyInputParcel input, CryptoInputParcel cryptoInput,
        InputData inputData, InputStream in, OutputStream out, int indent) throws IOException, PGPException {

    OperationLog log = new OperationLog();

    log.add(LogType.MSG_DC, indent);
    indent += 1;

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

    // parse ASCII Armor headers
    ArmorHeaders armorHeaders = parseArmorHeaders(in, log, indent);
    String charset = armorHeaders.charset;
    boolean useBackupCode = false;
    if (armorHeaders.backupVersion != null && armorHeaders.backupVersion == 2) {
        useBackupCode = true;
    }

    OpenPgpDecryptionResultBuilder decryptionResultBuilder = new OpenPgpDecryptionResultBuilder();

    JcaSkipMarkerPGPObjectFactory plainFact;
    Object dataChunk;
    EncryptStreamResult esResult = null;
    { // resolve encrypted (symmetric and asymmetric) packets
        JcaSkipMarkerPGPObjectFactory pgpF = new JcaSkipMarkerPGPObjectFactory(in);
        Object obj = pgpF.nextObject();

        if (obj instanceof PGPEncryptedDataList) {
            esResult = handleEncryptedPacket(input, cryptoInput, (PGPEncryptedDataList) obj, log, indent,
                    useBackupCode);

            // if there is an error, nothing left to do here
            if (esResult.errorResult != null) {
                return esResult.errorResult;
            }

            // if this worked out so far, the data is encrypted
            decryptionResultBuilder.setEncrypted(true);
            if (esResult.sessionKey != null && esResult.decryptedSessionKey != null) {
                decryptionResultBuilder.setSessionKey(esResult.sessionKey, esResult.decryptedSessionKey);
            }

            if (esResult.insecureEncryptionKey) {
                log.add(LogType.MSG_DC_INSECURE_SYMMETRIC_ENCRYPTION_ALGO, indent + 1);
                decryptionResultBuilder.setInsecure(true);
            }

            // Check for insecure encryption algorithms!
            if (!PgpSecurityConstants.isSecureSymmetricAlgorithm(esResult.symmetricEncryptionAlgo)) {
                log.add(LogType.MSG_DC_INSECURE_SYMMETRIC_ENCRYPTION_ALGO, indent + 1);
                decryptionResultBuilder.setInsecure(true);
            }

            plainFact = new JcaSkipMarkerPGPObjectFactory(esResult.cleartextStream);
            dataChunk = plainFact.nextObject();

        } else {
            decryptionResultBuilder.setEncrypted(false);

            plainFact = pgpF;
            dataChunk = obj;
        }

    }

    log.add(LogType.MSG_DC_PREP_STREAMS, indent);

    log.add(LogType.MSG_DC_CLEAR, indent);
    indent += 1;

    // resolve compressed data
    if (dataChunk instanceof PGPCompressedData) {
        log.add(LogType.MSG_DC_CLEAR_DECOMPRESS, indent + 1);

        PGPCompressedData compressedData = (PGPCompressedData) dataChunk;

        JcaSkipMarkerPGPObjectFactory fact = new JcaSkipMarkerPGPObjectFactory(compressedData.getDataStream());
        dataChunk = fact.nextObject();
        plainFact = fact;
    }

    PgpSignatureChecker signatureChecker = new PgpSignatureChecker(mProviderHelper, input.getSenderAddress());
    if (signatureChecker.initializeOnePassSignature(dataChunk, log, indent + 1)) {
        dataChunk = plainFact.nextObject();
    }

    if (dataChunk instanceof PGPSignatureList) {
        // skip
        dataChunk = plainFact.nextObject();
    }

    OpenPgpMetadata metadata;

    if (!(dataChunk instanceof PGPLiteralData)) {

        log.add(LogType.MSG_DC_ERROR_INVALID_DATA, indent);
        return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);

    }

    log.add(LogType.MSG_DC_CLEAR_DATA, indent + 1);
    indent += 2;

    PGPLiteralData literalData = (PGPLiteralData) dataChunk;

    String originalFilename = literalData.getFileName();
    // reject filenames with slashes completely (path traversal issue)
    if (originalFilename.contains("/")) {
        originalFilename = "";
    }
    String mimeType = null;
    if (literalData.getFormat() == PGPLiteralData.TEXT || literalData.getFormat() == PGPLiteralData.UTF8) {
        mimeType = "text/plain";
    } else {
        // try to guess from file ending
        String extension = MimeTypeMap.getFileExtensionFromUrl(originalFilename);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            mimeType = mime.getMimeTypeFromExtension(extension);
        }
    }
    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }

    if (!"".equals(originalFilename)) {
        log.add(LogType.MSG_DC_CLEAR_META_FILE, indent + 1, originalFilename);
    }
    log.add(LogType.MSG_DC_CLEAR_META_TIME, indent + 1,
            new Date(literalData.getModificationTime().getTime()).toString());

    // return here if we want to decrypt the metadata only
    if (input.isDecryptMetadataOnly()) {

        log.add(LogType.MSG_DC_CLEAR_META_MIME, indent + 1, mimeType);

        // this operation skips the entire stream to find the data length!
        Long originalSize = literalData.findDataLength();

        if (originalSize != null) {
            log.add(LogType.MSG_DC_CLEAR_META_SIZE, indent + 1, Long.toString(originalSize));
        } else {
            log.add(LogType.MSG_DC_CLEAR_META_SIZE_UNKNOWN, indent + 1);
        }

        metadata = new OpenPgpMetadata(originalFilename, mimeType, literalData.getModificationTime().getTime(),
                originalSize == null ? 0 : originalSize, charset);

        log.add(LogType.MSG_DC_OK_META_ONLY, indent);
        DecryptVerifyResult result = new DecryptVerifyResult(DecryptVerifyResult.RESULT_OK, log);
        result.setDecryptionMetadata(metadata);
        return result;
    }

    InputStream dataIn = literalData.getInputStream();

    long opTime, startTime = System.currentTimeMillis();

    long alreadyWritten = 0;
    long wholeSize = inputData.getSize() - inputData.getStreamPosition();
    boolean sizeIsKnown = inputData.getSize() != InputData.UNKNOWN_FILESIZE && wholeSize > 0;
    int length;
    byte[] buffer = new byte[8192];
    byte[] firstBytes = new byte[48];
    CharsetVerifier charsetVerifier = new CharsetVerifier(buffer, mimeType, charset);

    updateProgress(R.string.progress_decrypting, 1, 100);

    long nextProgressTime = 0L;
    int lastReportedProgress = 1;
    while ((length = dataIn.read(buffer)) > 0) {
        // Log.d(Constants.TAG, "read bytes: " + length);
        if (out != null) {
            out.write(buffer, 0, length);
        }

        // update signature buffer if signature is also present
        signatureChecker.updateSignatureData(buffer, 0, length);

        charsetVerifier.readBytesFromBuffer(0, length);

        // note down first couple of bytes for "magic bytes" file type detection
        if (alreadyWritten == 0) {
            System.arraycopy(buffer, 0, firstBytes, 0, length > firstBytes.length ? firstBytes.length : length);
        }

        alreadyWritten += length;
        if (sizeIsKnown && nextProgressTime < System.currentTimeMillis()) {
            long progress = 100 * inputData.getStreamPosition() / wholeSize;
            // stop at 100% for wrong file sizes...
            if (progress > 100) {
                progress = 100;
            }
            if (progress > lastReportedProgress) {
                updateProgress((int) progress, 100);
                lastReportedProgress = (int) progress;
                nextProgressTime = System.currentTimeMillis() + PROGRESS_STRIDE_MILLISECONDS;
            }
        }
    }

    if (signatureChecker.isInitialized()) {

        Object o = plainFact.nextObject();
        boolean signatureCheckOk = signatureChecker.verifySignatureOnePass(o, log, indent + 1);

        if (!signatureCheckOk) {
            return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
        }

    }

    opTime = System.currentTimeMillis() - startTime;
    Log.d(Constants.TAG, "decrypt time taken: " + String.format("%.2f", opTime / 1000.0) + "s, for "
            + alreadyWritten + " bytes");

    // special treatment to detect pgp mime types
    // TODO move into CharsetVerifier? seems like that would be a plausible place for this logic
    if (matchesPrefix(firstBytes, "-----BEGIN PGP PUBLIC KEY BLOCK-----")
            || matchesPrefix(firstBytes, "-----BEGIN PGP PRIVATE KEY BLOCK-----")) {
        mimeType = Constants.MIME_TYPE_KEYS;
    } else if (matchesPrefix(firstBytes, "-----BEGIN PGP MESSAGE-----")) {
        // this is NOT application/pgp-encrypted, see RFC 3156!
        mimeType = Constants.MIME_TYPE_ENCRYPTED_ALTERNATE;
    } else {
        mimeType = charsetVerifier.getGuessedMimeType();
    }
    metadata = new OpenPgpMetadata(originalFilename, mimeType, literalData.getModificationTime().getTime(),
            alreadyWritten, charsetVerifier.getCharset());

    log.add(LogType.MSG_DC_CLEAR_META_MIME, indent + 1, mimeType);
    Log.d(Constants.TAG, metadata.toString());

    indent -= 1;

    if (esResult != null) {
        if (esResult.encryptedData.isIntegrityProtected()) {
            if (esResult.encryptedData.verify()) {
                log.add(LogType.MSG_DC_INTEGRITY_CHECK_OK, indent);
            } else {
                log.add(LogType.MSG_DC_ERROR_INTEGRITY_CHECK, indent);
                return new DecryptVerifyResult(DecryptVerifyResult.RESULT_ERROR, log);
            }
        } else if (!signatureChecker.isInitialized()) {
            // If no signature is present, we *require* an MDC!
            // Handle missing integrity protection like failed integrity protection!
            // The MDC packet can be stripped by an attacker!
            log.add(LogType.MSG_DC_INSECURE_MDC_MISSING, indent);
            decryptionResultBuilder.setInsecure(true);
        }
    }

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

    log.add(LogType.MSG_DC_OK, indent);

    // Return a positive result, with metadata and verification info
    DecryptVerifyResult result = new DecryptVerifyResult(DecryptVerifyResult.RESULT_OK, log);

    result.setCachedCryptoInputParcel(cryptoInput);
    result.setSignatureResult(signatureChecker.getSignatureResult());
    result.setDecryptionResult(decryptionResultBuilder.build());
    result.setDecryptionMetadata(metadata);
    result.mOperationTime = opTime;

    return result;

}

From source file:org.tramaci.onionmail.PGP.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "deprecation" })
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password) throws Exception {
    InputStream inb = new ByteArrayInputStream(encrypted);
    InputStream in = PGPUtil.getDecoderStream(inb);

    try {/*from   w  ww  . j  a  va 2s  . co m*/
        PGPObjectFactory pgpF = new PGPObjectFactory(in);
        PGPEncryptedDataList enc = null;
        Object o = pgpF.nextObject();
        if (o == null)
            throw new Exception("@550 No data in message");

        if (o instanceof PGPEncryptedDataList)
            enc = (PGPEncryptedDataList) o;
        else
            enc = (PGPEncryptedDataList) pgpF.nextObject();

        //deadcode: if (o==null) throw new Exception("@550 No dataList in message");

        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();
            sKey = findSecretKey(pgpSec, pbe.getKeyID(), password);
        }

        if (sKey == null)
            throw new IllegalArgumentException("@550 SecretKey not found");
        InputStream clear = pbe.getDataStream(sKey, "BC");
        PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
        PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
        pgpFact = new PGPObjectFactory(cData.getDataStream());
        PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
        InputStream unc = ld.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int ch;
        while ((ch = unc.read()) >= 0) {
            out.write(ch);
        }

        byte[] rs = out.toByteArray();
        try {
            in.close();
        } catch (Exception I) {
        }
        try {
            inb.close();
        } catch (Exception I) {
        }
        out.close();
        return rs;

    } catch (Exception E) {
        try {
            in.close();
        } catch (Exception I) {
        }
        try {
            inb.close();
        } catch (Exception I) {
        }
        throw E;
    }
}

From source file:uk.ac.ebi.ega.cipher.GPGStream.java

License:Apache License

public GPGStream(InputStream in, OutputStream out, int blocksize, char[] password, boolean mod,
        int pw_strength) {

    InputStream in_ = null;//from  w w  w .j av  a 2  s.c  o m
    {
        InputStream clear = null;
        try {
            if (mod)
                return;
            in_ = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
            PGPObjectFactory pgpF = new PGPObjectFactory(in_);
            PGPEncryptedDataList enc;
            Object o = pgpF.nextObject();
            if (o instanceof PGPEncryptedDataList) {
                enc = (PGPEncryptedDataList) o;
            } else {
                enc = (PGPEncryptedDataList) pgpF.nextObject();
            }
            PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
            clear = pbe.getDataStream(password, "BC");
            PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
            PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
            pgpFact = new PGPObjectFactory(cData.getDataStream());
            PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
            InputStream in__ = ld.getInputStream();
        } catch (PGPException ex) {
            Logger.getLogger(GPGStream.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(GPGStream.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GPGStream.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Throwable t) {

        } finally {
            try {
                in_.close();
            } catch (IOException ex) {
                Logger.getLogger(GPGStream.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                clear.close();
            } catch (IOException ex) {
                Logger.getLogger(GPGStream.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

From source file:uk.ac.ebi.ega.cipher.GPGStream.java

License:Apache License

public static InputStream getDecodingGPGInoutStream(FileInputStream fis, char[] pw)
        throws IOException, PGPException, NoSuchProviderException {
    InputStream in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(fis);

    PGPObjectFactory pgpF = new PGPObjectFactory(in);
    PGPEncryptedDataList enc;/* w  w w . j  a va  2 s.  c  o m*/

    Object o = pgpF.nextObject();
    if (o instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) o;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
    InputStream clear = pbe.getDataStream(pw, "BC");
    PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
    PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
    pgpFact = new PGPObjectFactory(cData.getDataStream());
    PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();

    return ld.getInputStream();
}