List of usage examples for org.bouncycastle.openpgp PGPPublicKeyRing insertPublicKey
public static PGPPublicKeyRing insertPublicKey(PGPPublicKeyRing pubRing, PGPPublicKey pubKey)
From source file:com.google.gerrit.gpg.GerritPublicKeyCheckerTest.java
License:Apache License
@Test public void keyLaterInTrustChainMissingUserId() throws Exception { // A---Bx/*from www .j av a 2 s.c om*/ // \ // \---C // // The server ultimately trusts B. // C signed A's key but is not in the store. TestKey keyA = add(keyA(), user); PGPPublicKeyRing keyRingB = keyB().getPublicKeyRing(); PGPPublicKey keyB = keyRingB.getPublicKey(); keyB = PGPPublicKey.removeCertification(keyB, (String) keyB.getUserIDs().next()); keyRingB = PGPPublicKeyRing.insertPublicKey(keyRingB, keyB); add(keyRingB, addUser("userB")); PublicKeyChecker checkerA = checkerFactory.create(user, store); assertProblems(checkerA.check(keyA.getPublicKey()), Status.OK, "No path to a trusted key", "Certification by " + keyToString(keyB) + " is valid, but key is not trusted", "Key D24FE467 used for certification is not in store"); }
From source file:com.google.gerrit.gpg.PublicKeyCheckerTest.java
License:Apache License
private PGPPublicKeyRing removeRevokers(PGPPublicKeyRing kr) { PGPPublicKey k = kr.getPublicKey();//w w w. j av a 2 s .c o m @SuppressWarnings("unchecked") Iterator<PGPSignature> sigs = k.getSignaturesOfType(DIRECT_KEY); while (sigs.hasNext()) { PGPSignature sig = sigs.next(); if (sig.getHashedSubPackets().hasSubpacket(REVOCATION_KEY)) { k = PGPPublicKey.removeCertification(k, sig); } } return PGPPublicKeyRing.insertPublicKey(kr, k); }
From source file:com.google.gerrit.gpg.PublicKeyStoreTest.java
License:Apache License
@Test public void updateExisting() throws Exception { TestKey key5 = TestKey.key5();/*w w w. j a v a 2 s . c om*/ PGPPublicKeyRing keyRing = key5.getPublicKeyRing(); PGPPublicKey key = keyRing.getPublicKey(); store.add(keyRing); assertEquals(RefUpdate.Result.NEW, store.save(newCommitBuilder())); assertUserIds(store.get(key5.getKeyId()).iterator().next(), "Testuser Five <test5@example.com>", "foo:myId"); keyRing = PGPPublicKeyRing.removePublicKey(keyRing, key); key = PGPPublicKey.removeCertification(key, "foo:myId"); keyRing = PGPPublicKeyRing.insertPublicKey(keyRing, key); store.add(keyRing); assertEquals(RefUpdate.Result.FAST_FORWARD, store.save(newCommitBuilder())); Iterator<PGPPublicKeyRing> keyRings = store.get(key.getKeyID()).iterator(); keyRing = keyRings.next(); assertFalse(keyRings.hasNext()); assertUserIds(keyRing, "Testuser Five <test5@example.com>"); }
From source file:org.kontalk.xmppserver.pgp.PGPUtils.java
License:Open Source License
public static PGPPublicKeyRing merge(PGPPublicKeyRing oldRing, PGPPublicKeyRing newRing) throws PGPException, IOException { if (!equals(oldRing, newRing)) { throw new PGPKeyValidationException("keys are not equal"); }// w w w . java 2 s .c om // remember which certs we already added. this is cheaper than semantic deduplication Set<byte[]> certs = new TreeSet<>(new Comparator<byte[]>() { public int compare(byte[] left, byte[] right) { // check for length equality if (left.length != right.length) { return left.length - right.length; } // compare byte-by-byte for (int i = 0; i < left.length; i++) { if (left[i] != right[i]) { return (left[i] & 0xff) - (right[i] & 0xff); } } // ok they're the same return 0; } }); PGPPublicKeyRing result = oldRing; PGPPublicKeyRing candidate = newRing; // Pre-load all existing certificates for (@SuppressWarnings("unchecked") Iterator<PGPPublicKey> i = result.getPublicKeys(); i.hasNext();) { PGPPublicKey key = i.next(); for (@SuppressWarnings("unchecked") Iterator<PGPSignature> j = key.getSignatures(); j.hasNext();) { PGPSignature cert = j.next(); certs.add(cert.getEncoded()); } } for (@SuppressWarnings("unchecked") Iterator<PGPPublicKey> i = candidate.getPublicKeys(); i.hasNext();) { PGPPublicKey key = i.next(); final PGPPublicKey resultKey = result.getPublicKey(key.getKeyID()); if (resultKey == null) { // otherwise, just insert the public key result = PGPPublicKeyRing.insertPublicKey(result, key); continue; } // Modifiable version of the old key, which we merge stuff into (keep old for comparison) PGPPublicKey modified = resultKey; // Iterate certifications for (@SuppressWarnings("unchecked") Iterator<PGPSignature> j = key.getSignatures(); j.hasNext();) { PGPSignature cert = j.next(); byte[] encoded = cert.getEncoded(); // Known cert, skip it if (certs.contains(encoded)) { continue; } certs.add(encoded); modified = PGPPublicKey.addCertification(modified, cert); } // If this is a subkey, merge it in and stop here if (!key.isMasterKey()) { if (modified != resultKey) { result = PGPPublicKeyRing.insertPublicKey(result, modified); } continue; } // Copy over all user id certificates for (@SuppressWarnings("unchecked") Iterator<byte[]> r = key.getRawUserIDs(); r.hasNext();) { byte[] rawUserId = r.next(); @SuppressWarnings("unchecked") Iterator<PGPSignature> signaturesIt = key.getSignaturesForID(rawUserId); // no signatures for this User ID, skip it if (signaturesIt == null) { continue; } while (signaturesIt.hasNext()) { PGPSignature cert = signaturesIt.next(); byte[] encoded = cert.getEncoded(); // Known cert, skip it if (certs.contains(encoded)) { continue; } certs.add(encoded); modified = PGPPublicKey.addCertification(modified, rawUserId, cert); } } // Copy over all user attribute certificates for (@SuppressWarnings("unchecked") Iterator<PGPUserAttributeSubpacketVector> v = key.getUserAttributes(); v.hasNext();) { PGPUserAttributeSubpacketVector vector = v.next(); @SuppressWarnings("unchecked") Iterator<PGPSignature> signaturesIt = key.getSignaturesForUserAttribute(vector); // no signatures for this user attribute attribute, skip it if (signaturesIt == null) { continue; } while (signaturesIt.hasNext()) { PGPSignature cert = signaturesIt.next(); byte[] encoded = cert.getEncoded(); // Known cert, skip it if (certs.contains(encoded)) { continue; } certs.add(encoded); modified = PGPPublicKey.addCertification(modified, vector, cert); } } // If anything change, save the updated (sub)key if (modified != resultKey) { result = PGPPublicKeyRing.insertPublicKey(result, modified); } } return result; }
From source file:org.sufficientlysecure.keychain.pgp.PgpCertifyOperation.java
License:Open Source License
public PgpCertifyResult certify(CanonicalizedSecretKey secretKey, CanonicalizedPublicKeyRing publicRing, OperationLog log, int indent, CertifyAction action, Map<ByteBuffer, byte[]> signedHashes, Date creationTimestamp) { if (!secretKey.isMasterKey()) { throw new AssertionError("tried to certify with non-master key, this is a programming error!"); }// ww w .j a v a 2 s . c o m if (publicRing.getMasterKeyId() == secretKey.getKeyId()) { throw new AssertionError("key tried to self-certify, this is a programming error!"); } // create a signatureGenerator from the supplied masterKeyId and passphrase PGPSignatureGenerator signatureGenerator = secretKey.getCertSignatureGenerator(signedHashes); { // supply signatureGenerator with a SubpacketVector PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); if (creationTimestamp != null) { spGen.setSignatureCreationTime(false, creationTimestamp); Log.d(Constants.TAG, "For NFC: set sig creation time to " + creationTimestamp); } PGPSignatureSubpacketVector packetVector = spGen.generate(); signatureGenerator.setHashedSubpackets(packetVector); } // get the master subkey (which we certify for) PGPPublicKey publicKey = publicRing.getPublicKey().getPublicKey(); SecurityTokenSignOperationsBuilder requiredInput = new SecurityTokenSignOperationsBuilder(creationTimestamp, publicKey.getKeyID(), publicKey.getKeyID()); try { if (action.mUserIds != null) { log.add(LogType.MSG_CRT_CERTIFY_UIDS, 2, action.mUserIds.size(), KeyFormattingUtils.convertKeyIdToHex(action.mMasterKeyId)); // fetch public key ring, add the certification and return it for (String userId : action.mUserIds) { try { PGPSignature sig = signatureGenerator.generateCertification(userId, publicKey); publicKey = PGPPublicKey.addCertification(publicKey, userId, sig); } catch (NfcInteractionNeeded e) { requiredInput.addHash(e.hashToSign, e.hashAlgo); } } } if (action.mUserAttributes != null) { log.add(LogType.MSG_CRT_CERTIFY_UATS, 2, action.mUserAttributes.size(), KeyFormattingUtils.convertKeyIdToHex(action.mMasterKeyId)); // fetch public key ring, add the certification and return it for (WrappedUserAttribute userAttribute : action.mUserAttributes) { PGPUserAttributeSubpacketVector vector = userAttribute.getVector(); try { PGPSignature sig = signatureGenerator.generateCertification(vector, publicKey); publicKey = PGPPublicKey.addCertification(publicKey, vector, sig); } catch (NfcInteractionNeeded e) { requiredInput.addHash(e.hashToSign, e.hashAlgo); } } } } catch (PGPException e) { Log.e(Constants.TAG, "signing error", e); return new PgpCertifyResult(); } if (!requiredInput.isEmpty()) { return new PgpCertifyResult(requiredInput.build()); } PGPPublicKeyRing ring = PGPPublicKeyRing.insertPublicKey(publicRing.getRing(), publicKey); return new PgpCertifyResult(new UncachedKeyRing(ring)); }
From source file:org.sufficientlysecure.keychain.pgp.UncachedKeyRing.java
License:Open Source License
/** This method replaces a public key in a keyring. * * This method essentially wraps PGP*KeyRing.insertPublicKey, where the keyring may be of either * the secret or public subclass./*from w w w . j ava 2s . c o m*/ * * @return the resulting PGPKeyRing of the same type as the input */ private static PGPKeyRing replacePublicKey(PGPKeyRing ring, PGPPublicKey key) { if (ring instanceof PGPPublicKeyRing) { PGPPublicKeyRing pubRing = (PGPPublicKeyRing) ring; return PGPPublicKeyRing.insertPublicKey(pubRing, key); } else { PGPSecretKeyRing secRing = (PGPSecretKeyRing) ring; PGPSecretKey sKey = secRing.getSecretKey(key.getKeyID()); // if this is a secret key which does not yet occur in the secret ring if (sKey == null) { // generate a stripped secret (sub)key sKey = PGPSecretKey.constructGnuDummyKey(key); } sKey = PGPSecretKey.replacePublicKey(sKey, key); return PGPSecretKeyRing.insertSecretKey(secRing, sKey); } }
From source file:ubicrypt.core.crypto.PGPECTest.java
License:Open Source License
@Test public void serializePKring() throws Exception { final PGPKeyPair sign = PGPEC.masterKey(); final PGPKeyPair enc = PGPEC.encryptionKey(); final char[] passPhrase = "g".toCharArray(); final PGPKeyPair newKeyPair = PGPEC.extractEncryptKeyPair(PGPEC.createSecretKeyRing(passPhrase), passPhrase);// ww w. j a va2 s. c o m final PGPKeyPair newKeyPair2 = PGPEC.extractEncryptKeyPair(PGPEC.createSecretKeyRing(passPhrase), passPhrase); final PGPPublicKeyRing kring = PGPPublicKeyRing .insertPublicKey(PGPEC.keyRingGenerator(sign).generatePublicKeyRing(), newKeyPair.getPublicKey()); List<PGPPublicKey> pks = PGPEC.readPKring(new ByteArrayInputStream(kring.getEncoded())); assertThat(pks).hasSize(1); assertThat(pks.get(0).getKeyID()).isEqualTo(newKeyPair.getKeyID()); pks = PGPEC.readPKring(new ByteArrayInputStream( PGPPublicKeyRing.insertPublicKey(kring, newKeyPair2.getPublicKey()).getEncoded())); assertThat(pks).hasSize(2); assertThat(pks.stream().map(PGPPublicKey::getKeyID).collect(Collectors.toList())) .contains(newKeyPair.getKeyID(), newKeyPair2.getKeyID()); }
From source file:ubicrypt.core.crypto.PGPECTest.java
License:Open Source License
@Test public void signPK() throws Exception { final char[] password = "ciao".toCharArray(); final PGPSecretKeyRing skr = PGPEC.createSecretKeyRing(password); final byte[] encSkr = skr.getEncoded(); final PGPKeyPair keyPair = PGPEC.extractEncryptKeyPair(PGPEC.readSK(new ByteArrayInputStream(encSkr)), "ciao".toCharArray()); final PGPKeyRingGenerator pkgen = PGPEC.keyRingGenerator(); final PGPSecretKeyRing targetSecRing = PGPEC.createSecretKeyRing("g".toCharArray()); final PGPPrivateKey priv = PGPEC.extractSignKey(targetSecRing, "g".toCharArray()); final PGPPublicKeyRing pkr = PGPPublicKeyRing.insertPublicKey(pkgen.generatePublicKeyRing(), PGPEC.signPK(keyPair.getPublicKey(), priv)); final byte[] pkis = pkr.getEncoded(); final List<PGPPublicKey> loadRing = PGPEC.readPKring(new ByteArrayInputStream(pkis)); assertThat(loadRing).hasSize(1);// w w w. j ava 2 s . c o m assertThat(Utils.toStream(loadRing.get(0).getKeySignatures()) .filter(sig -> ((PGPSignature) sig).getKeyID() == priv.getKeyID()).findFirst()).isPresent(); }