Example usage for org.bouncycastle.openpgp PGPSignatureGenerator initSign

List of usage examples for org.bouncycastle.openpgp PGPSignatureGenerator initSign

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPSignatureGenerator initSign.

Prototype

public void initSign(int signatureType, PGPPrivateKey key) throws PGPException 

Source Link

Document

Initialise the generator for signing.

Usage

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

License:Open Source License

/**
 * Sign the passed in message stream//from ww  w  . jav a  2 s .  c o  m
 */
private void signData(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException {
    try {
        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut));
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

        sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> users = publicKey.getUserIDs();
        if (users.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, users.next());
            sGen.setHashedSubpackets(spGen.generate());
        }

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

        OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile);

        FileInputStream fIn = new FileInputStream(inFile);

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

        fIn.close();

        // close() finishes the writing of the literal data and flushes the stream
        // It does not close bOut so this is ok here
        lGen.close();

        // Generate the signature
        sGen.generate().encode(bOut);

        // Must not close bOut here
        bOut.finish();
        bOut.flush();

        cGen.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

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

License:Open Source License

public PGPSignature makeSignature(byte[] input, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

    sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> users = publicKey.getUserIDs();
    if (users.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, users.next());
        sGen.setHashedSubpackets(spGen.generate());
    }/*from   w w  w .ja va 2 s. c o m*/

    for (byte b : input) {
        sGen.update(b);
    }

    return sGen.generate();
}

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

License:Apache License

/**
 * PGP sign a stream./*w  ww.  j  a v  a2s. c  o 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.verhas.licensor.License.java

License:Open Source License

/**
 * Encode the currently loaded/created license.
 * //w  w w . jav a2s.  c  o m
 * @param keyPassPhraseString
 *            the pass phrase to the signing key that was loaded.
 * @return the license encoded as ascii string.
 * @throws java.io.IOException
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.NoSuchProviderException
 * @throws org.bouncycastle.openpgp.PGPException
 * @throws java.security.SignatureException
 */
