Example usage for org.bouncycastle.openpgp PGPSecretKey getEncoded

List of usage examples for org.bouncycastle.openpgp PGPSecretKey getEncoded

Introduction

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

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Usage

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Get the keyring pointed to by the public & secret files.  Creates the files
 * with a single key if they don't already exist; interrogates keyDataSource for the
 * info to create the key (typically it should pop up a gui).
 * //  w w w .  j  a  v a2s .c o m
 * TODO bobby: doesn't create usable keyrings yet, and doesn't save what it does create :-( 
 * @param publicKeyRingFile
 * @param secretKeyRingFile
 * @param keyDataSource
 * @return
 * @throws PGPException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
public Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> getOrCreateKeyring(File publicKeyRingFile,
        File secretKeyRingFile, KeyDataSource keyDataSource) throws PGPException, FileNotFoundException,
        IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    boolean pubRingFound = publicKeyRingFile.isFile();
    boolean secRingFound = secretKeyRingFile.isFile();

    if (pubRingFound != secRingFound) {
        throw new PGPException("Expect both public & secret keyring, or neither: " + publicKeyRingFile + ", "
                + secretKeyRingFile);
    }

    Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> retval = new Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection>();

    if (pubRingFound) {
        retval.setFirst(EncryptionUtil.instance().readPublicKeyRingCollection(publicKeyRingFile));
        retval.setSecond(EncryptionUtil.instance().readSecretKeyRingCollection(secretKeyRingFile));
    } else {
        if (publicKeyRingFile.exists() || secretKeyRingFile.exists()) {
            throw new PGPException("Either public or secret keyring not a normal file: " + publicKeyRingFile
                    + ", " + secretKeyRingFile);
        }

        PGPSecretKey key = generateKey(keyDataSource.getIdentity(), keyDataSource.getPassphrase());

        PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(key.getPublicKey().getEncoded());
        Collection<PGPPublicKeyRing> collection = Collections.singletonList(publicKeyRing);
        retval.setFirst(new PGPPublicKeyRingCollection(collection));

        PGPSecretKeyRing secretKeyRing = new PGPSecretKeyRing(key.getEncoded());
        Collection<PGPSecretKeyRing> secretKeyRings = Collections.singletonList(secretKeyRing);
        retval.setSecond(new PGPSecretKeyRingCollection(secretKeyRings));

        //TODO bobby save keyrings to the files
    }

    return retval;
}

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

License:Open Source License

public PgpEditKeyResult createSecretKeyRing(SaveKeyringParcel saveParcel) {

    OperationLog log = new OperationLog();
    int indent = 0;

    try {/* w w  w.ja  v  a2s  . c  o  m*/

        log.add(LogType.MSG_CR, indent);
        progress(R.string.progress_building_key, 0);
        indent += 1;

        if (saveParcel.mAddSubKeys.isEmpty()) {
            log.add(LogType.MSG_CR_ERROR_NO_MASTER, indent);
            return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
        }

        if (saveParcel.mAddUserIds.isEmpty()) {
            log.add(LogType.MSG_CR_ERROR_NO_USER_ID, indent);
            return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
        }

        SubkeyAdd add = saveParcel.mAddSubKeys.remove(0);
        if ((add.mFlags & KeyFlags.CERTIFY_OTHER) != KeyFlags.CERTIFY_OTHER) {
            log.add(LogType.MSG_CR_ERROR_NO_CERTIFY, indent);
            return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
        }

        if (add.mExpiry == null) {
            log.add(LogType.MSG_CR_ERROR_NULL_EXPIRY, indent);
            return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
        }

        Date creationTime = new Date();

        subProgressPush(10, 30);
        PGPKeyPair keyPair = createKey(add, creationTime, log, indent);
        subProgressPop();

        // return null if this failed (an error will already have been logged by createKey)
        if (keyPair == null) {
            return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
        }

        progress(R.string.progress_building_master_key, 40);

        // Build key encrypter and decrypter based on passphrase
        PGPDigestCalculator encryptorHashCalc = new JcaPGPDigestCalculatorProviderBuilder().build()
                .get(PgpSecurityConstants.SECRET_KEY_ENCRYPTOR_HASH_ALGO);
        PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder(
                PgpSecurityConstants.SECRET_KEY_ENCRYPTOR_SYMMETRIC_ALGO, encryptorHashCalc,
                PgpSecurityConstants.SECRET_KEY_ENCRYPTOR_S2K_COUNT)
                        .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());

        PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
                .get(PgpSecurityConstants.SECRET_KEY_SIGNATURE_CHECKSUM_HASH_ALGO);
        PGPSecretKey masterSecretKey = new PGPSecretKey(keyPair.getPrivateKey(), keyPair.getPublicKey(),
                sha1Calc, true, keyEncryptor);

        PGPSecretKeyRing sKR = new PGPSecretKeyRing(masterSecretKey.getEncoded(),
                new JcaKeyFingerprintCalculator());

        subProgressPush(50, 100);
        CryptoInputParcel cryptoInput = new CryptoInputParcel(creationTime, new Passphrase(""));
        return internal(sKR, masterSecretKey, add.mFlags, add.mExpiry, cryptoInput, saveParcel, log, indent);

    } catch (PGPException e) {
        log.add(LogType.MSG_CR_ERROR_INTERNAL_PGP, indent);
        Log.e(Constants.TAG, "pgp error encoding key", e);
        return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
    } catch (IOException e) {
        Log.e(Constants.TAG, "io error encoding key", e);
        return new PgpEditKeyResult(PgpEditKeyResult.RESULT_ERROR, log, null);
    }

}

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

