Example usage for org.bouncycastle.openpgp PGPSignatureGenerator PGPSignatureGenerator

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

Introduction

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

Prototype

public PGPSignatureGenerator(PGPContentSignerBuilder contentSignerBuilder) 

Source Link

Document

Create a signature generator built on the passed in contentSignerBuilder.

Usage

From source file:org.eclipse.packagedrone.utils.rpm.signature.RsaHeaderSignatureProcessor.java

License:Open Source License

@Override
public void feedHeader(final ByteBuffer header) {
    try {//from  www  . j av  a 2  s . c  o  m
        final BcPGPContentSignerBuilder contentSignerBuilder = new BcPGPContentSignerBuilder(
                this.privateKey.getPublicKeyPacket().getAlgorithm(), this.hashAlgorithm);
        final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder);

        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, this.privateKey);

        if (header.hasArray()) {
            signatureGenerator.update(header.array(), header.position(), header.remaining());
        } else {
            final byte[] buffer = new byte[header.remaining()];
            header.get(buffer);
            signatureGenerator.update(buffer);
        }

        this.value = signatureGenerator.generate().getEncoded();
        logger.info("RSA HEADER: {}", this.value);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.packagedrone.utils.security.pgp.SigningStream.java

License:Open Source License

protected void testInit() throws IOException {
    if (this.initialized) {
        return;/*from w ww.  j a v a2 s .c  o  m*/
    }

    this.initialized = true;

    try {
        this.signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(
                this.privateKey.getPublicKeyPacket().getAlgorithm(), this.digestAlgorithm));
        this.signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, this.privateKey);

        this.armoredOutput = new ArmoredOutputStream(this.stream);
        if (this.version != null) {
            this.armoredOutput.setHeader("Version", this.version);
        }

        if (this.inline) {
            this.armoredOutput.beginClearText(this.digestAlgorithm);
        }
    } catch (final PGPException e) {
        throw new IOException(e);
    }
}

From source file:org.elasticsearch.plugins.InstallPluginCommandTests.java

License:Apache License

private String signature(final byte[] bytes, final PGPSecretKey secretKey) {
    try {/*from  ww  w.  j  av a2 s . com*/
        final PGPPrivateKey privateKey = secretKey.extractPrivateKey(
                new BcPBESecretKeyDecryptorBuilder(new JcaPGPDigestCalculatorProviderBuilder().build())
                        .build("passphrase".toCharArray()));
        final PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(
                privateKey.getPublicKeyPacket().getAlgorithm(), HashAlgorithmTags.SHA512));
        generator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        try (BCPGOutputStream pout = new BCPGOutputStream(new ArmoredOutputStream(output));
                InputStream is = new ByteArrayInputStream(bytes)) {
            final byte[] buffer = new byte[1024];
            int read;
            while ((read = is.read(buffer)) != -1) {
                generator.update(buffer, 0, read);
            }
            generator.generate().encode(pout);
        }
        return new String(output.toByteArray(), "UTF-8");
    } catch (IOException | PGPException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.gradle.plugins.signing.signatory.pgp.PgpSignatory.java

License:Apache License

public PGPSignatureGenerator createSignatureGenerator() {
    try {//from ww w . j  a  va  2  s. com
        PGPSignatureGenerator generator = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
        generator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
        return generator;
    } catch (PGPException e) {
        throw new UncheckedException(e);
    }
}

From source file:org.kontalk.certgen.PGP.java

License:Open Source License

/** Signs a public key with the given secret key. */
public static PGPPublicKey signPublicKey(PGPKeyPair secret, PGPPublicKey keyToBeSigned, String id,
        int certification) throws PGPException, IOException, SignatureException {

    PGPPrivateKey pgpPrivKey = secret.getPrivateKey();

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(secret.getPublicKey().getAlgorithm(), PGPUtil.SHA512)
                    .setProvider(PROVIDER));

    sGen.init(certification, pgpPrivKey);

    return PGPPublicKey.addCertification(keyToBeSigned, id, sGen.generateCertification(id, keyToBeSigned));
}

From source file:org.kontalk.certgen.PGP.java

License:Open Source License

/** Signs and add the given user attributes to the given public key. */
public static PGPPublicKey signUserAttributes(PGPKeyPair secret, PGPPublicKey keyToBeSigned,
        PGPUserAttributeSubpacketVector attributes, int certification) throws PGPException, SignatureException {

    PGPPrivateKey pgpPrivKey = secret.getPrivateKey();

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(secret.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider(PROVIDER));

    sGen.init(certification, pgpPrivKey);

    return PGPPublicKey.addCertification(keyToBeSigned, attributes,
            sGen.generateCertification(attributes, keyToBeSigned));
}

