Example usage for org.bouncycastle.openpgp PGPSignature DEFAULT_CERTIFICATION

List of usage examples for org.bouncycastle.openpgp PGPSignature DEFAULT_CERTIFICATION

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPSignature DEFAULT_CERTIFICATION.

Prototype

int DEFAULT_CERTIFICATION

To view the source code for org.bouncycastle.openpgp PGPSignature DEFAULT_CERTIFICATION.

Click Source Link

Usage

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

License:Open Source License

public PGPSecretKey generateKey(String identity, char[] passPhrase) throws PGPException,
        NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(2048);/* w ww.  j  a va  2 s  . c om*/
    KeyPair kp = kpg.generateKeyPair();
    PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PGPPublicKey.RSA_GENERAL,
            kp.getPublic(), kp.getPrivate(), new Date(), identity, PGPEncryptedData.AES_256, passPhrase, null,
            null, new SecureRandom(), "BC");

    //TODO sign key, associate email address, expiration?, comment?
    return secretKey;
}

From source file:com.ginema.crypto.encryption.PGPKeyPairGenerator.java

License:Apache License

private static void exportKeyPair(OutputStream secretOut, OutputStream publicOut, PublicKey publicKey,
        PrivateKey privateKey, String identity, char[] passPhrase, boolean armor)
        throws IOException, InvalidKeyException, NoSuchProviderException, SignatureException, PGPException {
    if (armor) {/* w w w . j a v  a2s.co  m*/
        secretOut = new ArmoredOutputStream(secretOut);
    }

    PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PGPPublicKey.RSA_GENERAL,
            publicKey, privateKey, new Date(), identity, PGPEncryptedData.CAST5, passPhrase, null, null,
            new SecureRandom(), "BC");

    secretKey.encode(secretOut);

    secretOut.close();

    if (armor) {
        publicOut = new ArmoredOutputStream(publicOut);
    }

    PGPPublicKey key = secretKey.getPublicKey();

    key.encode(publicOut);

    publicOut.close();
}

From source file:com.google.e2e.bcdriver.KeyChecker.java

License:Apache License

private static final void maybeAddUserID(List<UserID> uids, PGPPublicKey pk, String uid, StringBuilder errors)
        throws PGPException, SignatureException, IOException {

    Iterator<PGPSignature> sigit = Util.getTypedIterator(pk.getSignaturesForID(uid), PGPSignature.class);
    if (sigit == null) {
        errors.append(//from www. jav a 2s.co  m
                "Reject name '" + uid + "' for " + nicePk(pk) + " because no self-signatures were found.\n");
        return;
    }

    // Select the most recent valid signature.
    PGPSignature validSig = null;
    long validTs = -1L;

    while (sigit.hasNext()) {
        PGPSignature sig = sigit.next();

        switch (sig.getSignatureType()) {
        case PGPSignature.DEFAULT_CERTIFICATION:
        case PGPSignature.NO_CERTIFICATION:
        case PGPSignature.CASUAL_CERTIFICATION:
        case PGPSignature.POSITIVE_CERTIFICATION:
        case PGPSignature.CERTIFICATION_REVOCATION:
            if (isGoodUIDSignature(sig, pk, uid, errors)) {
                long ts = sig.getCreationTime().getTime();
                if (ts > validTs) {
                    validTs = ts;
                    validSig = sig;
                }
            }
            break;

        default:
            break;
        }
    }

    if (validSig == null) {
        errors.append("Name '" + uid + "' rejected because no self-signatures were found.\n");
        return;
    }

    if (validSig.getSignatureType() == PGPSignature.CERTIFICATION_REVOCATION) {
        errors.append("Name '" + uid + "' rejected because it was revoked.\n");
        return;
    }

    // Add UID information.
    uids.add(new UserID(uid, validSig));
}

From source file:com.google.gerrit.gpg.GerritPublicKeyChecker.java

License:Apache License

private static boolean isValidCertification(PGPPublicKey key, PGPSignature sig, String userId)
        throws PGPException {
    if (sig.getSignatureType() != PGPSignature.DEFAULT_CERTIFICATION
            && sig.getSignatureType() != PGPSignature.POSITIVE_CERTIFICATION) {
        return false;
    }/*  w ww  .j a va2s .c o  m*/
    if (sig.getKeyID() != key.getKeyID()) {
        return false;
    }
    // TODO(dborowitz): Handle certification revocations:
    // - Is there a revocation by either this key or another key trusted by the
    //   server?
    // - Does such a revocation postdate all other valid certifications?

    sig.init(new BcPGPContentVerifierBuilderProvider(), key);
    return sig.verifyCertification(userId, key);
}

From source file:com.google.gerrit.gpg.PublicKeyChecker.java

License:Apache License