License:Open Source License

@Test
public void testDuplicateSubkey() throws Exception {

    { // duplicate subkey

        // get subkey packets
        Iterator<RawPacket> it = KeyringTestingHelper.parseKeyring(ring.getEncoded());
        RawPacket subKey = KeyringTestingHelper.getNth(it, 7);
        RawPacket subSig = it.next();//w  w w . j a va 2  s  . com

        // inject at a second position
        UncachedKeyRing modified = ring;
        modified = KeyringTestingHelper.injectPacket(modified, subKey.buf, 9);
        modified = KeyringTestingHelper.injectPacket(modified, subSig.buf, 10);

        // canonicalize, and check if we lose the bad signature
        OperationLog log = new OperationLog();
        CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
        Assert.assertNull("canonicalization with duplicate subkey should fail", canonicalized);
        Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
    }

    { // duplicate subkey, which is the same as the master key

        // We actually encountered one of these in the wild:
        // https://www.sparkasse-holstein.de/firmenkunden/electronic_banking/secure-e-mail/pdf/Spk_Holstein_PGP_Domain-Zertifikat.asc

        CanonicalizedSecretKeyRing canonicalized = (CanonicalizedSecretKeyRing) ring.canonicalize(log, 0);

        CanonicalizedSecretKey masterSecretKey = canonicalized.getSecretKey();
        masterSecretKey.unlock(new Passphrase());
        PGPPublicKey masterPublicKey = masterSecretKey.getPublicKey();
        CryptoInputParcel cryptoInput = new CryptoInputParcel(new Date());
        PGPSignature cert = PgpKeyOperation.generateSubkeyBindingSignature(
                PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), cryptoInput),
                cryptoInput.getSignatureTime(), masterPublicKey, masterSecretKey.getPrivateKey(),
                PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), null),
                masterSecretKey.getPrivateKey(), masterPublicKey, masterSecretKey.getKeyUsage(), 0);
        PGPPublicKey subPubKey = PGPPublicKey.addSubkeyBindingCertification(masterPublicKey, cert);

        PGPSecretKey sKey;
        {
            // Build key encrypter and decrypter based on passphrase
            PGPDigestCalculator encryptorHashCalc = new JcaPGPDigestCalculatorProviderBuilder().build()
                    .get(HashAlgorithmTags.SHA256);
            PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder(
                    SymmetricKeyAlgorithmTags.AES_256, encryptorHashCalc, 10)
                            .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());

            // NOTE: only SHA1 is supported for key checksum calculations.
            PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build()
                    .get(HashAlgorithmTags.SHA1);
            sKey = new PGPSecretKey(masterSecretKey.getPrivateKey(), subPubKey, sha1Calc, false, keyEncryptor);
        }

        UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sKey.getEncoded(), 7);

        // canonicalize, and check if we lose the bad signature
        OperationLog log = new OperationLog();
        CanonicalizedKeyRing result = modified.canonicalize(log, 0);
        Assert.assertNull("canonicalization with duplicate subkey (from master) should fail", result);
        Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
    }

}