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.vafer.jdeb.DebMaker.java

License:Apache License

public void makeDeb() throws PackagingException {
    BinaryPackageControlFile packageControlFile;
    try {/*from w  w w. j a va2s . c  om*/
        console.info("Creating debian package: " + deb);

        // If we should sign the package
        boolean doSign = signPackage;

        if (doSign) {

            if (keyring == null || !keyring.exists()) {
                doSign = false;
                console.warn("Signing requested, but no keyring supplied");
            }

            if (key == null) {
                doSign = false;
                console.warn("Signing requested, but no key supplied");
            }

            if (passphrase == null) {
                doSign = false;
                console.warn("Signing requested, but no passphrase supplied");
            }

            FileInputStream keyRingInput = new FileInputStream(keyring);
            PGPSigner signer = null;
            try {
                signer = new PGPSigner(new FileInputStream(keyring), key, passphrase);
            } finally {
                keyRingInput.close();
            }

            int digest = PGPUtil.SHA1;

            PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                    new BcPGPContentSignerBuilder(signer.getSecretKey().getPublicKey().getAlgorithm(), digest));
            signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, signer.getPrivateKey());

            packageControlFile = createSignedDeb(Compression.toEnum(compression), signatureGenerator, signer);
        } else {
            packageControlFile = createDeb(Compression.toEnum(compression));
        }

    } catch (Exception e) {
        throw new PackagingException("Failed to create debian package " + deb, e);
    }

    makeChangesFiles(packageControlFile);
}

From source file:org.vafer.jdeb.maven.DebMaker.java

License:Apache License

public void makeDeb() throws PackagingException {

    if (control == null || !control.isDirectory()) {
        throw new PackagingException("\"" + control + "\" is not a valid 'control' directory)");
    }//from   w w  w.  j a  va  2s  . c o  m

    if (changesIn != null) {

        if (!changesIn.isFile() || !changesIn.canRead()) {
            throw new PackagingException("The 'changesIn' setting needs to point to a readable file. "
                    + changesIn + " was not found/readable.");
        }

        if (changesOut == null) {
            throw new PackagingException("A 'changesIn' without a 'changesOut' does not make much sense.");
        }

        if (!isPossibleOutput(changesOut)) {
            throw new PackagingException("Cannot write the output for 'changesOut' to " + changesOut);
        }

        if (changesSave != null && !isPossibleOutput(changesSave)) {
            throw new PackagingException("Cannot write the output for 'changesSave' to " + changesSave);
        }

    } else {
        if (changesOut != null || changesSave != null) {
            throw new PackagingException(
                    "The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.");
        }
    }

    if (!"gzip".equals(compression) && !"bzip2".equals(compression) && !"none".equals(compression)) {
        throw new PackagingException("The compression method '" + compression + "' is not supported");
    }

    if (deb == null) {
        throw new PackagingException("You need to specify where the deb file is supposed to be created.");
    }

    final File[] controlFiles = control.listFiles();

    final DataProducer[] data = new DataProducer[dataProducers.size()];
    dataProducers.toArray(data);

    final Processor processor = new Processor(console, variableResolver);

    final PackageDescriptor packageDescriptor;
    try {

        console.info("Creating debian package: " + deb);

        if (signPackage) {
            if (keyring == null || !keyring.exists()) {
                throw new PackagingException("Signing requested, but no keyring supplied");
            }

            if (key == null) {
                throw new PackagingException("Signing requested, but no key supplied");
            }

            if (passphrase == null) {
                throw new PackagingException("Signing requested, but no passphrase supplied");
            }

            FileInputStream keyRingInput = new FileInputStream(keyring);
            PGPSecretKey secretKey = null;
            try {
                secretKey = SigningUtils.getSecretKey(keyRingInput, key);
            } finally {
                keyRingInput.close();
            }

            int digest = PGPUtil.SHA1;

            PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                    new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), digest));
            signatureGenerator.init(PGPSignature.BINARY_DOCUMENT,
                    SigningUtils.getPrivateKey(secretKey, passphrase));

            packageDescriptor = processor.createSignedDeb(controlFiles, data, deb, compression,
                    signatureGenerator);
        } else {
            packageDescriptor = processor.createDeb(controlFiles, data, deb, compression);
        }

    } catch (Exception e) {
        throw new PackagingException("Failed to create debian package " + deb, e);
    }

    final TextfileChangesProvider changesProvider;

    try {
        if (changesOut == null) {
            return;
        }

        console.info("Creating changes file: " + changesOut);

        // for now only support reading the changes form a textfile provider
        changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor);

        processor.createChanges(packageDescriptor, changesProvider,
                (keyring != null) ? new FileInputStream(keyring) : null, key, passphrase,
                new FileOutputStream(changesOut));

    } catch (Exception e) {
        throw new PackagingException("Failed to create debian changes file " + changesOut, e);
    }

    try {
        if (changesSave == null) {
            return;
        }

        console.info("Saving changes to file: " + changesSave);

        changesProvider.save(new FileOutputStream(changesSave));

    } catch (Exception e) {
        throw new PackagingException("Failed to save debian changes file " + changesSave, e);
    }
}

