Example usage for org.bouncycastle.bcpg HashAlgorithmTags SHA1

List of usage examples for org.bouncycastle.bcpg HashAlgorithmTags SHA1

Introduction

In this page you can find the example usage for org.bouncycastle.bcpg HashAlgorithmTags SHA1.

Prototype

int SHA1

To view the source code for org.bouncycastle.bcpg HashAlgorithmTags SHA1.

Click 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 {//from   w w  w. jav a2s.c  om
        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.arcusx.simplepgp.PgpDataEncryptor.java

public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName,
        InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput)
        throws IOException, PGPException {
    PGPCompressedDataGenerator comData = null;
    try {/*ww w.  j ava 2  s . com*/
        OutputStream out = dataOut;
        PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn);

        if (isArmoredOutput) {
            out = new ArmoredOutputStream(out);
        }

        BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
        dataEncryptor.setWithIntegrityPacket(true);
        dataEncryptor.setSecureRandom(new SecureRandom());

        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
        encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey));

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

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

        // Initialize signature generator
        final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn);
        PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey);

        PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
                senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);

        PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
        signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey));
        signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate());
        signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

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

        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = dataIn.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }
        dataIn.close();
        literalDataGenerator.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        signatureGenerator.generate().encode(compressedOut);
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        if (isArmoredOutput) {
            out.close();
        }
    } finally {
        if (comData != null) {
            comData.close();
        }
        IOUtils.closeQuietly(dataOut);
    }
}

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

License:Open Source License

/**
 * /*w  w  w  . j  ava2s. com*/
 * @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

/**
 * /*  www.j  ava2  s .  co 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.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * PGP sign a stream.//from   w ww .j av  a  2  s.c  o  m
 *
 * @param data       The stream that contains the data to sign.
 * @param privateKey The private key to use for signing.
 * @param passPhrase The passphrase that the private key is locked with.
 * @param armoured   {@code true}: ASCII armor the signature.
 *
 * @return The signature.
 *
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws FileNotFoundException
 * @throws PGPException
 * @throws IOException
 */
public static InputStream sign(final InputStream data, final PGPSecretKey privateKey, final String passPhrase,
        final boolean armoured) throws NoSuchAlgorithmException, NoSuchProviderException, PGPException,
        SignatureException, IOException {

    /* Build the signature generator. */
    PGPSignatureGenerator signer = new PGPSignatureGenerator(privateKey.getPublicKey().getAlgorithm(),
            HashAlgorithmTags.SHA1, BouncyCastleProvider.PROVIDER_NAME);
    signer.initSign(PGPSignature.BINARY_DOCUMENT,
            privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME));

    /* Write the data into the generator. */
    byte[] buffer = new byte[4096];
    for (int read; (read = data.read(buffer)) >= 0;)
        signer.update(buffer, 0, read);

    /* Create the signature output stream, armour if necessary. */
    try (ByteArrayOutputStream signatureByteStream = new ByteArrayOutputStream();
            OutputStream signatureStream = armoured ? new ArmoredOutputStream(signatureByteStream)
                    : signatureByteStream) {

        /* Create and write out the signature. */
        PGPSignature signature = signer.generate();
        signature.encode(signatureStream);

        return new ByteArrayInputStream(signatureByteStream.toByteArray());
    }
}

From source file:crypttools.PGPTools.java

License:Open Source License

/**
 * /*w ww  .  j  av 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:de.dentrassi.pm.signing.pgp.internal.PgpSigningService.java

License:Open Source License

@Override
public void sign(final InputStream in, final OutputStream out, final boolean inline) throws Exception {
    final int digest = HashAlgorithmTags.SHA1;
    final PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new BcPGPContentSignerBuilder(this.privateKey.getPublicKeyPacket().getAlgorithm(), digest));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, this.privateKey);

    final ArmoredOutputStream armoredOutput = new ArmoredOutputStream(out);

    if (inline) {
        armoredOutput.beginClearText(digest);
    }/*from www  .  j  av  a  2s . com*/

    final byte[] buffer = new byte[4096];

    int rc;
    while ((rc = in.read(buffer)) >= 0) {
        if (inline) {
            armoredOutput.write(buffer, 0, rc);
        }
        signatureGenerator.update(buffer, 0, rc);
    }

    armoredOutput.endClearText();

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

    armoredOutput.close();
}

