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:org.gradle.plugins.signing.signatory.pgp.PgpSignatory.java

License:Apache License

public PGPSignatureGenerator createSignatureGenerator() {
    try {//from   ww  w  .j  a v a2 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/*  ww w.  j a va 2 s.co m*/
 * @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
 */// w ww . j a v a 2s . co 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   www  .  j a v  a 2 s .com*/
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();
}

From source file:org.opentestsystem.delivery.testreg.transformer.GPGEncryptor.java

License:Open Source License

/**
 * Uses the Legion of the Bouncy Castle (aka BouncyCastle) PGP API to encrypt, compress, and sign the input.
 * /*from w w  w .  j a  v a2 s .co  m*/
 * The configured landing zone public key is used to encrypt the input. Only the landing zone private key will be
 * able to decrypt.
 * 
 * The configured test registration private key is used to sign the input. This can be verified by the landing zone
 * to prove that this specific test registration instance created the data.
 * 
 * @param input
 *            A byte array
 * @return A byte array comprised of a PGP/GPG compatible binary encrypted and signed output
 */
@Transformer
public Message<File> encryptStream(final File input, final @Header("dwBatchUuid") String dwBatchUuid,
        final @Header("fileSuffix") String fileSuffix, final @Header("recordsSent") int recordsSent,
        final @Header("tempPaths") List<Path> tempPaths,
        final @Header("dwConfigType") DwConfigType dwConfigType) {

    String debugPrefix = dwConfigType + " DW Config: ";

    long curTime = System.currentTimeMillis();
    File tmpEncFile;

    try {

        PGPPublicKey landingZonePubKey = findLandingZonePublicKey(dwConfigType);
        PGPSecretKey testRegSecretKey = findTestRegSecretKey();

        PGPPrivateKey testRegPrivateKey = testRegSecretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(getPassphrase()));

        // ////////////////////
        // setup encryptor

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(landingZonePubKey).setProvider("BC"));

        // This outputstream, encryptedSignedOutputStream is the ultimate target that will contain the encrypted and
        // signed output
        Path tempEncPath = Files.createTempFile(DwBatchHandler.DW_ENC_TMP_PREFIX,
                (dwConfigType == DwConfigType.SBAC ? DwBatchHandler.SBAC_DW_NAME : DwBatchHandler.LOCAL_DW_NAME)
                        + fileSuffix);
        tempPaths.add(tempEncPath);
        tmpEncFile = tempEncPath.toFile();
        FileOutputStream encryptedSignedOutputStream = new FileOutputStream(tmpEncFile);

        LOGGER.debug(debugPrefix + "Created temp encrypted output file " + tmpEncFile.getAbsolutePath());

        OutputStream encryptOutStream = encGen.open(encryptedSignedOutputStream, new byte[BUFFER_SIZE]);

        // ////////////////////////////
        // setup data compression

        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
        OutputStream compressOutStream = comData.open(encryptOutStream);

        // /////////////////////
        // sign encrypted file with test reg private key

        // create a signature generator
        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder(testRegSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                        .setProvider("BC"));
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, testRegPrivateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> it = testRegSecretKey.getPublicKey().getUserIDs();

        if (it.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, it.next());
            signatureGenerator.setHashedSubpackets(spGen.generate());
        }

        // setup signature generator to encode the contents of the compressed output stream
        signatureGenerator.generateOnePassVersion(false).encode(compressOutStream);

        // create a PGP Literal Data Generator and open it to wrap the compression output stream
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        OutputStream signedOutStream = lGen.open(compressOutStream, PGPLiteralData.BINARY, "",
                new java.util.Date(), new byte[BUFFER_SIZE]);

        // create an input stream out of the input bytes
        FileInputStream clearInputStream = new FileInputStream(input);

        // read the input and write all data to the signing output stream, also update the signature
        // generator with the same input data
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = clearInputStream.read(buf)) > 0) {
            signedOutStream.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }

        // close everything and generate the final signature
        signedOutStream.close();
        lGen.close();
        signatureGenerator.generate().encode(compressOutStream);
        compressOutStream.close();
        comData.close();
        encryptOutStream.close();
        encGen.close();
        clearInputStream.close();

        encryptedSignedOutputStream.close();

    } catch (IOException | PGPException | SignatureException e) {
        throw new GPGEncryptionException(debugPrefix + "Failure to encrypt and sign input", e);
    }

    LOGGER.debug(debugPrefix + "Generated encrypted data in " + (System.currentTimeMillis() - curTime));

    return MessageBuilder.withPayload(tmpEncFile).setHeader("dwBatchUuid", dwBatchUuid)
            .setHeader("fileSuffix", fileSuffix).setHeader("recordsSent", recordsSent)
            .setHeader("tempPaths", tempPaths).setHeader("dwConfigType", dwConfigType).build();
}

From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.java

License:Open Source License

public PGPSignatureGenerator getCertSignatureGenerator(Map<ByteBuffer, byte[]> signedHashes) {
    PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(
            PgpSecurityConstants.CERTIFY_HASH_ALGO, signedHashes);

    if (mPrivateKeyState == PRIVATE_KEY_STATE_LOCKED) {
        throw new PrivateKeyNotUnlockedException();
    }/*from  w w  w  .  j a  v  a 2  s . com*/

    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder);
    try {
        signatureGenerator.init(PGPSignature.DEFAULT_CERTIFICATION, mPrivateKey);
        return signatureGenerator;
    } catch (PGPException e) {
        Log.e(Constants.TAG, "signing error", e);
        return null;
    }
}

From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.java

License:Open Source License

public PGPSignatureGenerator getDataSignatureGenerator(int hashAlgo, boolean cleartext,
        Map<ByteBuffer, byte[]> signedHashes, Date creationTimestamp) throws PgpGeneralException {
    if (mPrivateKeyState == PRIVATE_KEY_STATE_LOCKED) {
        throw new PrivateKeyNotUnlockedException();
    }//from  w  ww.  j a  v  a  2 s.co  m

    // We explicitly create a signature creation timestamp in this place.
    // That way, we can inject an artificial one from outside, ie the one
    // used in previous runs of this function.
    if (creationTimestamp == null) {
        // to sign using nfc PgpSignEncrypt is executed two times.
        // the first time it stops to return the PendingIntent for nfc connection and signing the hash
        // the second time the signed hash is used.
        // to get the same hash we cache the timestamp for the second round!
        creationTimestamp = new Date();
    }

    PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(hashAlgo, signedHashes);

    int signatureType;
    if (cleartext) {
        // for sign-only ascii text (cleartext signature)
        signatureType = PGPSignature.CANONICAL_TEXT_DOCUMENT;
    } else {
        signatureType = PGPSignature.BINARY_DOCUMENT;
    }

    try {
        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(contentSignerBuilder);
        signatureGenerator.init(signatureType, mPrivateKey);

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, mRing.getPrimaryUserIdWithFallback());
        spGen.setSignatureCreationTime(false, creationTimestamp);
        signatureGenerator.setHashedSubpackets(spGen.generate());
        return signatureGenerator;
    } catch (PgpKeyNotFoundException | PGPException e) {
        // TODO: simply throw PGPException!
        throw new PgpGeneralException("Error initializing signature!", e);
    }
}