Example usage for org.bouncycastle.openpgp PGPEncryptedDataGenerator close

List of usage examples for org.bouncycastle.openpgp PGPEncryptedDataGenerator close

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPEncryptedDataGenerator close.

Prototype

public void close() throws IOException 

Source Link

Document

Close off the encrypted object - this is equivalent to calling close on the stream returned by the open() methods.

Usage

From source file:com.arcusx.simplepgp.PgpDataEncryptor.java

public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName,
        InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput)
        throws IOException, PGPException {
    PGPCompressedDataGenerator comData = null;
    try {//from  w  w w.  jav a2  s  .c o  m
        OutputStream out = dataOut;
        PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn);

        if (isArmoredOutput) {
            out = new ArmoredOutputStream(out);
        }

        BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
        dataEncryptor.setWithIntegrityPacket(true);
        dataEncryptor.setSecureRandom(new SecureRandom());

        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
        encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey));

        OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);

        // Initialize compressed data generator
        PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(
                PGPCompressedData.ZIP);
        OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]);

        // Initialize signature generator
        final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn);
        PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey);

        PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
                senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);

        PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
        signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey));
        signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate());
        signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, dataFileName,
                new Date(), new byte[BUFFER_SIZE]);

        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = dataIn.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }
        dataIn.close();
        literalDataGenerator.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        signatureGenerator.generate().encode(compressedOut);
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        if (isArmoredOutput) {
            out.close();
        }
    } finally {
        if (comData != null) {
            comData.close();
        }
        IOUtils.closeQuietly(dataOut);
    }
}

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 ava  2 s  . c om
 * 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 w w w  . j av a 2s.co  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.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * PGP Encrypt a stream./*from  w w w  .  ja v a 2 s . c  o  m*/
 *
 * @param plainTextStream The stream that contains the plain-text data.
 * @param publicKey       The public key to use for encryption.
 * @param armoured        {@code true}: ASCII armor the encrypted data.
 *
 * @return The encrypted data stream.
 *
 * @throws NoSuchProviderException
 * @throws IOException
 * @throws PGPException
 */
public static InputStream encrypt(final InputStream plainTextStream, final PGPPublicKey publicKey,
        final boolean armoured) throws IOException, NoSuchProviderException, PGPException {

    /* Compress and extract literal data packets that can be encrypted. */
    PGPEncryptedDataGenerator encryptedDataGenerator = null;
    try (ByteArrayOutputStream decryptedStream = new ByteArrayOutputStream();
            ByteArrayOutputStream encryptedByteStream = new ByteArrayOutputStream()) {
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB);
        OutputStream literalStream = literalDataGenerator.open(compressor.open(decryptedStream),
                PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
        ByteStreams.copy(plainTextStream, literalStream);
        compressor.close();

        /* Encrypt compressed data. */
        encryptedDataGenerator = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5,
                new SecureRandom(), BouncyCastleProvider.PROVIDER_NAME);
        encryptedDataGenerator.addMethod(publicKey);

        /* Create the encrypted output stream, armour if necessary. */
        OutputStream encryptedStream = encryptedByteStream;
        if (armoured)
            encryptedStream = new ArmoredOutputStream(encryptedStream);

        /* Create and write out the encrypted file. */
        OutputStream encryptionStream = encryptedDataGenerator.open(encryptedStream, new byte[4096]);
        ByteStreams.copy(new ByteArrayInputStream(decryptedStream.toByteArray()), encryptionStream);

        return new ByteArrayInputStream(encryptedByteStream.toByteArray());
    } finally {
        if (encryptedDataGenerator != null)
            encryptedDataGenerator.close();
    }
}

From source file:de.jtheuer.diki.lib.pgp.PGPHandler.java

License:Open Source License

/**
 * Encryptes the given input and writes into the output. If the key doesn't exist nothing will happen.
 * @param input input content/*ww  w  .  ja  v a 2s.com*/
 * @param output output as {@link ArmoredOutputStream} (BASE64)
 * @param keyID the keyID of the PublicKey that should be used
 * @throws PGPException
 * @throws IOException
 * @throws NoSuchProviderException
 */
