Example usage for org.bouncycastle.openpgp PGPSignatureGenerator update

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

Introduction

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

Prototype

public void update(byte[] b) throws PGPSignatureException 

Source Link

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 {//w  w  w  . j  a  va2  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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Sign the passed in message stream//from   ww  w .j  a v 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  v a  2s .  c  om

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

    return sGen.generate();
}

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 a v  a2 s.  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.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  w w  w .j a va 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.verhas.licensor.License.java

License:Open Source License

/**
 * Encode the currently loaded/created license.
 * //from  w  ww.jav  a  2s  . co  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: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.  j  av  a 2s.  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");
}

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  w w  w .j  a  v  a  2  s  .  c om
    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: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 {// w  w w  .jav  a 2s .  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:exchange.User.java

public String addSignature(String message) throws PGPException, SignatureException, IOException {
    message = (message.endsWith("#")) ? message.substring(0, message.length() - 1) : message;
    PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(keyAlgorithm, PGPUtil.SHA256));

    sigGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);
    sigGen.update(message.getBytes());
    PGPSignature signature = sigGen.generate();
    System.out.println(message);/*from  w  w w .  j  a  va  2  s  .c o m*/
    return message + msgDelimiter + DatatypeConverter.printBase64Binary(signature.getEncoded());
}