Example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPKeyPair JcaPGPKeyPair

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcaPGPKeyPair JcaPGPKeyPair

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcaPGPKeyPair JcaPGPKeyPair.

Prototype

public JcaPGPKeyPair(int algorithm, KeyPair keyPair, Date date) throws PGPException 

Source Link

Document

Construct PGP key pair from a JCA/JCE key pair.

Usage

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

License:Apache License

public PGPSecretKey newSecretKey() throws NoSuchAlgorithmException, NoSuchProviderException, PGPException {
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);/*from w  w w.  j  av a 2s . c  o  m*/
    final KeyPair pair = kpg.generateKeyPair();
    final PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
            .get(HashAlgorithmTags.SHA1);
    final PGPKeyPair pkp = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, pair, new Date());
    return new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, pkp, "example@example.com", sha1Calc, null,
            null, new JcaPGPContentSignerBuilder(pkp.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
            new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.CAST5, sha1Calc)
                    .setProvider(new BouncyCastleProvider()).build("passphrase".toCharArray()));
}

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

License:Open Source License

/** Creates an ECDSA/ECDH key pair. */
public static PGPDecryptedKeyPairRing create() throws NoSuchAlgorithmException, NoSuchProviderException,
        PGPException, InvalidAlgorithmParameterException {

    KeyPairGenerator gen;/*from  www.  j a  va2s .  com*/
    PGPKeyPair encryptKp, signKp;

    if (EXPERIMENTAL_ECC) {

        gen = KeyPairGenerator.getInstance("ECDH", PROVIDER);
        gen.initialize(new ECGenParameterSpec(EC_CURVE));

        encryptKp = new JcaPGPKeyPair(PGPPublicKey.ECDH, gen.generateKeyPair(), new Date());

        gen = KeyPairGenerator.getInstance("ECDSA", PROVIDER);
        gen.initialize(new ECGenParameterSpec(EC_CURVE));

        signKp = new JcaPGPKeyPair(PGPPublicKey.ECDSA, gen.generateKeyPair(), new Date());
    }

    else {

        gen = KeyPairGenerator.getInstance("RSA", PROVIDER);
        gen.initialize(RSA_KEY_LENGTH);

        encryptKp = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, gen.generateKeyPair(), new Date());

        gen = KeyPairGenerator.getInstance("RSA", PROVIDER);
        gen.initialize(RSA_KEY_LENGTH);

        signKp = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, gen.generateKeyPair(), new Date());
    }

    return new PGPDecryptedKeyPairRing(signKp, encryptKp);
}

From source file:org.pgptool.gui.encryption.implpgp.KeyGeneratorServicePgpImpl.java

License:Open Source License

@Override
public Key createNewKey(CreateKeyParams params) throws FieldValidationException {
    try {//w  w w  .j a va  2s. co m
        Preconditions.checkArgument(params != null, "params must not be null");
        assertParamsValid(params);

        // Create KeyPairs
        KeyPair dsaKp = getOrGenerateDsaKeyPair(DEFAULT_DSA_KEY_PARAMETERS);
        KeyPairGenerator elgKpg = KeyPairGenerator.getInstance("ELGAMAL", "BC");
        DHParameterSpec elParams = new DHParameterSpec(p, g);
        elgKpg.initialize(elParams);
        KeyPair elgKp = elgKpg.generateKeyPair();

        // Now let do some crazy stuff (I HAVE NO IDEA WHAT I AM DOING
        // HERE). BouncyCastle guys are not helping by changing API from
        // one version to another so often!!!!!!!
        PGPKeyPair dsaKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKp, new Date());
        PGPKeyPair elgKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKp, new Date());

        // PGPContentSignerBuilde
        // JCA
        // JcaPGPContentSignerBuilder keySignerBuilder = new
        // JcaPGPContentSignerBuilder(
        // dsaKeyPair.getPublicKey().getAlgorithm(),
        // HashAlgorithmTags.SHA256);

        // BC
        BcPGPContentSignerBuilder keySignerBuilderBC = new BcPGPContentSignerBuilder(
                dsaKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256);

        // PGPDigestCalculator
        // JCA
        // PGPDigestCalculator sha1Calc = new
        // JcaPGPDigestCalculatorProviderBuilder().build()
        // .get(HashAlgorithmTags.SHA256);

        // BC
        PGPDigestCalculator sha1CalcBC = new BcPGPDigestCalculatorProvider().get(HashAlgorithmTags.SHA1);

        // keyEncryptor
        // BC
        BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder(
                PGPEncryptedData.AES_256, sha1CalcBC);
        PBESecretKeyEncryptor keyEncryptorBC = encryptorBuilderBC.build(params.getPassphrase().toCharArray());

        // JCA
        // JcePBESecretKeyEncryptorBuilder encryptorBuilder = new
        // JcePBESecretKeyEncryptorBuilder(
        // PGPEncryptedData.AES_256, sha1Calc).setProvider("BC");
        // PBESecretKeyEncryptor keyEncryptor =
        // encryptorBuilder.build(params.getPassphrase().toCharArray());

        // keyRingGen
        String userName = params.getFullName() + " <" + params.getEmail() + ">";
        // JCA
        // PGPKeyRingGenerator keyRingGen = new
        // PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
        // dsaKeyPair,
        // userName, sha1Calc, null, null, keySignerBuilder,
        // keyEncryptor);

        // BC
        PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
                dsaKeyPair, userName, sha1CalcBC, null, null, keySignerBuilderBC, keyEncryptorBC);

        keyRingGen.addSubKey(elgKeyPair);
        // building ret
        Key ret = buildKey(keyRingGen);
        return ret;
    } catch (Throwable t) {
        Throwables.propagateIfInstanceOf(t, FieldValidationException.class);
        throw new RuntimeException("Failed to generate key", t);
    }
}

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