public void encrypt(InputStream input, OutputStream output, long keyID) throws PGPException, IOException {
    PGPPublicKey encryptkey = null;

    /* take the own key if that is the ID... */
    if (keyID == publickey.getKeyID()) {
        encryptkey = publickey;
    } else {
        encryptkey = keyring.getPublicKey(keyID);
    }

    if (encryptkey != null) {

        PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
                PGPEncryptedDataGenerator.TRIPLE_DES, new SecureRandom(), "BC");

        try {
            encryptor.addMethod(encryptkey);
        } catch (NoSuchProviderException e) {
            LOGGER.log(Level.SEVERE,
                    "provider hasn't been loaded successfully! There is a problem with the Bouncycastle system!",
                    e);
        }
        ArmoredOutputStream armoredOut = new ArmoredOutputStream(output);
        OutputStream encryptedOut = encryptor.open(armoredOut, new byte[256]);
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
        OutputStream compressedOut = compressor.open(encryptedOut);

        PGPLiteralDataGenerator literalor = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalor.open(compressedOut, PGPLiteralDataGenerator.TEXT, "internal",
                new Date(), new byte[256]);

        /* copy from input to output */
        IOUtils.copy(input, literalOut);

        literalor.close();
        compressor.close();
        encryptor.close();
        armoredOut.close();
    }
}

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

License:Open Source License

/**
 * Creates encrypted and signed message body.
 * Errors that may occur are saved to the message.
 * @param message/*from  ww  w.j a v a2s.  c om*/
 * @return the encrypted and signed text.
 */
public static Optional<byte[]> processOutMessage(OutMessage message) {
    if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) {
        LOGGER.warning("message does not want to be encrypted");
        return Optional.empty();
    }

    LOGGER.info("encrypting message...");

    // get keys
    KeysResult keys = getKeys(message.getUser());
    if (keys.myKey == null || keys.otherKey == null) {
        message.setSecurityErrors(keys.errors);
        return Optional.empty();
    }

    // secure the message against the most basic attacks using Message/CPIM
    String from = keys.myKey.getUserId();
    String to = keys.otherKey.userID + "; ";
    String mime = "text/plain";
    // TODO encrypt more possible content
    String text = message.getContent().getPlainText();
    CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text);
    byte[] plainText;
    try {
        plainText = cpim.toByteArray();
    } catch (UnsupportedEncodingException ex) {
        LOGGER.log(Level.WARNING, "UTF-8 not supported", ex);
        plainText = cpim.toString().getBytes();
    }

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    //for (PGPPublicKey rcpt : mRecipients)
    encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(plainText);
    try { // catch all io and pgp exceptions

        OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);

        // setup compressed data generator
        PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

        // setup signature generator
        int algo = keys.myKey.getPublicEncryptionKey().getAlgorithm();
        PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1));
        sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey());

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, keys.myKey.getUserId());
        sigGen.setUnhashedSubpackets(spGen.generate());

        sigGen.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalGen.open(compressedOut, PGPLiteralData.BINARY, "", new Date(),
                new byte[BUFFER_SIZE]);

        // read the "in" stream, compress, encrypt and write to the "out" stream
        // this must be done if clear data is bigger than the buffer size
        // but there are other ways to optimize...
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            try {
                sigGen.update(buf, 0, len);
            } catch (SignatureException ex) {
                LOGGER.log(Level.WARNING, "can't read data for signature", ex);
                message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
                return Optional.empty();
            }
        }

        in.close();
        literalGen.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        try {
            sigGen.generate().encode(compressedOut);
        } catch (SignatureException ex) {
            LOGGER.log(Level.WARNING, "can't create signature", ex);
            message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
            return Optional.empty();
        }
        compGen.close();
        encGen.close();

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't encrypt message", ex);
        message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR));
        return Optional.empty();
    }

    LOGGER.info("encryption successful");
    return Optional.of(out.toByteArray());
}

From source file:org.opentestsystem.delivery.testreg.transformer.GPGEncryptor.java

License:Open Source License

/**
 * Uses the Legion of the Bouncy Castle (aka BouncyCastle) PGP API to encrypt, compress, and sign the input.
 * /*from ww w.j a  v a 2s . co  m*/
 * The configured landing zone public key is used to encrypt the input. Only the landing zone private key will be
 * able to decrypt.
 * 
 * The configured test registration private key is used to sign the input. This can be verified by the landing zone
 * to prove that this specific test registration instance created the data.
 * 
 * @param input
 *            A byte array
 * @return A byte array comprised of a PGP/GPG compatible binary encrypted and signed output
 */