From source file:org.vafer.jdeb.signing.DebMakerTestCase.java

License:Apache License

public void testCreation() throws Exception {

    File control = new File(getClass().getResource("../deb/control/control").toURI());
    File archive1 = new File(getClass().getResource("../deb/data.tgz").toURI());
    File archive2 = new File(getClass().getResource("../deb/data.tar.bz2").toURI());
    File archive3 = new File(getClass().getResource("../deb/data.zip").toURI());
    File directory = new File(getClass().getResource("../deb/data").toURI());

    final InputStream ring = getClass().getClassLoader().getResourceAsStream("org/vafer/gpg/secring.gpg");

    DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null),
            new DataProducerArchive(archive2, null, null, null),
            new DataProducerArchive(archive3, null, null, null),
            new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null),
            new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null,
                    null) };//  w ww. j av  a  2  s.  c om

    int digest = PGPUtil.SHA1;
    PGPSigner signer = new PGPSigner(ring, "2E074D8F", "test");
    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(signer.getSecretKey().getPublicKey().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, signer.getPrivateKey());

    for (int i = 0; i <= 1; i++) {
        File deb = File.createTempFile("jdeb", ".deb");

        DebMaker maker = new DebMaker(new NullConsole(), Arrays.asList(data), null);
        maker.setControl(new File(getClass().getResource("../deb/control").toURI()));
        maker.setDeb(deb);

        if (i == 0)
            maker.setSignMethod("debsig-verify");
        else
            maker.setSignMethod("dpkg-sig");

        BinaryPackageControlFile packageControlFile = maker.createSignedDeb(Compression.GZIP,
                signatureGenerator, signer);

        assertTrue(packageControlFile.isValid());

        final Map<String, TarArchiveEntry> filesInDeb = new HashMap<String, TarArchiveEntry>();

        ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() {
            public void visit(TarArchiveEntry entry, byte[] content) throws IOException {
                filesInDeb.put(entry.getName(), entry);
            }
        }, Compression.GZIP);

        assertTrue("_gpgorigin wasn't found in the package",
                ArchiveWalker.arArchiveContains(deb, "_gpgorigin"));
        assertTrue("debian-binary wasn't found in the package",
                ArchiveWalker.arArchiveContains(deb, "debian-binary"));
        assertTrue("control.tar.gz wasn't found in the package",
                ArchiveWalker.arArchiveContains(deb, "control.tar.gz"));
        assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile"));
        assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2"));
        assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3"));
        assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4"));
        assertTrue("/link/path-element.ext wasn't found in the package",
                filesInDeb.containsKey("./link/path-element.ext"));
        assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext",
                filesInDeb.get("./link/path-element.ext").getLinkName());

        if (i == 0) {
            FileUtils.copyFile(deb, new File("./target/test_debsig-verify.deb"));
        } else {
            FileUtils.copyFile(deb, new File("./target/test_dpkg-sig.deb"));
        }

        assertTrue("Cannot delete the file " + deb, deb.delete());
    }
}

From source file:org.vafer.jdeb.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 va 2  s .  c o  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);

    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:ubicrypt.core.crypto.PGPEC.java

License:Open Source License

public static PGPPublicKey signPK(final PGPPublicKey pk, final PGPPrivateKey priv) {
    final PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(PGPPublicKey.ECDSA, PGPUtil.SHA256).setProvider("BC"));

    try {/*from   w  w w .ja  va 2  s.c o  m*/
        sGen.init(PGPSignature.DIRECT_KEY, priv);
    } catch (final PGPException e) {
        Throwables.propagate(e);
    }

    final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

    final PGPSignatureSubpacketVector packetVector = spGen.generate();

    sGen.setHashedSubpackets(packetVector);

    try {
        return PGPPublicKey.addCertification(pk, sGen.generateCertification("id", pk));
    } catch (final PGPException e) {
        Throwables.propagate(e);
    }
    return null;
}