Example usage for org.bouncycastle.openpgp PGPSecretKey getPublicKey

List of usage examples for org.bouncycastle.openpgp PGPSecretKey getPublicKey

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPSecretKey getPublicKey.

Prototype

public PGPPublicKey getPublicKey() 

Source Link

Document

Return the public key associated with this key.

Usage

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 {/*from  ww  w  . j a v a2  s.  com*/
        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.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 ww .  j  a va 2  s  .com*/
        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

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

        PGPObjectFactory pgpFact = new PGPObjectFactory(fileToDecrypt);

        Object message = pgpFact.nextObject();

        PGPPublicKeyEncryptedData pked = null;
        //            PGPCompressedData cData;

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

            PGPEncryptedDataList enc = (PGPEncryptedDataList) message;

            int count = 0;

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

                count++;
            }

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

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

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

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

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

            PGPObjectFactory pgpClearFact = new PGPObjectFactory(clear);

            message = pgpClearFact.nextObject();

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

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

            message = pgpFact.nextObject();
        }

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

            InputStream dataIn = ld.getInputStream();

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

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

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

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

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

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

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

License:Open Source License

/**
 * Get the keyring pointed to by the public & secret files.  Creates the files
 * with a single key if they don't already exist; interrogates keyDataSource for the
 * info to create the key (typically it should pop up a gui).
 * /*from  w w w  .  jav a  2  s.  c  om*/
 * TODO bobby: doesn't create usable keyrings yet, and doesn't save what it does create :-( 
 * @param publicKeyRingFile
 * @param secretKeyRingFile
 * @param keyDataSource
 * @return
 * @throws PGPException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
public Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> getOrCreateKeyring(File publicKeyRingFile,
        File secretKeyRingFile, KeyDataSource keyDataSource) throws PGPException, FileNotFoundException,
        IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    boolean pubRingFound = publicKeyRingFile.isFile();
    boolean secRingFound = secretKeyRingFile.isFile();

    if (pubRingFound != secRingFound) {
        throw new PGPException("Expect both public & secret keyring, or neither: " + publicKeyRingFile + ", "
                + secretKeyRingFile);
    }

    Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> retval = new Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection>();

    if (pubRingFound) {
        retval.setFirst(EncryptionUtil.instance().readPublicKeyRingCollection(publicKeyRingFile));
        retval.setSecond(EncryptionUtil.instance().readSecretKeyRingCollection(secretKeyRingFile));
    } else {
        if (publicKeyRingFile.exists() || secretKeyRingFile.exists()) {
            throw new PGPException("Either public or secret keyring not a normal file: " + publicKeyRingFile
                    + ", " + secretKeyRingFile);
        }

        PGPSecretKey key = generateKey(keyDataSource.getIdentity(), keyDataSource.getPassphrase());

        PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(key.getPublicKey().getEncoded());
        Collection<PGPPublicKeyRing> collection = Collections.singletonList(publicKeyRing);
        retval.setFirst(new PGPPublicKeyRingCollection(collection));

        PGPSecretKeyRing secretKeyRing = new PGPSecretKeyRing(key.getEncoded());
        Collection<PGPSecretKeyRing> secretKeyRings = Collections.singletonList(secretKeyRing);
        retval.setSecond(new PGPSecretKeyRingCollection(secretKeyRings));

        //TODO bobby save keyrings to the files
    }

    return retval;
}

From source file:com.ginema.crypto.encryption.PGPKeyPairGenerator.java

License:Apache License

private static void exportKeyPair(OutputStream secretOut, OutputStream publicOut, PublicKey publicKey,
        PrivateKey privateKey, String identity, char[] passPhrase, boolean armor)
        throws IOException, InvalidKeyException, NoSuchProviderException, SignatureException, PGPException {
    if (armor) {/*from  www .  ja v  a2  s. c om*/
        secretOut = new ArmoredOutputStream(secretOut);
    }

    PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PGPPublicKey.RSA_GENERAL,
            publicKey, privateKey, new Date(), identity, PGPEncryptedData.CAST5, passPhrase, null, null,
            new SecureRandom(), "BC");

    secretKey.encode(secretOut);

    secretOut.close();

    if (armor) {
        publicOut = new ArmoredOutputStream(publicOut);
    }

    PGPPublicKey key = secretKey.getPublicKey();

    key.encode(publicOut);

    publicOut.close();
}

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

License:Apache License