@Transformer
public Message<File> encryptStream(final File input, final @Header("dwBatchUuid") String dwBatchUuid,
        final @Header("fileSuffix") String fileSuffix, final @Header("recordsSent") int recordsSent,
        final @Header("tempPaths") List<Path> tempPaths,
        final @Header("dwConfigType") DwConfigType dwConfigType) {

    String debugPrefix = dwConfigType + " DW Config: ";

    long curTime = System.currentTimeMillis();
    File tmpEncFile;

    try {

        PGPPublicKey landingZonePubKey = findLandingZonePublicKey(dwConfigType);
        PGPSecretKey testRegSecretKey = findTestRegSecretKey();

        PGPPrivateKey testRegPrivateKey = testRegSecretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(getPassphrase()));

        // ////////////////////
        // setup encryptor

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(landingZonePubKey).setProvider("BC"));

        // This outputstream, encryptedSignedOutputStream is the ultimate target that will contain the encrypted and
        // signed output
        Path tempEncPath = Files.createTempFile(DwBatchHandler.DW_ENC_TMP_PREFIX,
                (dwConfigType == DwConfigType.SBAC ? DwBatchHandler.SBAC_DW_NAME : DwBatchHandler.LOCAL_DW_NAME)
                        + fileSuffix);
        tempPaths.add(tempEncPath);
        tmpEncFile = tempEncPath.toFile();
        FileOutputStream encryptedSignedOutputStream = new FileOutputStream(tmpEncFile);

        LOGGER.debug(debugPrefix + "Created temp encrypted output file " + tmpEncFile.getAbsolutePath());

        OutputStream encryptOutStream = encGen.open(encryptedSignedOutputStream, new byte[BUFFER_SIZE]);

        // ////////////////////////////
        // setup data compression

        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
        OutputStream compressOutStream = comData.open(encryptOutStream);

        // /////////////////////
        // sign encrypted file with test reg private key

        // create a signature generator
        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder(testRegSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                        .setProvider("BC"));
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, testRegPrivateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> it = testRegSecretKey.getPublicKey().getUserIDs();

        if (it.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, it.next());
            signatureGenerator.setHashedSubpackets(spGen.generate());
        }

        // setup signature generator to encode the contents of the compressed output stream
        signatureGenerator.generateOnePassVersion(false).encode(compressOutStream);

        // create a PGP Literal Data Generator and open it to wrap the compression output stream
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        OutputStream signedOutStream = lGen.open(compressOutStream, PGPLiteralData.BINARY, "",
                new java.util.Date(), new byte[BUFFER_SIZE]);

        // create an input stream out of the input bytes
        FileInputStream clearInputStream = new FileInputStream(input);

        // read the input and write all data to the signing output stream, also update the signature
        // generator with the same input data
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = clearInputStream.read(buf)) > 0) {
            signedOutStream.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }

        // close everything and generate the final signature
        signedOutStream.close();
        lGen.close();
        signatureGenerator.generate().encode(compressOutStream);
        compressOutStream.close();
        comData.close();
        encryptOutStream.close();
        encGen.close();
        clearInputStream.close();

        encryptedSignedOutputStream.close();

    } catch (IOException | PGPException | SignatureException e) {
        throw new GPGEncryptionException(debugPrefix + "Failure to encrypt and sign input", e);
    }

    LOGGER.debug(debugPrefix + "Generated encrypted data in " + (System.currentTimeMillis() - curTime));

    return MessageBuilder.withPayload(tmpEncFile).setHeader("dwBatchUuid", dwBatchUuid)
            .setHeader("fileSuffix", fileSuffix).setHeader("recordsSent", recordsSent)
            .setHeader("tempPaths", tempPaths).setHeader("dwConfigType", dwConfigType).build();
}

From source file:uk.ac.ebi.enaega.uploadclient.NewMain.java

License:Open Source License