public String encodeLicense(final String keyPassPhraseString) throws IOException, NoSuchAlgorithmException,
        NoSuchProviderException, PGPException, SignatureException {

    final char[] keyPassPhrase = keyPassPhraseString.toCharArray();
    final String licensePlain = getLicenseString();
    final ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    final OutputStream out = new ArmoredOutputStream(baOut);

    final PGPPrivateKey pgpPrivKey = key.extractPrivateKey(keyPassPhrase, "BC");
    final PGPSignatureGenerator sGen = new PGPSignatureGenerator(key.getPublicKey().getAlgorithm(),
            hashAlgorithm, "BC");

    sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

    @SuppressWarnings("unchecked")
    final Iterator<String> it = key.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

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

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

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

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

    final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
    final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "licenseFileName-Ignored", new Date(),
            new byte[1024]);
    final InputStream fIn = new ByteArrayInputStream(licensePlain.getBytes("utf-8"));
    int ch = 0;
    while ((ch = fIn.read()) >= 0) {
        lOut.write(ch);
        sGen.update((byte) ch);
    }
    lGen.close();
    sGen.generate().encode(bOut);
    cGen.close();
    out.close();
    return new String(baOut.toByteArray());
}

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 {//  w w w. j  a v a  2s  .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:de.softwareforge.pgpsigner.commands.SignCommand.java

License:Apache License

@Override
public void executeInteractiveCommand(final String[] args) {

    PGPSignatureGenerator signatureGenerator = null;

    SecretKey signKey = getContext().getSignKey();
    PGPPublicKey pubKey = signKey.getPGPPublicKey();

    try {/*www  .  j  a v  a2  s  . c om*/
        signatureGenerator = new PGPSignatureGenerator(pubKey.getAlgorithm(), PGPUtil.SHA1, "BC");
        signatureGenerator.initSign(PGPSignature.DEFAULT_CERTIFICATION, signKey.getPGPPrivateKey());

        PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
        for (Iterator it = pubKey.getUserIDs(); it.hasNext();) {
            subpacketGenerator.setSignerUserID(false, (String) it.next());
            signatureGenerator.setHashedSubpackets(subpacketGenerator.generate());
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        System.out.println("Could not generate signature for signing.");
        return;
    }

    for (PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) {

        if (!key.isSigned()) {
            try {
                PGPPublicKey newKey = key.getPGPPublicKey();
                PGPSignature signature = signatureGenerator.generateCertification(newKey);

                for (Iterator it = key.getUserIds(); it.hasNext();) {
                    String userId = (String) it.next();
                    newKey = PGPPublicKey.addCertification(newKey, userId, signature);
                }

                key.setPGPPublicKey(newKey);
                key.setSigned(true);
                System.out.println("Signed Key " + key.getKeyId() + " with " + signKey.getKeyId());

            } catch (RuntimeException re) {
                throw re;
            } catch (Exception e) {
                System.out.println("Could not sign key " + DisplayHelpers.showKey(key) + ", skipping.");
            }
        }
    }
}

From source file:eu.mrbussy.security.crypto.pgp.PGPEncryptor.java

License:Open Source License

public void encryptFile(File inputFile, File outputFile)
        throws IOException, NoSuchProviderException, PGPException {
    if (pedg == null) {
        pedg = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, checkIntegrity, new SecureRandom(), "BC");

        try {/*  ww  w .j  av  a2  s  . co m*/
            pedg.addMethod(publicKey);
        } catch (PGPException e) {
            throw new PGPException("Error when creating PGP encryptino data generator.");
        }
    }
    OutputStream fileOutStream = new FileOutputStream(outputFile);
    if (isArmored) {
        fileOutStream = new ArmoredOutputStream(fileOutStream);
    }

    OutputStream encryptdOutStream = pedg.open(fileOutStream, new byte[1 << 16]);
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOutStream = comData.open(encryptdOutStream);

    try {
        PGPSignatureGenerator sg = null;
        if (isSigning) {
            InputStream keyInputStream = new FileInputStream(new File(signingPrivateKeyFilePath));
            PGPSecretKey secretKey = PGPUtils.findSecretKey(keyInputStream);
            PGPPrivateKey privateKey = secretKey.extractPrivateKey(signingPrivateKeyPassword.toCharArray(),
                    "BC");
            sg = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
            sg.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);
            Iterator it = secretKey.getPublicKey().getUserIDs();
            if (it.hasNext()) {
                PGPSignatureSubpacketGenerator ssg = new PGPSignatureSubpacketGenerator();
                ssg.setSignerUserID(false, (String) it.next());
                sg.setHashedSubpackets(ssg.generate());
            }
            sg.generateOnePassVersion(false).encode(compressedOutStream);
        }

        PGPLiteralDataGenerator lg = new PGPLiteralDataGenerator();
        OutputStream literalDataOutStream = lg.open(compressedOutStream, PGPLiteralData.BINARY, inputFile);

        byte[] bytes = IOUtils.toByteArray(new FileInputStream(inputFile));

        literalDataOutStream.write(bytes);
        if (isSigning) {
            sg.update(bytes);
            sg.generate().encode(compressedOutStream);
        }
        literalDataOutStream.close();
        lg.close();
        compressedOutStream.close();
        comData.close();
        pedg.close();
        fileOutStream.close();
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.ivy.plugins.signer.bouncycastle.OpenPGPSignatureGenerator.java

License:Apache License

public void sign(File src, File dest) throws IOException {
    OutputStream out = null;//from   w ww .  j a v a 2  s  .  com
    InputStream in = null;
    InputStream keyIn = null;

    try {
        if (secring == null) {
            secring = System.getProperty("user.home") + "/.gnupg/secring.gpg";
        }

        if (pgpSec == null) {
            keyIn = new FileInputStream(secring);
            pgpSec = readSecretKey(keyIn);
        }

        PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(password.toCharArray(),
                BouncyCastleProvider.PROVIDER_NAME);
        PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSec.getPublicKey().getAlgorithm(),
                PGPUtil.SHA1, BouncyCastleProvider.PROVIDER_NAME);
        sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

        in = new FileInputStream(src);
        out = new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream(dest)));

        int ch = 0;
        while ((ch = in.read()) >= 0) {
            sGen.update((byte) ch);
        }

        sGen.generate().encode(out);
    } catch (SignatureException e) {
        IOException ioexc = new IOException();
        ioexc.initCause(e);
        throw ioexc;
    } catch (PGPException e) {
        IOException ioexc = new IOException();
        ioexc.initCause(e);
        throw ioexc;
    } catch (NoSuchAlgorithmException e) {
        IOException ioexc = new IOException();
        ioexc.initCause(e);
        throw ioexc;
    } catch (NoSuchProviderException e) {
        IOException ioexc = new IOException();
        ioexc.initCause(e);
        throw ioexc;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (keyIn != null) {
            try {
                keyIn.close();
            } catch (IOException e) {
            }
        }
    }
}

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