static final PGPPrivateKey extractDecryptionKey(PGPSecretKeyRing pskr, String pass) throws PGPException {
    Iterator<PGPSecretKey> skit = Util.getTypedIterator(pskr.getSecretKeys(), PGPSecretKey.class);

    PGPSecretKey selected = null;/*w  w w .ja  v  a  2s  .c  o  m*/

    // Pass #1 - use key flags on signatures.
    while (skit.hasNext()) {
        PGPSecretKey sk = skit.next();
        Iterator<PGPSignature> sigit = Util.getTypedIterator(sk.getPublicKey().getSignatures(),
                PGPSignature.class);
        while (sigit.hasNext()) {
            if (Util.hasKeyFlag(sigit.next(), KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE)) {
                selected = sk;
                break;
            }
        }
    }
    if (selected == null) {
        // Pass #2 - use intrinsic key capabilities, but prefer subkeys
        // where possible.
        skit = Util.getTypedIterator(pskr.getSecretKeys(), PGPSecretKey.class);
        while (skit.hasNext()) {
            PGPSecretKey sk = skit.next();
            if (sk.getPublicKey().isEncryptionKey()) {
                selected = sk;
                // But continue the loop, so subkeys will be chosen.
            }
        }
    }

    if (selected != null) {
        return selected
                .extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
                        .build(pass.toCharArray()));
    } else {
        return null;
    }
}

From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * PGP sign a stream.//from   w  w  w .  j av  a 2 s.co m
 *
 * @param data       The stream that contains the data to sign.
 * @param privateKey The private key to use for signing.
 * @param passPhrase The passphrase that the private key is locked with.
 * @param armoured   {@code true}: ASCII armor the signature.
 *
 * @return The signature.
 *
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws FileNotFoundException
 * @throws PGPException
 * @throws IOException
 */
public static InputStream sign(final InputStream data, final PGPSecretKey privateKey, final String passPhrase,
        final boolean armoured) throws NoSuchAlgorithmException, NoSuchProviderException, PGPException,
        SignatureException, IOException {

    /* Build the signature generator. */
    PGPSignatureGenerator signer = new PGPSignatureGenerator(privateKey.getPublicKey().getAlgorithm(),
            HashAlgorithmTags.SHA1, BouncyCastleProvider.PROVIDER_NAME);
    signer.initSign(PGPSignature.BINARY_DOCUMENT,
            privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME));

    /* Write the data into the generator. */
    byte[] buffer = new byte[4096];
    for (int read; (read = data.read(buffer)) >= 0;)
        signer.update(buffer, 0, read);

    /* Create the signature output stream, armour if necessary. */
    try (ByteArrayOutputStream signatureByteStream = new ByteArrayOutputStream();
            OutputStream signatureStream = armoured ? new ArmoredOutputStream(signatureByteStream)
                    : signatureByteStream) {

        /* Create and write out the signature. */
        PGPSignature signature = signer.generate();
        signature.encode(signatureStream);

        return new ByteArrayInputStream(signatureByteStream.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//from w  w w  . j av a  2  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:com.zwitserloot.ivyplusplus.mavencentral.CreateDetachedSignatures_.java

License:Open Source License

void signFile(InputStream fileData, PGPSecretKey signingKey, String passphrase, OutputStream out)
        throws IOException, NoSuchProviderException, PGPException, NoSuchAlgorithmException,
        SignatureException {/*from ww w .  ja  va 2  s . c o m*/
    PGPPrivateKey privKey = signingKey.extractPrivateKey(passphrase.toCharArray(), "BC");
    PGPSignatureGenerator sigGen = new PGPSignatureGenerator(signingKey.getPublicKey().getAlgorithm(),
            PGPUtil.SHA1, "BC");
    sigGen.initSign(PGPSignature.BINARY_DOCUMENT, privKey);
    out = new ArmoredOutputStream(out);
    BCPGOutputStream bOut = new BCPGOutputStream(out);
    byte[] b = new byte[4096];
    while (true) {
        int r = fileData.read(b);
        if (r == -1)
            break;
        sigGen.update(b, 0, r);
    }

    sigGen.generate().encode(bOut);
    bOut.close();
    out.close();
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public String signData(String data, String passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey);
    PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream);
    PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider("BC"));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> it = pgpSecretKey.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, it.next());
        signatureGenerator.setHashedSubpackets(spGen.generate());
    }// ww w .  ja v a  2  s  . c om
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = new ArmoredOutputStream(byteOutputStream);
    PGPCompressedDataGenerator compressDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
    BCPGOutputStream bcOutputStream = new BCPGOutputStream(compressDataGenerator.open(outputStream));
    signatureGenerator.generateOnePassVersion(false).encode(bcOutputStream);

    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    File fileToSign = File.createTempFile("temp", ".scrap");
    FileUtils.writeStringToFile(fileToSign, data);

    OutputStream literalDataGenOutputStream = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY,
            fileToSign);
    FileInputStream fis = new FileInputStream(fileToSign);
    int ch;
    while ((ch = fis.read()) >= 0) {
        literalDataGenOutputStream.write(ch);
        signatureGenerator.update((byte) ch);
    }

    literalDataGenerator.close();
    fis.close();

    signatureGenerator.generate().encode(bcOutputStream);
    compressDataGenerator.close();
    outputStream.close();

    fileToSign.delete();
    return new String(byteOutputStream.toByteArray(), "UTF-8");
}