private static String[] convert(String fileName, InputStream inputStream, long restartAt, long streamOffset,
        long offset, PGPPublicKey pgKey) {
    String result = "Error", result1 = "Error";
    String[] results = null;//from   w ww  . j av a2s. com

    // If public Key provided - use it to encrypt file (provider already added)
    ByteArrayOutputStream baos = null; // PGP
    MessageDigest crypt_digest = null; // PGP
    OutputStream literalOut = null, encOut = null, compressedOut = null; // PGP
    int DEFAULT_BUFFER_SIZE = 65 * 1024; // PGP
    PGPEncryptedDataGenerator encryptedDataGenerator = null; // PGP
    PGPCompressedDataGenerator compressedDataGenerator = null; // PGP
    PGPLiteralDataGenerator literalDataGenerator = null; // PGP

    if (pgKey != null) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            baos = new ByteArrayOutputStream(2 * DEFAULT_BUFFER_SIZE); // Write to memory!
            try {
                crypt_digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("MD5 Algorithm not installed with Java. Contact Systems.");
                System.out.print(ex.getLocalizedMessage());
            }

            // Encrypted Data Generator -- needs unlimited Security Policy
            encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true,
                    new SecureRandom(), "BC");
            try {
                encryptedDataGenerator.addMethod(pgKey);
                encOut = encryptedDataGenerator.open(baos, new byte[DEFAULT_BUFFER_SIZE]);
            } catch (NoSuchProviderException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("No Such Service Provider Error: " + ex.getLocalizedMessage());
            } catch (PGPException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("PGP Error: " + ex.getLocalizedMessage());
                System.out.println("Ensure that Unlimited Strength Policy files are installed for this JRE:");
                Process java = Runtime.getRuntime().exec("cmd /C java -version");
                BufferedReader in_ = new BufferedReader(new InputStreamReader(java.getInputStream()));
                String line;
                while ((line = in_.readLine()) != null) {
                    System.out.print(line);
                }
            }

            // Compression
            compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
            compressedOut = compressedOut = new BufferedOutputStream(compressedDataGenerator.open(encOut));

            // Literal Data Generator and Output Stream
            literalDataGenerator = new PGPLiteralDataGenerator();
            literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
                    new byte[DEFAULT_BUFFER_SIZE]); // 1<<16
        } catch (IOException t) {
            String[] failure = { "Cipher Issues" };
            return failure;
        }
    }

    // Convert the stream.
    if (literalOut == null)
        return null;
    if (baos == null)
        return null;
    try {
        // Skips.
        inputStream.skip(streamOffset);
        OutputStream dataTransferOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));

        // Let's do it!
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int l = 0;

        MessageDigest digest = null; // calculate checksum of incoming data stream
        try {
            digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("MD5 Algorithm not installed with Java. Contact Systems.");
            System.out.print(ex.getLocalizedMessage());
        }

        while ((l = inputStream.read(buffer)) != -1) { // The actual data transfer loop -------------------
            if (pgKey != null) {
                literalOut.write(buffer, 0, l); // Write to mem buffer
                literalOut.flush();
                byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
                if (crypt_digest != null)
                    crypt_digest.update(buffer_); // update crypto MD5
                dataTransferOutputStream.write(buffer_); // Write cipher data to file
                baos.reset(); // empty mem buffer
            } else {
                dataTransferOutputStream.write(buffer, 0, l); // no cipher -- write directly to socket
            }
            //dataTransferOutputStream.flush();
            if (digest != null)
                digest.update(buffer, 0, l); // Calculate plain text MD5 for TCP stream
        }

        // Get a representation of the MD5 digest (checksum) plain file
        byte[] md5sum = digest == null ? null : digest.digest();
        result = "";
        if (md5sum != null)
            for (int i = 0; i < md5sum.length; i++)
                result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);

        // Upload loop complete. Close PGP streams, if used
        if (pgKey != null) {
            literalOut.close();
            if (literalDataGenerator != null)
                literalDataGenerator.close();
            // Close all other streams
            if (compressedOut != null)
                compressedOut.close();
            if (compressedDataGenerator != null)
                compressedDataGenerator.close();
            if (encOut != null)
                encOut.close();
            if (encryptedDataGenerator != null)
                encryptedDataGenerator.close();
            byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
            if (crypt_digest != null)
                crypt_digest.update(buffer_); // update crypto MD5
            dataTransferOutputStream.write(buffer_); // Write cipher data to socket
            dataTransferOutputStream.flush();
            baos.close();

            // Get a representation of the MD5 digest (checksum) cipher file
            byte[] md5sum_ = crypt_digest == null ? null : crypt_digest.digest();
            result1 = "";
            if (md5sum_ != null)
                for (int i = 0; i < md5sum_.length; i++)
                    result1 += Integer.toString((md5sum_[i] & 0xff) + 0x100, 16).substring(1);
        }
    } catch (IOException e) {
        ;
    }

    if (pgKey != null) {
        results = new String[2];
        results[0] = result;
        results[1] = result1;
    } else {
        results = new String[1];
        results[0] = result;
    }

    return results;
}

From source file:uk.ac.ebi.enaega.uploadclient.UploadClient.java