@Override
public String signAndEncrypt(String message) throws IOException {

    try {/*from   w w w  .  j a  v  a2s .com*/
        /* Final < Armored < Crypted < Clear PGP */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ArmoredOutputStream armoredOutput = new ArmoredOutputStream(out);
        PGPEncryptedDataGenerator crypter = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.S2K_SHA1,
                new SecureRandom(), _provider);
        crypter.addMethod(getRemotePublicKey());
        BCPGOutputStream pgpOut = new BCPGOutputStream(crypter.open(armoredOutput, new byte[512]));

        /* Prepare for signing */
        PGPSignatureGenerator signer = new PGPSignatureGenerator(getSigningPublicKey().getAlgorithm(),
                PGPUtil.SHA1, _provider);
        signer.initSign(PGPSignature.BINARY_DOCUMENT, getSigningPrivateKey());

        /* Output the standard header */
        signer.generateOnePassVersion(false).encode(pgpOut);

        /* Output the literal data */
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(true);
        literalDataGenerator.open(pgpOut, 'b', "bar", message.getBytes().length, new Date())
                .write(message.getBytes());

        /* Calculate signature and output it */
        signer.update(message.getBytes());
        signer.generate().encode(pgpOut);

        pgpOut.close();
        armoredOutput.close();
        out.close();

        byte[] result = out.toByteArray();

        // brain dead UMAPI adds an extra base64 encoding on top of the ASCII armored string. Go figure.
        return new String(Base64.encode(result));

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

    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
        throw new IOException("Missing algorithm. Are you running a compatible JVM/Bouncycastle version?",
                noSuchAlgorithmException);

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

    } catch (NoSuchProviderException noSuchProviderException) {
        throw new IOException("Missing provider. Are you running a compatible JVM/Bouncycastle version?",
                noSuchProviderException);

    }

}

From source file:org.vafer.jdeb.signing.SigningUtils.java

License:Apache License

/**
 * Create a clear sign signature over the input data. (Not detached)
 *
 * @param pInput//www . j av  a2s.  co  m
 * @param pKeyring
 * @param pKey
 * @param pPassphrase
 * @param pOutput
 * @throws IOException
 * @throws PGPException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 */
public static void clearSign(final InputStream pInput, final InputStream pKeyring, final String pKey,
        final String pPassphrase, final OutputStream pOutput) throws IOException, PGPException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException {

    Security.addProvider(new BouncyCastleProvider());

    final PGPSecretKey secretKey = getSecretKey(pKeyring, pKey);
    final PGPPrivateKey privateKey = secretKey.extractPrivateKey(pPassphrase.toCharArray(), "BC");

    final int digest = PGPUtil.SHA1;

    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            secretKey.getPublicKey().getAlgorithm(), digest, "BC");
    signatureGenerator.initSign(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);

    //        final PGPSignatureSubpacketGenerator subpackageGenerator = new PGPSignatureSubpacketGenerator();
    //
    //        final Iterator it = secretKey.getPublicKey().getUserIDs();
    //        if (it.hasNext()) {
    //            subpackageGenerator.setSignerUserID(false, (String)it.next());
    //            signatureGenerator.setHashedSubpackets(subpackageGenerator.generate());
    //        }

    final ArmoredOutputStream armoredOutput = new ArmoredOutputStream(pOutput);

    armoredOutput.beginClearText(digest);

    final BufferedReader reader = new BufferedReader(new InputStreamReader(pInput));

    final byte[] newline = "\r\n".getBytes("UTF-8");

    processLine(reader.readLine(), armoredOutput, signatureGenerator);

    while (true) {
        final String line = reader.readLine();

        if (line == null) {
            armoredOutput.write(newline);
            break;
        }

        armoredOutput.write(newline);
        signatureGenerator.update(newline);

        processLine(line, armoredOutput, signatureGenerator);
    }

    armoredOutput.endClearText();

    final BCPGOutputStream pgpOutput = new BCPGOutputStream(armoredOutput);

    signatureGenerator.generate().encode(pgpOutput);

    armoredOutput.close();

}