From source file:divconq.pgp.PGPUtil.java

License:Open Source License

public static String getDigestName(int hashAlgorithm) throws PGPException {
    switch (hashAlgorithm) {
    case HashAlgorithmTags.SHA1:
        return "SHA1";
    case HashAlgorithmTags.MD2:
        return "MD2";
    case HashAlgorithmTags.MD5:
        return "MD5";
    case HashAlgorithmTags.RIPEMD160:
        return "RIPEMD160";
    case HashAlgorithmTags.SHA256:
        return "SHA256";
    case HashAlgorithmTags.SHA384:
        return "SHA384";
    case HashAlgorithmTags.SHA512:
        return "SHA512";
    case HashAlgorithmTags.SHA224:
        return "SHA224";
    case HashAlgorithmTags.TIGER_192:
        return "TIGER";
    default://  w  w  w.  java  2  s  .co m
        throw new PGPException("unknown hash algorithm tag in getDigestName: " + hashAlgorithm);
    }
}

From source file:keygenerator.KeyGenerator.java

public final static PGPKeyRingGenerator generateKeyRingGenerator(String id, char[] pass, int s2kcount)
        throws Exception {
    // This object generates individual key-pairs.
    RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();

    // Boilerplate RSA parameters, no need to change anything
    // except for the RSA key-size (2048). You can use whatever
    // key-size makes sense for you -- 4096, etc.
    kpg.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), new SecureRandom(), 2048, 12));

    // First create the master (signing) key with the generator.
    PGPKeyPair rsakp_sign = new BcPGPKeyPair(PGPPublicKey.RSA_SIGN, kpg.generateKeyPair(), new Date());
    // Then an encryption subkey.
    PGPKeyPair rsakp_enc = new BcPGPKeyPair(PGPPublicKey.RSA_ENCRYPT, kpg.generateKeyPair(), new Date());

    // Add a self-signature on the id
    PGPSignatureSubpacketGenerator signhashgen = new PGPSignatureSubpacketGenerator();

    // Add signed metadata on the signature.
    // 1) Declare its purpose
    signhashgen.setKeyFlags(false, KeyFlags.SIGN_DATA | KeyFlags.CERTIFY_OTHER);
    // 2) Set preferences for secondary crypto algorithms to use
    //    when sending messages to this key.
    signhashgen.setPreferredSymmetricAlgorithms(false, new int[] { SymmetricKeyAlgorithmTags.AES_256,
            SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128 });
    signhashgen.setPreferredHashAlgorithms(false, new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1,
            HashAlgorithmTags.SHA384, HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224, });
    // 3) Request senders add additional checksums to the
    //    message (useful when verifying unsigned messages.)
    signhashgen.setFeature(false, Features.FEATURE_MODIFICATION_DETECTION);

    // Create a signature on the encryption subkey.
    PGPSignatureSubpacketGenerator enchashgen = new PGPSignatureSubpacketGenerator();
    // Add metadata to declare its purpose
    enchashgen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);

    // Objects used to encrypt the secret key.
    PGPDigestCalculator sha1Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);
    PGPDigestCalculator sha256Calc = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA256);

    // bcpg 1.48 exposes this API that includes s2kcount. Earlier
    // versions use a default of 0x60.
    PBESecretKeyEncryptor pske = (new BcPBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha256Calc,
            s2kcount)).build(pass);//  ww  w .ja v a  2  s.c o  m

    // Finally, create the keyring itself. The constructor
    // takes parameters that allow it to generate the self
    // signature.

    BcPGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
            rsakp_sign.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

    PGPKeyRingGenerator keyRingGen;
    keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, rsakp_sign, id, sha1Calc,
            signhashgen.generate(), null, signerBuilder, pske);

    // Add our encryption subkey, together with its signature.
    keyRingGen.addSubKey(rsakp_enc, enchashgen.generate(), null);
    return keyRingGen;
}

From source file:org.eclipse.packagedrone.repo.signing.pgp.internal.AbstractSecretKeySigningService.java

License:Open Source License

@Override
public OutputStream signingStream(final OutputStream stream, final boolean inline) {
    return new SigningStream(stream, this.privateKey, HashAlgorithmTags.SHA1, inline,
            VersionInformation.VERSIONED_PRODUCT);
}