@Override
public void run() {
    completed = false;//from w  ww  .j  a v a2s . c om
    System.setProperty("java.net.preferIPv4Stack", "true");
    ByteArrayOutputStream baos = null; // PGP
    MessageDigest crypt_digest = null; // PGP
    OutputStream literalOut = null, encOut = null, compressedOut = null; // PGP
    int DEFAULT_BUFFER_SIZE = 65 * 1024; // PGP
    PGPEncryptedDataGenerator encryptedDataGenerator = null; // PGP
    PGPCompressedDataGenerator compressedDataGenerator = null; // PGP
    PGPLiteralDataGenerator literalDataGenerator = null; // PGP

    if (this.pgKey != null) { // EGA: Encrypt file
        try {
            Security.addProvider(new BouncyCastleProvider());
            baos = new ByteArrayOutputStream(2 * DEFAULT_BUFFER_SIZE); // Write to memory!
            try {
                crypt_digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Encrypted Data Generator -- needs unlimited Security Policy
            encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true,
                    new SecureRandom(), "BC");
            try {
                encryptedDataGenerator.addMethod(this.pgKey);
                encOut = encryptedDataGenerator.open(baos, new byte[DEFAULT_BUFFER_SIZE]);
            } catch (NoSuchProviderException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            } catch (PGPException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Compression
            compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
            compressedOut = compressedOut = new BufferedOutputStream(compressedDataGenerator.open(encOut));

            // Literal Data Generator and Output Stream
            literalDataGenerator = new PGPLiteralDataGenerator();
            literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
                    new byte[DEFAULT_BUFFER_SIZE]); // 1<<16                                
        } catch (Throwable t) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "Can't instantiate cipher key.\nBe sure to have JCE Unlimited Strength Security Policy installed.",
                    "Cipher Key Problem", JOptionPane.ERROR_MESSAGE);
            String[] failure = { "Cipher Issues" };
            return;
            //return failure;
        }
    }

    // Upload the stream.
    try {
        // Skips.
        inputStream.skip(streamOffset);
        // Opens the data transfer connection.
        dataTransferOutputStream = dtConnection.getOutputStream(); // TCP or UDT - automatically

        // MODE Z enabled?
        if (modezEnabled) { // don't use with PGP stream
            dataTransferOutputStream = new DeflaterOutputStream(dataTransferOutputStream);
        }
        // Listeners. Initialize to offset!
        if (listener != null) {
            listener.started();
            int large = 0, small = 0;
            large = (int) (offset / Integer.MAX_VALUE); // times the size of largest int
            small = (int) (offset % Integer.MAX_VALUE); // remainder
            for (int iu = 0; iu < large; iu++)
                listener.transferred(Integer.MAX_VALUE);
            listener.transferred(small);
        }
        long tot = 0;
        int idx = 0; // Update the table model
        if (mm != null) { // For Table Updates
            idx = mm.getCur();
            mm.setValueAt("0%", idx, 5);
            tot = mm.getSize();
        }
        // Let's do it!
        if (tp == TYPE_TEXTUAL) { // ------------------------------------- TEXT DATA ------------------
            char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE];
            byte[] bbuffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE];
            int l, l_tot = 0;

            Reader reader = new InputStreamReader(inputStream);
            Writer writer = new OutputStreamWriter(dataTransferOutputStream, charSet);

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            }

            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload
            while ((l = reader.read(buffer)) != -1) { // The actual data transfer loop -------------------
                System.arraycopy(buffer, 0, bbuffer, 0, l);
                digest.update(bbuffer, 0, l); // Calculate MD5 for TCP stream

                if (this.pgKey != null) { // Cipher - write to mem buffer first, to enable MD5
                    literalOut.write(bbuffer, 0, l);
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray();
                    crypt_digest.update(buffer_);
                    char[] buffer__ = new char[buffer_.length];
                    System.arraycopy(buffer_, l_tot, buffer__, 0, buffer_.length);
                    writer.write(buffer__);
                    baos.reset();
                } else { // Write directly to socket
                    writer.write(buffer, 0, l);
                }
                writer.flush();

                if (listener != null) {
                    listener.transferred(l);
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) {
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            }

            // Get a representation of the MD5 digest (checksum)
            byte[] md5sum = digest.digest();
            result = "";
            if (md5sum != null)
                for (int i = 0; i < md5sum.length; i++)
                    result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);

        } else if (tp == TYPE_BINARY) { // ------------------------------ BINARY DATA ---------------------
            byte[] buffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE];
            int l;
            long l_tot = 0;

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(FTPClient_alternative.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Actual transfer identical between TCP and UDT
            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload                                        
            while ((l = inputStream.read(buffer)) != -1) { // The actual data transfer loop -------------------
                if (this.pgKey != null) {
                    literalOut.write(buffer, 0, l); // Write to mem buffer
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
                    crypt_digest.update(buffer_); // update crypto MD5
                    dataTransferOutputStream.write(buffer_); // Write cipher data to socket
                    c += buffer_.length;
                    baos.reset(); // empty mem buffer
                } else {
                    dataTransferOutputStream.write(buffer, 0, l); // no cipher -- write directly to socket
                    c += buffer.length;
                }
                dataTransferOutputStream.flush();

                digest.update(buffer, 0, l); // Calculate plain text MD5 for TCP stream

                if (listener != null) {
                    listener.transferred(l); // Update total-progress bar
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) { // Update in-table progress bar
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            }

            // Get a representation of the MD5 digest (checksum) plain file
            byte[] md5sum = digest.digest();
            result = "";
            if (md5sum != null)
                for (int i = 0; i < md5sum.length; i++)
                    result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);
        }

        // Upload loop complete. Close PGP streams, if used
        if (this.pgKey != null) {
            literalOut.close();
            literalDataGenerator.close();
            // Close all other streams
            compressedOut.close();
            compressedDataGenerator.close();
            encOut.close();
            encryptedDataGenerator.close();
            byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
            crypt_digest.update(buffer_); // update crypto MD5
            dataTransferOutputStream.write(buffer_); // Write cipher data to socket
            dataTransferOutputStream.flush();
            baos.close();

            // Get a representation of the MD5 digest (checksum) cipher file
            byte[] md5sum = crypt_digest.digest();
            result1 = "";
            for (int i = 0; i < md5sum.length; i++)
                result1 += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);

            complete = true;
        }

    } catch (Throwable e) {
        if (listener != null) {
            listener.aborted();
        }
        complete = false;
        try {
            throw new FTPDataTransferException("I/O error in data transfer", e);
        } catch (FTPDataTransferException ex) {
            Logger.getLogger(UploadClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    completed = true;
}

From source file:uk.ac.ebi.enaega.uploadclient.UploadClientUDT.java

@Override
public void run() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    ByteArrayOutputStream baos = null; // PGP
    MessageDigest crypt_digest = null; // PGP
    OutputStream literalOut = null, encOut = null, compressedOut = null; // PGP
    int DEFAULT_BUFFER_SIZE = 65 * 1024; // PGP
    PGPEncryptedDataGenerator encryptedDataGenerator = null; // PGP
    PGPCompressedDataGenerator compressedDataGenerator = null; // PGP
    PGPLiteralDataGenerator literalDataGenerator = null; // PGP

    if (this.pgKey != null) { // EGA: Encrypt file
        try {/* ww w  . j a  v a2  s. c o m*/
            Security.addProvider(new BouncyCastleProvider());
            baos = new ByteArrayOutputStream(2 * DEFAULT_BUFFER_SIZE); // Write to memory!
            try {
                crypt_digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Encrypted Data Generator -- needs unlimited Security Policy
            encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, true,
                    new SecureRandom(), "BC");
            try {
                encryptedDataGenerator.addMethod(this.pgKey);
                encOut = encryptedDataGenerator.open(baos, new byte[DEFAULT_BUFFER_SIZE]);
            } catch (NoSuchProviderException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            } catch (PGPException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Compression
            compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
            compressedOut = compressedOut = new BufferedOutputStream(compressedDataGenerator.open(encOut));

            // Literal Data Generator and Output Stream
            literalDataGenerator = new PGPLiteralDataGenerator();
            literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
                    new byte[DEFAULT_BUFFER_SIZE]); // 1<<16                                
        } catch (Throwable t) {
            JOptionPane.showMessageDialog(new JFrame(),
                    "Can't instantiate cipher key.\nBe sure to have JCE Unlimited Strength Security Policy installed.",
                    "Cipher Key Problem", JOptionPane.ERROR_MESSAGE);
            String[] failure = { "Cipher Issues" };
            return;
            //return failure;
        }
    }

    // Upload the stream.
    // Transfer! Start by accepting aconnection initiated by the server
    UnifiedSocket dataSocket = null;

    // Upload the stream.
    long c = 0;
    System.out.println("1 getting " + dataHost.toString() + "   " + hostPort);
    try {
        //                    dataSocket = pasvServer.getMatching( dataHost, hostPort );
        dataSocket = getSocket_timeout(); //getSocket();
        //if (dataSocket == null) dataSocket = getSocket_timeout();
        if (dataSocket == null)
            throw new ConnectException();
        System.out.println("2");

        // Skips.
        inputStream.skip(streamOffset);
        // Opens the data transfer connection.
        dataTransferOutputStream = dataSocket.getOutputStream(); // TCP or UDT - automatically

        // Listeners. Initialize to offset!
        if (listener != null) {
            listener.started();
            int large = 0, small = 0;
            large = (int) (offset / Integer.MAX_VALUE); // times the size of largest int
            small = (int) (offset % Integer.MAX_VALUE); // remainder
            for (int iu = 0; iu < large; iu++)
                listener.transferred(Integer.MAX_VALUE);
            listener.transferred(small);
        }
        long tot = 0;
        int idx = 0; // Update the table model
        if (mm != null) { // For Table Updates
            idx = mm.getCur();
            mm.setValueAt("0%", idx, 5);
            tot = mm.getSize();
        }

        String line = communication.readFTPReply().toString();
        System.out.println("Server Reply (STOR test.txt): " + line);

        // Let's do it!
        if (tp == TYPE_TEXTUAL) { // ------------------------------------- TEXT DATA ------------------
            char[] buffer = new char[SEND_AND_RECEIVE_BUFFER_SIZE];
            byte[] bbuffer = new byte[SEND_AND_RECEIVE_BUFFER_SIZE];
            int l, l_tot = 0;
            long cnt = 0, cnt_ = 0;
            long block_cnt = 0, block_cnt_pre = 0;
            long flush_point = 1048576L * 10L;
            long pre_flush_point = 1048576L * 9L;

            Reader reader = new InputStreamReader(inputStream);
            Writer writer = new OutputStreamWriter(dataTransferOutputStream, charSet);

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload
            while ((l = reader.read(buffer)) != -1) { // The actual data transfer loop -------------------
                System.arraycopy(buffer, 0, bbuffer, 0, l);
                digest.update(bbuffer, 0, l); // Calculate MD5 for TCP stream

                if (this.pgKey != null) { // Cipher - write to mem buffer first, to enable MD5
                    literalOut.write(bbuffer, 0, l);
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray();
                    crypt_digest.update(buffer_);
                    char[] buffer__ = new char[buffer_.length];
                    System.arraycopy(buffer_, l_tot, buffer__, 0, buffer_.length);
                    cnt += buffer_.length;
                    cnt_ += buffer_.length;
                    block_cnt += buffer_.length;
                    block_cnt_pre += buffer_.length;
                    writer.write(buffer__);
                    baos.reset();
                } else { // Write directly to socket
                    cnt += buffer.length;
                    cnt_ += buffer.length;
                    block_cnt += buffer.length;
                    block_cnt_pre += buffer.length;
                    writer.write(buffer, 0, l);
                }
                if ((block_cnt_pre / pre_flush_point) > 0) {
                    block_cnt_pre = 0;
                    writer.flush();
                }
                //writer.flush();

                if (listener != null) {
                    listener.transferred(l);
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) {
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            }

            // Get a representation of the MD5 digest (checksum)
            byte[] md5sum = digest.digest();
            result = "";
            for (int i = 0; i < md5sum.length; i++)
                result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);

        } else if (tp == TYPE_BINARY) { // ------------------------------ BINARY DATA ---------------------
            System.out.println("Binary Transfer");
            long cnt = 0, cnt_ = 0;
            long block_cnt = 0, block_cnt_pre = 0;
            long flush_point = 1048576L * 10L;
            long pre_flush_point = 1048576L * 9L;
            int bufsze = 250 * (UDPEndPoint.DATAGRAM_SIZE - 24);
            byte[] buffer = new byte[bufsze];

            int l;
            long l_tot = 0;

            MessageDigest digest = null; // calculate checksum of incoming data stream
            try {
                digest = MessageDigest.getInstance("MD5"); // get the hash algorithm
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
            }

            // Actual transfer identical between TCP and UDT
            long dt_file = System.currentTimeMillis(), dt_upd = System.currentTimeMillis(); // time before upload
            CircularBuffer cb = new CircularBuffer(bufsze + (20 * (UDPEndPoint.DATAGRAM_SIZE - 24)));

            System.out.println("Actual Send Loop starts");
            while ((l = inputStream.read(buffer)) != -1) { // The actual data transfer loop -------------------
                if (this.pgKey != null) { // PGP Key present - encrypted Stream
                    literalOut.write(buffer, 0, l); // Write to mem buffer - this is the encryption
                    literalOut.flush();
                    byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
                    crypt_digest.update(buffer_); // update crypto MD5
                    c += buffer_.length;
                    cb.put(buffer_); // Write into circular buffer                                                
                    baos.reset(); // empty mem buffer
                } else {
                    c += l; //buffer.length; // only what was read!
                    cb.put(Arrays.copyOf(buffer, l)); // Write into circular buffer
                }

                // Send the data in packet-sized portions from circular buffer temp structure
                while (cb.getSize() > (UDPEndPoint.DATAGRAM_SIZE - 24)) {
                    byte[] sendbuf = new byte[(UDPEndPoint.DATAGRAM_SIZE - 24)];
                    sendbuf = cb.get(sendbuf.length);

                    cnt += sendbuf.length;
                    cnt_ += sendbuf.length;
                    block_cnt += sendbuf.length;
                    block_cnt_pre += sendbuf.length;
                    dataTransferOutputStream.write(sendbuf, 0, sendbuf.length); // buffer, 0, l

                    if ((block_cnt_pre / pre_flush_point) > 0) {
                        block_cnt_pre = 0;
                        ((UDTOutputStream) dataTransferOutputStream).pre_flush();
                    }

                    if ((block_cnt / flush_point) > 0) {
                        block_cnt = 0;
                        dataTransferOutputStream.flush();
                    }
                }

                digest.update(buffer, 0, l); // Calculate plain text MD5 for TCP stream

                if (listener != null) {
                    listener.transferred(l); // Update total-progress bar
                    if (l > 0) { // l = bytes, dt_file = milliseconds
                        dt_upd = System.currentTimeMillis() - dt_upd;
                        double rate = (((double) (l)) / (((double) (dt_upd)))) * 1000.0; // bytes/s
                        if (rate > 0) {
                            String sd = size_display((long) (rate));
                            if (sd != null && sd.length() > 0)
                                listener.setText(size_display((long) (rate)) + "/s");
                        }
                        dt_upd = System.currentTimeMillis();
                    }
                }

                if (mm != null && tot != 0) { // Update in-table progress bar
                    l_tot += l;
                    double pct = (double) l_tot / (double) tot;
                    int i_pct = (int) Math.floor(pct * 100);
                    String s_pct = String.valueOf(i_pct) + "%";
                    mm.setValueAt(s_pct, idx, 5);
                }
            } // Input stream completely read ---
            if (cb.getSize() > 0) { // Flush the buffer at the end - MD5s already complete at this point
                byte[] sendbuf = new byte[cb.getSize()];
                sendbuf = cb.get(sendbuf.length);
                dataTransferOutputStream.write(sendbuf, 0, sendbuf.length);
            }

            // Get a representation of the MD5 digest (checksum) plain file
            byte[] md5sum = digest.digest();
            result = "";
            for (int i = 0; i < md5sum.length; i++)
                result += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);
        }

        // Upload loop complete. Close PGP streams, if used (produces extra data)
        if (this.pgKey != null) {
            literalOut.close();
            literalDataGenerator.close();
            // Close all other streams
            compressedOut.close();
            compressedDataGenerator.close();
            encOut.close();
            encryptedDataGenerator.close();
            byte[] buffer_ = baos.toByteArray(); // retrieve that buffer
            crypt_digest.update(buffer_); // update crypto MD5
            dataTransferOutputStream.write(buffer_); // Write cipher data to socket
            dataTransferOutputStream.flush();
            baos.close();

            // Get a representation of the MD5 digest (checksum) cipher file
            byte[] md5sum = crypt_digest.digest();
            result1 = "";
            for (int i = 0; i < md5sum.length; i++)
                result1 += Integer.toString((md5sum[i] & 0xff) + 0x100, 16).substring(1);
        }

        dataTransferOutputStream.flush();
    } catch (Throwable e) {
        if (listener != null) {
            listener.aborted();
        }
        try {
            throw new FTPDataTransferException("I/O error in data transfer", e);
        } catch (FTPDataTransferException ex) {
            Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        // Closing stream and data connection.
        if (dataTransferOutputStream != null) {
            try {
                dataTransferOutputStream.flush();
                dataTransferOutputStream.close();
            } catch (Throwable t) {
                ;
            }
        }
        try {
            dataSocket.close();
        } catch (Throwable t) {
            ;
        }
        // Set to null the instance-level input stream.
        dataTransferOutputStream = null;
        // Consume the result reply of the transfer.
        FTPReply readFTPReply = null;
        try {
            readFTPReply = communication.readFTPReply();
        } catch (Throwable ex) {
            Logger.getLogger(UploadClientUDT.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(readFTPReply.toString());
        // Change the operation status.
    }

}