Example usage for org.bouncycastle.bcpg ArmoredOutputStream close

List of usage examples for org.bouncycastle.bcpg ArmoredOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Note: close() does not close the underlying stream.

Usage

From source file:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

@Override
public void encrypt(final OutputStream outputStream, final InputStream inputStream, final String[] keyInfo) {

    try {//  w w w  . j  av  a  2 s  .  c om
        // =
        // this.readPublicKey(this.publicKeyRing);

        final ArmoredOutputStream out = new ArmoredOutputStream(outputStream);

        try {
            final BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(
                    SymmetricKeyAlgorithmTags.CAST5);
            builder.setSecureRandom(new SecureRandom());
            final PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(builder, true);
            for (final String info : keyInfo) {
                final PGPPublicKey encKey = this.getEncryptionKey(info);
                if (encKey != null) {
                    cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
                } else {
                    OpenPGPSecurityUtility.LOGGER
                            .info("Encryption key for recipient " + info + " could not be found!");
                }

            }

            final OutputStream cOut = cPk.open(out, new byte[1 << 16]);

            final PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
                    CompressionAlgorithmTags.ZIP);

            final PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
            final byte[] buffer = new byte[1 << 16];
            final OutputStream pOut = lData.open(comData.open(cOut), PGPLiteralData.BINARY, "", new Date(),
                    buffer);

            final byte[] buf = new byte[buffer.length];
            int len;

            while ((len = inputStream.read(buf)) > 0) {
                pOut.write(buf, 0, len);
            }

            lData.close();
            inputStream.close();

            comData.close();

            cOut.close();

            out.close();

        } catch (final PGPException e) {
            System.err.println(e);
            if (e.getUnderlyingException() != null) {
                e.getUnderlyingException().printStackTrace();
            }
        }
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

@Override
public void sign(final OutputStream outputStream, final InputStream inputStream, final String keyInfo) {
    try {//  ww w.  j av a  2 s. c  o  m
        final File keyFile = this.secretKeyRing;
        final char[] pass = this.secretKeyRingPassword;

        final ArmoredOutputStream out = new ArmoredOutputStream(outputStream);

        final PGPSecretKey pgpSec = this.getSignKey(keyInfo); // readSecretKey(new
        // FileInputStream(keyFile));
        final PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(
                new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass));
        final PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1));

        sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

        final Iterator it = pgpSec.getPublicKey().getUserIDs();
        if (it.hasNext()) {
            final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            spGen.setSignerUserID(false, (String) it.next());
            sGen.setHashedSubpackets(spGen.generate());
        }

        final PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB);

        final BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));

        sGen.generateOnePassVersion(false).encode(bOut);

        final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        final byte[] buffer = new byte[1 << 16];
        final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "", new Date(), buffer);
        int ch = 0;

        while ((ch = inputStream.read()) >= 0) {
            lOut.write(ch);
            sGen.update((byte) ch);
        }

        lGen.close();

        sGen.generate().encode(bOut);
        cGen.close();

        out.close();
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final PGPException e) {
        e.printStackTrace();
    } catch (final SignatureException e) {
        e.printStackTrace();
    }
}

From source file:com.fuzion.tools.pgp.BCPGPKeyGenTools.java

License:Open Source License

public static final void exportSecretKey(PGPKeyRingGenerator pgpKeyRingGen, File keyFile, boolean asciiArmor)
        throws IOException {
    PGPSecretKeyRing pgpSecKeyRing = pgpKeyRingGen.generateSecretKeyRing();

    if (asciiArmor) {
        ArmoredOutputStream aos = new ArmoredOutputStream(new FileOutputStream(keyFile));
        pgpSecKeyRing.encode(aos);/*w  w  w  .j av a2  s  .c om*/
        aos.close();
    } else {
        FileOutputStream fos = new FileOutputStream(keyFile);
        pgpSecKeyRing.encode(fos);
        fos.close();
    }
}

From source file:com.fuzion.tools.pgp.BCPGPKeyGenTools.java

License:Open Source License

