Example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentSignerBuilder JcaPGPContentSignerBuilder

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentSignerBuilder JcaPGPContentSignerBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPContentSignerBuilder JcaPGPContentSignerBuilder.

Prototype

public JcaPGPContentSignerBuilder(int keyAlgorithm, int hashAlgorithm) 

Source Link

Usage

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

License:Open Source License

/**
 * /*from   w ww  .j  a  v  a 2  s . co m*/
 * @param dsaKeyPair - the generated DSA key pair
 * @param elGamalKeyPair - the generated El Gamal key pair
 * @param identity - the given identity of the key pair ring
 * @param passphrase - the secret pass phrase to protect the key pair
 * @return a PGP Key Ring Generate with the El Gamal key pair added as sub key
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static final PGPKeyRingGenerator createPGPKeyRingGeneratorForDSAKeyPair(KeyPair dsaKeyPair,
        KeyPair elGamalKeyPair, String identity, char[] passphrase) throws Exception {
    PGPKeyPair dsaPgpKeyPair = new PGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date());
    PGPKeyPair elGamalPgpKeyPair = new PGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elGamalKeyPair, new Date());
    PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
            .get(HashAlgorithmTags.SHA1);
    PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaPgpKeyPair,
            identity, sha1Calc, null, null,
            new JcaPGPContentSignerBuilder(dsaPgpKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
            new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc).setProvider("BC")
                    .build(passphrase));

    keyRingGen.addSubKey(elGamalPgpKeyPair);
    return keyRingGen;
}

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

License:Open Source License

/**
 * /*from  ww  w .  ja  va 2  s  . c  o  m*/
 * @param signKeyPair - the generated signing RSA key pair
 * @param encryptKeyPair - the generated encrypting RSA key pair
 * @param identity - the given identity of the key pair ring
 * @param passphrase - the secret pass phrase to protect the key pair
 * @return a PGP Key Ring Generate with the RSA key pair added as sub key
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static final PGPKeyRingGenerator createPGPKeyRingGeneratorForRSAKeyPair(KeyPair signKeyPair,
        KeyPair encryptKeyPair, String identity, char[] passphrase) throws Exception {
    PGPKeyPair signPgpKeyPair = new PGPKeyPair(PGPPublicKey.RSA_SIGN, signKeyPair, new Date());
    PGPKeyPair encryptPgpKeyPair = new PGPKeyPair(PGPPublicKey.RSA_ENCRYPT, encryptKeyPair, new Date());
    PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
            .get(HashAlgorithmTags.SHA1);
    PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
            signPgpKeyPair, identity, sha1Calc, null, null,
            new JcaPGPContentSignerBuilder(signPgpKeyPair.getPublicKey().getAlgorithm(),
                    HashAlgorithmTags.SHA1),
            new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc).setProvider("BC")
                    .build(passphrase));

    keyRingGen.addSubKey(encryptPgpKeyPair);
    return keyRingGen;
}

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;//from ww  w.  j  a v  a 2  s.c  om
    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.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   www.j a va 2  s.  c om*/
 * @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   ww w  .j  a  v  a 2  s.co 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;/*  w  w w .  ja  v  a 2s.  c  o  m*/
    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:crypttools.PGPTools.java

License:Open Source License

/**
 * /*  w  w w . j a v  a2s .c o m*/
 * @param dsaKeyPair - the generated DSA key pair
 * @param elGamalKeyPair - the generated El Gamal key pair
 * @param identity - the given identity of the key pair ring
 * @param passphrase - the secret pass phrase to protect the key pair
 * @return a PGP Key Ring Generate with the El Gamal key pair added as sub key
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static final PGPKeyRingGenerator createPGPKeyRingGenerator(KeyPair dsaKeyPair, KeyPair elGamalKeyPair,
        String identity, char[] passphrase) throws Exception {
    PGPKeyPair dsaPgpKeyPair = new PGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date());
    PGPKeyPair elGamalPgpKeyPair = new PGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elGamalKeyPair, new Date());
    PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
            .get(HashAlgorithmTags.SHA1);

    PGPContentSignerBuilder pgpCSB = new JcaPGPContentSignerBuilder(dsaPgpKeyPair.getPublicKey().getAlgorithm(),
            HashAlgorithmTags.SHA1);
    PBESecretKeyEncryptor pbeSKE = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc)
            .setProvider("BC").build(passphrase);

    PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, dsaPgpKeyPair,
            identity, sha1Calc, null, null, pgpCSB, pbeSKE);

    keyRingGen.addSubKey(elGamalPgpKeyPair);
    return keyRingGen;
}