private CheckResult checkWebOfTrust(PGPPublicKey key, PublicKeyStore store, int depth, Set<Fingerprint> seen) {
    if (trusted == null || store == null) {
        return CheckResult.OK; // Trust checking not configured.
    }//from   w  ww  .  ja va 2 s  .c om
    Fingerprint fp = new Fingerprint(key.getFingerprint());
    if (seen.contains(fp)) {
        return new CheckResult("Key is trusted in a cycle");
    }
    seen.add(fp);

    Fingerprint trustedFp = trusted.get(key.getKeyID());
    if (trustedFp != null && trustedFp.equals(fp)) {
        return CheckResult.OK; // Directly trusted.
    } else if (depth >= maxTrustDepth) {
        return new CheckResult("No path of depth <= " + maxTrustDepth + " to a trusted key");
    }

    List<CheckResult> signerResults = new ArrayList<>();
    @SuppressWarnings("unchecked")
    Iterator<String> userIds = key.getUserIDs();
    while (userIds.hasNext()) {
        String userId = userIds.next();
        @SuppressWarnings("unchecked")
        Iterator<PGPSignature> sigs = key.getSignaturesForID(userId);
        while (sigs.hasNext()) {
            PGPSignature sig = sigs.next();
            // TODO(dborowitz): Handle CERTIFICATION_REVOCATION.
            if (sig.getSignatureType() != PGPSignature.DEFAULT_CERTIFICATION
                    && sig.getSignatureType() != PGPSignature.POSITIVE_CERTIFICATION) {
                continue; // Not a certification.
            }

            PGPPublicKey signer = getSigner(store, sig, userId, key, signerResults);
            // TODO(dborowitz): Require self certification.
            if (signer == null || Arrays.equals(signer.getFingerprint(), key.getFingerprint())) {
                continue;
            }
            CheckResult signerResult = checkTrustSubpacket(sig, depth);
            if (signerResult.isOk()) {
                signerResult = check(signer, store, depth + 1, false, seen);
                if (signerResult.isOk()) {
                    return CheckResult.OK;
                }
            }
            signerResults.add(new CheckResult(
                    "Certification by " + keyToString(signer) + " is valid, but key is not trusted"));
        }
    }

    List<String> problems = new ArrayList<>();
    problems.add("No path to a trusted key");
    for (CheckResult signerResult : signerResults) {
        problems.addAll(signerResult.getProblems());
    }
    return new CheckResult(problems);
}

From source file:de.jtheuer.diki.lib.pgp.PGPHandler.java

License:Open Source License

/**
 * Generates a new private/public key protected with the given passphrase.
 * //from  w  w w . j  a va 2  s  .  c  o  m
 * @param passphrase
 * @param identity
 * @param secret
 * @param pub
 * @return the generated key pair
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 * @throws PGPException
 */
private PGPSecretKey generateKeypair(char[] passphrase, String identity) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException, SignatureException, IOException, PGPException {
    /* initialize generator */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(2048);

    KeyPair kp = kpg.generateKeyPair();
    secretkey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, PGPPublicKey.RSA_GENERAL, kp.getPublic(),
            kp.getPrivate(), new Date(), identity, PGPEncryptedData.CAST5, passphrase, null, null,
            new SecureRandom(), "BC");

    return secretkey;

}

From source file:de.softwareforge.pgpsigner.commands.SignCommand.java

License:Apache License

@Override
public void executeInteractiveCommand(final String[] args) {

    PGPSignatureGenerator signatureGenerator = null;

    SecretKey signKey = getContext().getSignKey();
    PGPPublicKey pubKey = signKey.getPGPPublicKey();

    try {/*from  w ww . j a  v a  2s . c  o  m*/
        signatureGenerator = new PGPSignatureGenerator(pubKey.getAlgorithm(), PGPUtil.SHA1, "BC");
        signatureGenerator.initSign(PGPSignature.DEFAULT_CERTIFICATION, signKey.getPGPPrivateKey());

        PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
        for (Iterator it = pubKey.getUserIDs(); it.hasNext();) {
            subpacketGenerator.setSignerUserID(false, (String) it.next());
            signatureGenerator.setHashedSubpackets(subpacketGenerator.generate());
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        System.out.println("Could not generate signature for signing.");
        return;
    }

    for (PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) {

        if (!key.isSigned()) {
            try {
                PGPPublicKey newKey = key.getPGPPublicKey();
                PGPSignature signature = signatureGenerator.generateCertification(newKey);

                for (Iterator it = key.getUserIds(); it.hasNext();) {
                    String userId = (String) it.next();
                    newKey = PGPPublicKey.addCertification(newKey, userId, signature);
                }

                key.setPGPPublicKey(newKey);
                key.setSigned(true);
                System.out.println("Signed Key " + key.getKeyId() + " with " + signKey.getKeyId());

            } catch (RuntimeException re) {
                throw re;
            } catch (Exception e) {
                System.out.println("Could not sign key " + DisplayHelpers.showKey(key) + ", skipping.");
            }
        }
    }
}

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 ww.java  2  s.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.xmppserver.pgp.PGPUtils.java

License:Open Source License

public static boolean findValidKeySignature(PGPPublicKey key, String uid, PGPPublicKey signerKey)
        throws PGPException {
    PGPSignature valid = null;//from   w  ww .  j av a2 s .co  m
    long keyId = signerKey.getKeyID();

    @SuppressWarnings("unchecked")
    Iterator<PGPSignature> sigs = key.getSignaturesForID(uid);
    while (sigs != null && sigs.hasNext()) {
        PGPSignature sig = sigs.next();
        if (sig.getKeyID() == keyId && verifyUidSignature(key, sig, signerKey, uid)) {
            if (sig.getSignatureType() == PGPSignature.DEFAULT_CERTIFICATION
                    || sig.getSignatureType() == PGPSignature.CASUAL_CERTIFICATION) {
                if (valid == null || valid.getCreationTime().before(sig.getCreationTime()))
                    valid = sig;
            }
            // TODO else if (sig.getSignatureType() == PGPSignature.CERTIFICATION_REVOCATION) ...
        }
    }

    return valid != null;
}

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();
    }/* w ww.j  a v  a2  s. c  o m*/

    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;
    }
}