public static final void exportPublicKey(PGPKeyRingGenerator pgpKeyRingGen, File keyFile, boolean asciiArmor)
        throws IOException {
    PGPPublicKeyRing pgpPubKeyRing = pgpKeyRingGen.generatePublicKeyRing();

    if (asciiArmor) {
        ArmoredOutputStream aos = new ArmoredOutputStream(new FileOutputStream(keyFile));
        pgpPubKeyRing.encode(aos);//from  w w  w.  j  a  v a  2  s  .c  om
        aos.close();
    } else {
        FileOutputStream fos = new FileOutputStream(keyFile);
        pgpPubKeyRing.encode(fos);
        fos.close();
    }
}

From source file:com.github.chrbayer84.keybits.GnuPGP.java

License:Open Source License

public String getArmored(PGPPublicKeyRing public_key_ring) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ArmoredOutputStream armored = new ArmoredOutputStream(out);

    public_key_ring.encode(armored);
    armored.close();

    String ret = new String(out.toByteArray());
    out.close();//from   w  w w. j a  v a  2s . c o  m

    return ret;
}

From source file:com.github.sannies.nexusaptplugin.sign.PGPSigner.java

License:Apache License

/**
 * Creates a clear sign signature over the input data. (Not detached)
 *
 * @param input      the content to be signed
 * @param output     the output destination of the signature
 *///from   w  w  w.j  av  a  2  s  . c  o  m
public void clearSign(InputStream input, OutputStream output)
        throws IOException, PGPException, GeneralSecurityException {
    int digest = PGPUtil.SHA1;

    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);

    ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);
    armoredOutput.beginClearText(digest);

    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    String line;
    while ((line = reader.readLine()) != null) {
        // trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1)
        byte[] data = trim(line).getBytes("UTF-8");

        armoredOutput.write(data);
        armoredOutput.write(EOL);

        signatureGenerator.update(data);
        signatureGenerator.update(EOL);
    }

    armoredOutput.endClearText();

    PGPSignature signature = signatureGenerator.generate();
    signature.encode(new BCPGOutputStream(armoredOutput));

    armoredOutput.close();
}

From source file:com.goodvikings.cryptim.api.CryptimMessageListener.java

License:BEER-WARE LICENSE

/**
 * Sends this client's public key to the chat partner
 * @param chat The chat to send the key in
 * @throws IOException If an IO exception occurs
 * @throws XMPPException If an XMPP exception occurs
 */// w w  w  .java 2 s  . c o m
public void sendKey(Chat chat) throws IOException, XMPPException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArmoredOutputStream aos = new ArmoredOutputStream(baos);
    kr.getMyPublic().encode(aos);
    aos.close();

    Message keyMsg = new Message();
    keyMsg.setBody(baos.toString());
    keyMsg.setProperty(CryptimUtils.XMPPTAG, CryptimUtils.KEYEXCHANGE);
    chat.sendMessage(keyMsg);
}

From source file:com.google.gerrit.server.contact.EncryptedContactStore.java

License:Apache License

private byte[] encrypt(final String name, final Date date, final byte[] rawText)
        throws NoSuchProviderException, PGPException, IOException {
    final byte[] zText = compress(name, date, rawText);

    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final ArmoredOutputStream aout = new ArmoredOutputStream(buf);
    final OutputStream cout = cpk().open(aout, zText.length);
    cout.write(zText);//from  w  ww .  j a v a 2s. c  om
    cout.close();
    aout.close();

    return buf.toByteArray();
}

From source file:com.navnorth.learningregistry.LRSigner.java

License:Apache License

/**
 * Encodes the provided message with the private key and pass phrase set in configuration
 *
 * @param message Message to encode// w  ww . j a v  a2  s  .c o  m
 * @return Encoded message
 * @throws LRException SIGNING_FAILED if the document cannot be signed, NO_KEY if the key cannot be obtained
 */