From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java

License:Open Source License

public byte[] signInline(String input) throws IOException, PGPException {
    PGPSecretKey signKey = readSecretKey();
    PGPPrivateKey privKey = signKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
    PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256)
                    .setProvider("BC"));
    sigGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privKey);

    @SuppressWarnings("unchecked")
    Iterator<String> userIds = signKey.getUserIDs();
    if (userIds.hasNext()) {
        PGPSignatureSubpacketGenerator sigSubpacketGenerator = new PGPSignatureSubpacketGenerator();
        sigSubpacketGenerator.setSignerUserID(false, userIds.next());
        sigGenerator.setHashedSubpackets(sigSubpacketGenerator.generate());
    }/*  ww w  .  j a  v a 2  s. co m*/

    String[] lines = input.split("\r?\n");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
        aOut.beginClearText(PGPUtil.SHA256);

        boolean firstLine = true;
        for (String line : lines) {
            String sigLine = (firstLine ? "" : "\r\n") + line.replaceAll("\\s*$", "");
            sigGenerator.update(sigLine.getBytes(Charsets.UTF_8));
            aOut.write((line + "\n").getBytes(Charsets.UTF_8));
            firstLine = false;
        }
        aOut.endClearText();

        BCPGOutputStream bOut = new BCPGOutputStream(aOut);
        sigGenerator.generate().encode(bOut);
    }
    return buffer.toByteArray();
}

From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java

License:Open Source License

public byte[] signExternal(String input) throws IOException, PGPException {
    PGPSecretKey signKey = readSecretKey();
    PGPPrivateKey privKey = signKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(config.passphrase.toCharArray()));
    PGPSignatureGenerator sigGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(signKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256)
                    .setProvider("BC"));
    sigGenerator.init(PGPSignature.BINARY_DOCUMENT, privKey);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    try (ArmoredOutputStream aOut = new ArmoredOutputStream(buffer)) {
        BCPGOutputStream bOut = new BCPGOutputStream(aOut);
        sigGenerator.update(input.getBytes(Charsets.UTF_8));
        sigGenerator.generate().encode(bOut);
    }//  w w  w .  j av a2 s .com

    return buffer.toByteArray();
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

License:Apache License

protected PGPSignatureGenerator createSignatureGenerator(Exchange exchange, OutputStream out)
        throws IOException, PGPException, NoSuchProviderException, NoSuchAlgorithmException {

    String sigKeyFileName = findSignatureKeyFileName(exchange);
    String sigKeyUserid = findSignatureKeyUserid(exchange);
    String sigKeyPassword = findSignatureKeyPassword(exchange);
    byte[] sigKeyRing = findSignatureKeyRing(exchange);

    if ((sigKeyFileName == null && sigKeyRing == null) || sigKeyUserid == null || sigKeyPassword == null) {
        return null;
    }/*from   w ww.j  av  a 2s . co m*/

    PGPSecretKey sigSecretKey = PGPDataFormatUtil.findSecretKey(exchange.getContext(), sigKeyFileName,
            sigKeyRing, sigKeyPassword, sigKeyUserid, getProvider());
    if (sigSecretKey == null) {
        throw new IllegalArgumentException(String.format(
                "Cannot PGP encrypt message. No secret key found for User ID %s. Either add a key with this User ID to the secret keyring or change the configured User ID.",
                sigKeyUserid));
    }

    PGPPrivateKey sigPrivateKey = sigSecretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder()
            .setProvider(getProvider()).build(sigKeyPassword.toCharArray()));
    if (sigPrivateKey == null) {
        // this exception will never happen
        throw new IllegalArgumentException("Signature private key is null, cannot proceed");
    }

    PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
    spGen.setSignerUserID(false, sigKeyUserid);

    int algorithm = sigSecretKey.getPublicKey().getAlgorithm();
    PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(algorithm, findHashAlgorithm(exchange)).setProvider(getProvider()));
    sigGen.init(PGPSignature.BINARY_DOCUMENT, sigPrivateKey);
    sigGen.setHashedSubpackets(spGen.generate());
    sigGen.generateOnePassVersion(false).encode(out);
    return sigGen;
}