Example usage for org.bouncycastle.openpgp PGPSignatureGenerator init

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

Introduction

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

Prototype

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

Source Link

Document

Initialise the generator for signing.

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  w  ww. j av  a2  s . c  om*/
        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  w w. ja v 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.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  ww  w  .j a v  a 2s  . co  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.KeyRing.java

License:BEER-WARE LICENSE

public void signEncryptMessage(InputStream in, OutputStream out, String jid)
        throws IOException, PGPException, SignatureException {
    out = new ArmoredOutputStream(out);

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SYMM_ALG)
            .setWithIntegrityPacket(true).setSecureRandom(rand).setProvider(PROVIDER));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(keys.get(jid)).setProvider(PROVIDER));

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

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(kp.getPrivateKey().getPublicKeyPacket().getAlgorithm(), HASH_ALG)
                    .setProvider(PROVIDER));
    sGen.init(PGPSignature.BINARY_DOCUMENT, kp.getPrivateKey());
    sGen.generateOnePassVersion(false).encode(compressedData);

    OutputStream finalOut = new PGPLiteralDataGenerator().open(compressedData, PGPLiteralData.BINARY, "",
            new Date(), new byte[BUFFER_SIZE]);

    byte[] buf = new byte[BUFFER_SIZE];
    int len;/*  w ww  . ja  v  a 2 s  .  c o m*/
    while ((len = in.read(buf)) > 0) {
        finalOut.write(buf, 0, len);
        sGen.update(buf, 0, len);
    }

    in.close();

    finalOut.close();
    sGen.generate().encode(compressedData);
    compressedData.close();
    encryptedOut.close();
    out.close();
}

From source file:com.google.gerrit.gpg.PushCertificateCheckerTest.java

License:Apache License

private PushCertificate newSignedCert(String nonce, TestKey signingKey) throws Exception {
    PushCertificateIdent ident = new PushCertificateIdent(signingKey.getFirstUserId(),
            System.currentTimeMillis(), -7 * 60);
    String payload = "certificate version 0.1\n" + "pusher " + ident.getRaw() + "\n"
            + "pushee test://localhost/repo.git\n" + "nonce " + nonce + "\n" + "\n"
            + "0000000000000000000000000000000000000000" + " deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
            + " refs/heads/master\n";
    PGPSignatureGenerator gen = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(signingKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
    gen.init(PGPSignature.BINARY_DOCUMENT, signingKey.getPrivateKey());
    gen.update(payload.getBytes(UTF_8));
    PGPSignature sig = gen.generate();//from ww  w .  j a v  a  2s.  c  o m

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try (BCPGOutputStream out = new BCPGOutputStream(new ArmoredOutputStream(bout))) {
        sig.encode(out);
    }

    String cert = payload + new String(bout.toByteArray(), UTF_8);
    Reader reader = new InputStreamReader(new ByteArrayInputStream(cert.getBytes(UTF_8)));
    PushCertificateParser parser = new PushCertificateParser(tr.getRepository(), signedPushConfig);
    return parser.parse(reader);
}

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  .ja va  2s.co  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 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());
    }//from  w  w w .  ja  v a2 s  . c  o m
    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");
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public String signDataDetached(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);

    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = new ArmoredOutputStream(byteOutputStream);
    BCPGOutputStream bOut = new BCPGOutputStream(outputStream);

    InputStream fIn = IOUtils.toInputStream(data, "UTF-8");
    int ch;//from   www. j a va 2  s. com
    while ((ch = fIn.read()) >= 0) {
        signatureGenerator.update((byte) ch);
    }

    fIn.close();

    signatureGenerator.generate().encode(bOut);

    outputStream.close();
    keyInputStream.close();

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

From source file:de.dentrassi.pm.signing.pgp.internal.PgpSigningService.java

License:Open Source License

@Override
public void sign(final InputStream in, final OutputStream out, final boolean inline) throws Exception {
    final int digest = HashAlgorithmTags.SHA1;
    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(this.privateKey.getPublicKeyPacket().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, this.privateKey);

    final ArmoredOutputStream armoredOutput = new ArmoredOutputStream(out);

    if (inline) {
        armoredOutput.beginClearText(digest);
    }//from  w  w w. j  av a2 s  .  c o m

    final byte[] buffer = new byte[4096];

    int rc;
    while ((rc = in.read(buffer)) >= 0) {
        if (inline) {
            armoredOutput.write(buffer, 0, rc);
        }
        signatureGenerator.update(buffer, 0, rc);
    }

    armoredOutput.endClearText();

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

    armoredOutput.close();
}

From source file:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Creates the signature that will be used to PGP sign data
 *
 * @param secretKeys//from ww  w. j  a va2s  .  com
 *                 these are the secret keys
 * @param password
 *                 this is the password to unlock the secret key
 *
 * @return the signature used to sign data
 *
 * @throws PGPException
 */
private static PGPSignatureGenerator createSignature(List<PGPSecretKey> secretKeys, char[] password,
        int signatureType, boolean generateUserIdSubPacket) throws PGPException {

    PGPSecretKey secretKey = null;
    for (int i = 0; i < secretKeys.size(); i++) {
        secretKey = secretKeys.get(i);

        // we ONLY want the signing master key
        if (!secretKey.isSigningKey() || !secretKey.isMasterKey()) {
            secretKey = null;
        }
    }

    if (secretKey == null) {
        throw new PGPException("Secret key is not the signing master key");
    }

    //            System.err.println("Signing key = " + tmpKey.isSigningKey() +", Master key = " + tmpKey.isMasterKey() + ", UserId = " +
    //                               userId );

    if (password == null) {
        password = new char[0];
    }

    PBESecretKeyDecryptor build = new BcPBESecretKeyDecryptorBuilder(digestCalculatorProvider).build(password);

    SecureRandom random = new SecureRandom();
    BcPGPContentSignerBuilder bcPGPContentSignerBuilder = new BcPGPContentSignerBuilder(
            secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setSecureRandom(random);

    PGPSignatureGenerator signature = new PGPSignatureGenerator(bcPGPContentSignerBuilder);
    signature.init(signatureType, secretKey.extractPrivateKey(build));

    Iterator userIds = secretKey.getPublicKey().getUserIDs();

    // use the first userId that matches
    if (userIds.hasNext()) {
        if (generateUserIdSubPacket) {
            PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
            subpacketGenerator.setSignerUserID(false, (String) userIds.next());
            signature.setHashedSubpackets(subpacketGenerator.generate());
        } else {
            signature.setHashedSubpackets(null);
        }

        return signature;
    } else {
        throw new PGPException("Did not find specified userId");
    }
}