private String signEnvelopeData(String message) throws LRException {
    // Throw an exception if any of the required fields are null
    if (passPhrase == null || publicKeyLocation == null || privateKey == null) {
        throw new LRException(LRException.NULL_FIELD);
    }

    // Add the provider here so that after signing, we can remove the provider.
    // This allows using this code from multiple separate class loaders while Bouncy Castle is on a separate class loader
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    try {

        // Get an InputStream for the private key
        InputStream privateKeyStream = getPrivateKeyStream(privateKey);

        // Get an OutputStream for the result
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ArmoredOutputStream aOut = new ArmoredOutputStream(result);

        // Get the pass phrase
        char[] privateKeyPassword = passPhrase.toCharArray();

        try {
            // Get the private key from the InputStream
            PGPSecretKey sk = readSecretKey(privateKeyStream);
            PGPPrivateKey pk = sk.extractPrivateKey(
                    new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(privateKeyPassword));
            PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                    new JcaPGPContentSignerBuilder(sk.getPublicKey().getAlgorithm(), PGPUtil.SHA256)
                            .setProvider("BC"));
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            // Clear sign the message
            java.util.Iterator it = sk.getPublicKey().getUserIDs();
            if (it.hasNext()) {
                spGen.setSignerUserID(false, (String) it.next());
                sGen.setHashedSubpackets(spGen.generate());
            }
            aOut.beginClearText(PGPUtil.SHA256);
            sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, pk);
            byte[] msg = message.getBytes();
            sGen.update(msg, 0, msg.length);
            aOut.write(msg, 0, msg.length);
            BCPGOutputStream bOut = new BCPGOutputStream(aOut);
            aOut.endClearText();
            sGen.generate().encode(bOut);
            aOut.close();

            String strResult = result.toString("utf8");

            // for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE"
            strResult = strResult.replaceAll("([a-z0-9])-----BEGIN PGP SIGNATURE-----",
                    "$1\n-----BEGIN PGP SIGNATURE-----");

            return strResult;
        } catch (Exception e) {
            throw new LRException(LRException.SIGNING_FAILED, e);
        } finally {
            try {
                if (privateKeyStream != null) {
                    privateKeyStream.close();
                }

                result.close();
            } catch (IOException e) {
                //Could not close the streams
            }
        }
    } finally {
        Security.removeProvider(provider.getName());
    }
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public void generateKeys(String username, String passphrase) {
    try {//from  w  w w  . j  ava  2  s  . co  m
        BigInteger primeModulous = PGPTools.getSafePrimeModulus(PGPTools.PRIME_MODULUS_4096_BIT);
        BigInteger baseGenerator = PGPTools.getBaseGenerator();
        ElGamalParameterSpec paramSpecs = new ElGamalParameterSpec(primeModulous, baseGenerator);

        KeyPair dsaKeyPair = PGPTools.generateDsaKeyPair(1024);
        KeyPair elGamalKeyPair = PGPTools.generateElGamalKeyPair(paramSpecs);

        this.pgpKeyRingGen = PGPTools.createPGPKeyRingGenerator(dsaKeyPair, elGamalKeyPair, username,
                passphrase.toCharArray());
        PGPSecretKeyRing pgpSecKeyRing = this.pgpKeyRingGen.generateSecretKeyRing();
        PGPPublicKeyRing pgpPubKeyRing = this.pgpKeyRingGen.generatePublicKeyRing();

        /* Save secret key*/
        ByteArrayOutputStream pgpSecKeyRingOutputStream = new ByteArrayOutputStream();
        ArmoredOutputStream aosSecret = new ArmoredOutputStream(pgpSecKeyRingOutputStream);
        pgpSecKeyRing.encode(aosSecret);
        aosSecret.close();
        this.armoredSecretKey = pgpSecKeyRingOutputStream.toByteArray();

        /* Save public key*/
        ByteArrayOutputStream pgpPubKeyRingOutputStream = new ByteArrayOutputStream();
        ArmoredOutputStream aosPublic = new ArmoredOutputStream(pgpPubKeyRingOutputStream);
        pgpPubKeyRing.encode(aosPublic);
        aosPublic.close();
        this.armoredPublicKey = pgpPubKeyRingOutputStream.toByteArray();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}