From source file:org.kontalk.certgen.PGP.java

License:Open Source License

/** Revokes the given key. */
public static PGPPublicKey revokeKey(PGPKeyPair secret) throws PGPException, IOException, SignatureException {

    PGPPrivateKey pgpPrivKey = secret.getPrivateKey();
    PGPPublicKey pgpPubKey = secret.getPublicKey();

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(secret.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider(PROVIDER));

    sGen.init(PGPSignature.KEY_REVOCATION, pgpPrivKey);

    return PGPPublicKey.addCertification(pgpPubKey, sGen.generateCertification(pgpPubKey));
}

From source file:org.kontalk.crypto.Coder.java

License:Open Source License

/**
 * Creates encrypted and signed message body.
 * Errors that may occur are saved to the message.
 * @param message//from w  w w.jav a 2  s . c om
 * @return the encrypted and signed text.
 */
public static Optional<byte[]> processOutMessage(OutMessage message) {
    if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) {
        LOGGER.warning("message does not want to be encrypted");
        return Optional.empty();
    }

    LOGGER.info("encrypting message...");

    // get keys
    KeysResult keys = getKeys(message.getUser());
    if (keys.myKey == null || keys.otherKey == null) {
        message.setSecurityErrors(keys.errors);
        return Optional.empty();
    }

    // secure the message against the most basic attacks using Message/CPIM
    String from = keys.myKey.getUserId();
    String to = keys.otherKey.userID + "; ";
    String mime = "text/plain";
    // TODO encrypt more possible content
    String text = message.getContent().getPlainText();
    CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text);
    byte[] plainText;
    try {
        plainText = cpim.toByteArray();
    } catch (UnsupportedEncodingException ex) {
        LOGGER.log(Level.WARNING, "UTF-8 not supported", ex);
        plainText = cpim.toString().getBytes();
    }

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    //for (PGPPublicKey rcpt : mRecipients)
    encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(plainText);
    try { // catch all io and pgp exceptions

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

        // setup compressed data generator
        PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

        // setup signature generator
        int algo = keys.myKey.getPublicEncryptionKey().getAlgorithm();
        PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1));
        sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey());

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, keys.myKey.getUserId());
        sigGen.setUnhashedSubpackets(spGen.generate());

        sigGen.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalGen.open(compressedOut, PGPLiteralData.BINARY, "", new Date(),
                new byte[BUFFER_SIZE]);

        // read the "in" stream, compress, encrypt and write to the "out" stream
        // this must be done if clear data is bigger than the buffer size
        // but there are other ways to optimize...
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            try {
                sigGen.update(buf, 0, len);
            } catch (SignatureException ex) {
                LOGGER.log(Level.WARNING, "can't read data for signature", ex);
                message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
                return Optional.empty();
            }
        }

        in.close();
        literalGen.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        try {
            sigGen.generate().encode(compressedOut);
        } catch (SignatureException ex) {
            LOGGER.log(Level.WARNING, "can't create signature", ex);
            message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
            return Optional.empty();
        }
        compGen.close();
        encGen.close();

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't encrypt message", ex);
        message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR));
        return Optional.empty();
    }

    LOGGER.info("encryption successful");
    return Optional.of(out.toByteArray());
}

From source file:org.m1theo.apt.repo.signing.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  ww.ja  va2 s.  c  o m
public void clearSign(InputStream input, OutputStream output)
        throws IOException, PGPException, GeneralSecurityException {

    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);

    LineIterator iterator = new LineIterator(new InputStreamReader(input));

    while (iterator.hasNext()) {
        String line = iterator.nextLine();

        // 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);
        if (iterator.hasNext()) {
            signatureGenerator.update(EOL);
        }
    }

    armoredOutput.endClearText();

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

    armoredOutput.close();
}

From source file:org.m1theo.apt.repo.signing.PGPSigner.java

License:Apache License

/**
 * Creates a detached clear sign signature over the input data.
 *
 * @param input      the content to be signed
 * @param output     the output destination of the signature
 *//*from  ww  w. j  av  a2 s .  co m*/
public void clearSignDetached(InputStream input, OutputStream output)
        throws IOException, PGPException, GeneralSecurityException {

    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey);

    ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output);

    LineIterator iterator = new LineIterator(new InputStreamReader(input));

    while (iterator.hasNext()) {
        String line = iterator.nextLine();

        // 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");

        signatureGenerator.update(data);
        if (iterator.hasNext()) {
            signatureGenerator.update(EOL);
        }
    }

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

    armoredOutput.close();
}