License:Open Source License

/** Creates new secret key. */
private PGPKeyPair createKey(SubkeyAdd add, Date creationTime, OperationLog log, int indent) {

    try {/*w ww .  jav  a  2  s  . c om*/
        // Some safety checks
        if (add.mAlgorithm == Algorithm.ECDH || add.mAlgorithm == Algorithm.ECDSA) {
            if (add.mCurve == null) {
                log.add(LogType.MSG_CR_ERROR_NO_CURVE, indent);
                return null;
            }
        } else {
            if (add.mKeySize == null) {
                log.add(LogType.MSG_CR_ERROR_NO_KEYSIZE, indent);
                return null;
            }
            if (add.mKeySize < 2048) {
                log.add(LogType.MSG_CR_ERROR_KEYSIZE_2048, indent);
                return null;
            }
        }

        int algorithm;
        KeyPairGenerator keyGen;

        switch (add.mAlgorithm) {
        case DSA: {
            if ((add.mFlags & (PGPKeyFlags.CAN_ENCRYPT_COMMS | PGPKeyFlags.CAN_ENCRYPT_STORAGE)) > 0) {
                log.add(LogType.MSG_CR_ERROR_FLAGS_DSA, indent);
                return null;
            }
            progress(R.string.progress_generating_dsa, 30);
            keyGen = KeyPairGenerator.getInstance("DSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            keyGen.initialize(add.mKeySize, new SecureRandom());
            algorithm = PGPPublicKey.DSA;
            break;
        }

        case ELGAMAL: {
            if ((add.mFlags & (PGPKeyFlags.CAN_SIGN | PGPKeyFlags.CAN_CERTIFY)) > 0) {
                log.add(LogType.MSG_CR_ERROR_FLAGS_ELGAMAL, indent);
                return null;
            }
            progress(R.string.progress_generating_elgamal, 30);
            keyGen = KeyPairGenerator.getInstance("ElGamal", Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            BigInteger p = Primes.getBestPrime(add.mKeySize);
            BigInteger g = new BigInteger("2");

            ElGamalParameterSpec elParams = new ElGamalParameterSpec(p, g);

            keyGen.initialize(elParams);
            algorithm = PGPPublicKey.ELGAMAL_ENCRYPT;
            break;
        }

        case RSA: {
            progress(R.string.progress_generating_rsa, 30);
            keyGen = KeyPairGenerator.getInstance("RSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            keyGen.initialize(add.mKeySize, new SecureRandom());

            algorithm = PGPPublicKey.RSA_GENERAL;
            break;
        }

        case ECDSA: {
            if ((add.mFlags & (PGPKeyFlags.CAN_ENCRYPT_COMMS | PGPKeyFlags.CAN_ENCRYPT_STORAGE)) > 0) {
                log.add(LogType.MSG_CR_ERROR_FLAGS_ECDSA, indent);
                return null;
            }
            progress(R.string.progress_generating_ecdsa, 30);
            ECGenParameterSpec ecParamSpec = getEccParameterSpec(add.mCurve);
            keyGen = KeyPairGenerator.getInstance("ECDSA", Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            keyGen.initialize(ecParamSpec, new SecureRandom());

            algorithm = PGPPublicKey.ECDSA;
            break;
        }

        case ECDH: {
            // make sure there are no sign or certify flags set
            if ((add.mFlags & (PGPKeyFlags.CAN_SIGN | PGPKeyFlags.CAN_CERTIFY)) > 0) {
                log.add(LogType.MSG_CR_ERROR_FLAGS_ECDH, indent);
                return null;
            }
            progress(R.string.progress_generating_ecdh, 30);
            ECGenParameterSpec ecParamSpec = getEccParameterSpec(add.mCurve);
            keyGen = KeyPairGenerator.getInstance("ECDH", Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            keyGen.initialize(ecParamSpec, new SecureRandom());

            algorithm = PGPPublicKey.ECDH;
            break;
        }

        default: {
            log.add(LogType.MSG_CR_ERROR_UNKNOWN_ALGO, indent);
            return null;
        }
        }

        // build new key pair
        return new JcaPGPKeyPair(algorithm, keyGen.generateKeyPair(), creationTime);

    } catch (NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        log.add(LogType.MSG_CR_ERROR_UNKNOWN_ALGO, indent);
        return null;
    } catch (PGPException e) {
        Log.e(Constants.TAG, "internal pgp error", e);
        log.add(LogType.MSG_CR_ERROR_INTERNAL_PGP, indent);
        return null;
    }
}

From source file:portablepgp.core.PGPTools.java

License:Open Source License

/**
 *
 * @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/*w ww .  j a va  2s .  c  om*/
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static final PGPKeyRingGenerator createPGPKeyRingGenerator(KeyPair dsaKeyPair, KeyPair elGamalKeyPair,
        String identity, char[] passphrase) throws Exception {
    PGPKeyPair dsaPgpKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date());
    PGPKeyPair elGamalPgpKeyPair = new JcaPGPKeyPair(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:ubicrypt.core.crypto.PGPEC.java

License:Open Source License

private static PGPKeyPair keyPair(final String algorithm) {
    PGPKeyPair ecdsaKeyPair = null;/*from  w w  w  . ja  va2 s.  c o m*/
    try {
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm, "BC");
        //http://www.ietf.org/rfc/rfc4492.txt
        //5.1.1.  Supported Elliptic Curves Extension
        //https://chrispacia.wordpress.com/2013/10/30/nsa-backdoors-and-bitcoin/
        keyGen.initialize(new ECGenParameterSpec("secp256k1"), new SecureRandom());
        final KeyPair kpSign = keyGen.generateKeyPair();
        ecdsaKeyPair = new JcaPGPKeyPair(alg(algorithm), kpSign, new Date());
    } catch (final Exception e) {
        Throwables.propagate(e);
    }
    return ecdsaKeyPair;
}

From source file:uk.co.platosys.dinigma.LockSmith.java

License:Open Source License

/**
 *
 * @param keyDirectory the directory in which the private key is to be saved. This could be on a removable drive.
 * @param lockDirectory the directory in which the Lock(the public key) is to be saved.
 * @param userName//from   ww  w .  ja  v a 2s . c om
 * @param passPhrase
 * @return The key_id of the signing key.
 * @throws MinigmaException
 */
public static long createLockset(File keyDirectory, File lockDirectory, String userName, char[] passPhrase)
        throws MinigmaException, DuplicateNameException {
    String filename;
    File lockFile;
    File keyFile;
    //test that parameters have been set:
    if (keyDirectory == null) {
        throw new MinigmaException("Locksmith - key directory is null");
    }
    if (!keyDirectory.isDirectory()) {
        throw new MinigmaException("Locksmith: " + keyDirectory.toString() + " is not a directory");
    }
    if (!keyDirectory.canWrite()) {
        throw new MinigmaException("Locksmith: can't  write to " + keyDirectory.toString());
    }
    if (lockDirectory == null) {
        throw new MinigmaException("Locksmith - lock directory is null");
    }
    if (!lockDirectory.isDirectory()) {
        throw new MinigmaException("Locksmith: " + keyDirectory.toString() + " is not a directory");
    }
    if (!lockDirectory.canWrite()) {
        throw new MinigmaException("Locksmith: can't  write to " + keyDirectory.toString());
    }
    try {
        if (Security.getProvider(PROVIDER) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: problem adding security provider", e);
    }
    //
    KeyPairGenerator generator;
    KeyPair dsaKeyPair;
    KeyPair elgKeyPair;
    BigInteger g;
    BigInteger p;
    File lockFolder;
    File keyFolder;
    PGPKeyPair pgpSigKeyPair;
    PGPKeyPair pgpEncKeyPair;
    PGPKeyRingGenerator pgpKeyRingGenerator;
    PGPPublicKeyRing pgpPublicKeyRing;
    PGPSecretKeyRing pgpSecretKeyRing;
    try {
        //the DSA key for signing
        generator = KeyPairGenerator.getInstance(SIGNATURE_ALGORITHM, PROVIDER);
        generator.initialize(1024);
        dsaKeyPair = generator.generateKeyPair();
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to generate dsa key pair", e);
    }
    try {
        //the strong ElGamal key for encrypting
        generator = KeyPairGenerator.getInstance(ASYMMETRIC_ALGORITHM, PROVIDER);
        g = new BigInteger(
                "153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc",
                16);
        p = new BigInteger(
                "9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b",
                16);
        AlgorithmParameterSpec elGamalParameters = new ElGamalParameterSpec(p, g);
        generator.initialize(elGamalParameters);
        elgKeyPair = generator.generateKeyPair();
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to generate elgamal key pair", e);
    }

    try {

        filename = FileTools.removeFunnyCharacters(userName);
        lockFolder = new File(lockDirectory, Minigma.LOCK_DIRNAME);
        if (!lockFolder.exists()) {
            if (!lockFolder.mkdirs()) {
                throw new MinigmaException("Can't create lock folder");
            }
        }
        lockFile = new File(lockFolder, filename);
        if (lockFile.exists()) {
            throw new DuplicateNameException("lockfile with name " + lockFile.getName() + " already exists");
        }
        keyFolder = new File(keyDirectory, Minigma.KEY_DIRNAME);
        if (!keyFolder.exists()) {
            if (!keyFolder.mkdirs()) {
                throw new MinigmaException("Can't create key folder");
            }
        }
        keyFile = new File(keyFolder, filename);
        if (lockFile.exists()) {
            throw new DuplicateNameException("keyfile with name " + keyFile.getName() + " already exists");
        }

    } catch (Exception exc) {
        throw new MinigmaException("Locksmith: error setting up key files", exc);
    }
    try {
        pgpSigKeyPair = new JcaPGPKeyPair(PGPPublicKey.DSA, dsaKeyPair, new Date());
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to generate pgp-dsa key pair", e);
    }
    try {
        pgpEncKeyPair = new JcaPGPKeyPair(PGPPublicKey.ELGAMAL_ENCRYPT, elgKeyPair, new Date());
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to generate pgp-elgamal key pair", e);
    }
    PGPDigestCalculator pgpDigestCalculator = null;
    PGPContentSignerBuilder pgpContentSignerBuilder = null;
    PBESecretKeyEncryptor pbeSecretKeyEncryptor = null;
    try {
        pgpDigestCalculator = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
        pgpContentSignerBuilder = new JcaPGPContentSignerBuilder(SIGNATURE_ALGORITHM_TAG,
                HashAlgorithmTags.SHA512);
        pbeSecretKeyEncryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256,
                pgpDigestCalculator).setProvider(PROVIDER).build(passPhrase);
    } catch (Exception e) {
        throw new MinigmaException("failed to initialise KRG components", e);
    }
    try {
        pgpKeyRingGenerator = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, //certification level
                pgpSigKeyPair, //master key
                userName, // id
                pgpDigestCalculator, //PGPDigestCalculator
                null, //PGPSignatureSubpacketsVector hashed packets
                null, //PGPSignatureSubpacketsVector unhashed packets
                pgpContentSignerBuilder, //PGPContentSignerBuilder
                pbeSecretKeyEncryptor//PBESecretKeyEncryptor
        );

    } catch (PGPException e) {
        throw new MinigmaException("Locksmith: failed to create PGP-keyring generator", e);
    }
    try {
        pgpKeyRingGenerator.addSubKey(pgpEncKeyPair);
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to add elgamal subkey to ring", e);
    }
    try {
        ArmoredOutputStream secOut = new ArmoredOutputStream(new FileOutputStream(keyFile));
        pgpSecretKeyRing = pgpKeyRingGenerator.generateSecretKeyRing();
        pgpSecretKeyRing.encode(secOut);
        secOut.close();
    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to encode secret key output", e);
    }
    try {
        ArmoredOutputStream pubOut = new ArmoredOutputStream(new FileOutputStream(lockFile));
        pgpPublicKeyRing = pgpKeyRingGenerator.generatePublicKeyRing();
        pgpPublicKeyRing.encode(pubOut);
        pubOut.close();

    } catch (Exception e) {
        throw new MinigmaException("Locksmith: failed to encode pubring output", e);
    }

    return pgpSigKeyPair.getKeyID();

}