public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator() ); Iterator rIt = pgpPub.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next(); Iterator kIt = kRing.getPublicKeys(); while (kIt.hasNext()) { PGPPublicKey k = (PGPPublicKey) kIt.next(); if (k.isEncryptionKey()) { return k; } } } throw new IllegalArgumentException( "Can't find encryption key in key ring."); }
public static PGPPublicKey readPublicKey( InputStream is ) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( is ), new JcaKeyFingerprintCalculator() ); Iterator keyRingIter = pgpPub.getKeyRings(); while ( keyRingIter.hasNext() ) { PGPPublicKeyRing keyRing = ( PGPPublicKeyRing ) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while ( keyIter.hasNext() ) { PGPPublicKey key = ( PGPPublicKey ) keyIter.next(); if ( key.isEncryptionKey() ) { return key; } } } throw new IllegalArgumentException( "Can't find encryption key in key ring." ); }
public PGPPublicKey getKey(long keyID) throws IOException, PGPException { File keyFile = null; PGPPublicKey key = null; try { String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID); keyFile = new File(cachePath, path); if (!keyFile.exists()) { receiveKey(keyFile, keyID); } InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile)); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); key = pgpRing.getPublicKey(keyID); } finally { if (key == null) { deleteFile(keyFile); } } return key; }
/** * Search for public key on keyring based on a substring (like an email address). * * @throws VerifyException if the key couldn't be found. * @see #lookupKeyPair */ public static PGPPublicKey lookupPublicKey( PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) { try { // Safe by specification. @SuppressWarnings("unchecked") Iterator<PGPPublicKeyRing> results = keyring.getKeyRings(checkNotNull(query, "query"), true, true); verify(results.hasNext(), "No public key found matching substring: %s", query); while (results.hasNext()) { Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want); if (result.isPresent()) { return result.get(); } } throw new VerifyException(String.format( "No public key (%s) found matching substring: %s", want, query)); } catch (PGPException e) { throw new VerifyException(String.format( "Public key lookup with query %s failed: %s", query, e.getMessage())); } }
/** * Same as {@link #lookupPublicKey} but also retrieves the associated private key. * * @throws VerifyException if either keys couldn't be found. * @see #lookupPublicKey */ @SuppressWarnings("deprecation") public static PGPKeyPair lookupKeyPair( PGPPublicKeyRingCollection publics, PGPSecretKeyRingCollection privates, String query, KeyRequirement want) { PGPPublicKey publicKey = lookupPublicKey(publics, query, want); PGPPrivateKey privateKey; try { PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()), "Keyring missing private key associated with public key id: %x (query '%s')", publicKey.getKeyID(), query); // We do not support putting a password on the private key so we're just going to // put char[0] here. privateKey = secret.extractPrivateKey( new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(new char[0])); } catch (PGPException e) { throw new VerifyException(e.getMessage()); } return new PGPKeyPair(publicKey, privateKey); }
/** * Determines a public key from the keyring collection which has a certain * key ID and which has a User ID which contains at least one of the User ID * parts. * * @param keyId * key ID * @param userIdParts * user ID parts, can be empty, than no filter on the User ID is * executed * @param publicKeyringCollection * keyring collection * @return public key or <code>null</code> if no fitting key is found * @throws PGPException */ @SuppressWarnings("unchecked") public static PGPPublicKey getPublicKeyWithKeyIdAndUserID(long keyId, List<String> userIdParts, PGPPublicKeyRingCollection publicKeyringCollection) throws PGPException { PGPPublicKeyRing publicKeyring = publicKeyringCollection.getPublicKeyRing(keyId); if (publicKeyring == null) { LOG.debug("No public key found for key ID {}.", Long.toString(keyId)); return null; } // publicKey can be a subkey the user IDs must therefore be provided by the primary/master key if (isAllowedKey(userIdParts, publicKeyring.getPublicKey().getUserIDs())) { return publicKeyring.getPublicKey(keyId); } else { return null; } }
static PGPPublicKey readPublicKey(String keyringPath) throws Exception { InputStream input = new ByteArrayInputStream(getKeyRing(keyringPath)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
public PGPPublicKey createKeyFrom(InputStream in) throws IOException, PGPException { InputStream pgpData = PGPUtil.getDecoderStream(in); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(pgpData), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing)keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey)keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
private void saveToNotes(ObjectInserter ins, PGPPublicKeyRing keyRing) throws PGPException, IOException { long keyId = keyRing.getPublicKey().getKeyID(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size() + 1); boolean replaced = false; for (PGPPublicKeyRing kr : existing) { if (sameKey(keyRing, kr)) { toWrite.add(keyRing); replaced = true; } else { toWrite.add(kr); } } if (!replaced) { toWrite.add(keyRing); } notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite))); }
private void deleteFromNotes(ObjectInserter ins, Fingerprint fp) throws PGPException, IOException { long keyId = fp.getId(); PGPPublicKeyRingCollection existing = get(keyId); List<PGPPublicKeyRing> toWrite = new ArrayList<>(existing.size()); for (PGPPublicKeyRing kr : existing) { if (!fp.equalsBytes(kr.getPublicKey().getFingerprint())) { toWrite.add(kr); } } if (toWrite.size() == existing.size()) { return; } else if (!toWrite.isEmpty()) { notes.set(keyObjectId(keyId), ins.insert(OBJ_BLOB, keysToArmored(toWrite))); } else { notes.remove(keyObjectId(keyId)); } }
private Result checkSignature(PGPSignature sig, PushCertificate cert, PublicKeyStore store) throws PGPException, IOException { PGPPublicKeyRingCollection keys = store.get(sig.getKeyID()); if (!keys.getKeyRings().hasNext()) { return new Result( null, CheckResult.bad("No public keys found for key ID " + keyIdToString(sig.getKeyID()))); } PGPPublicKey signer = PublicKeyStore.getSigner(keys, sig, Constants.encode(cert.toText())); if (signer == null) { return new Result( null, CheckResult.bad("Signature by " + keyIdToString(sig.getKeyID()) + " is not valid")); } CheckResult result = publicKeyChecker.setStore(store).setEffectiveTime(sig.getCreationTime()).check(signer); if (!result.getProblems().isEmpty()) { StringBuilder err = new StringBuilder("Invalid public key ") .append(keyToString(signer)) .append(":\n ") .append(Joiner.on("\n ").join(result.getProblems())); return new Result(signer, CheckResult.create(result.getStatus(), err.toString())); } return new Result(signer, result); }
PGPPublicKey getKey(long keyID) throws IOException, PGPException { File keyFile = null; PGPPublicKey key = null; try { String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID); keyFile = new File(cachePath, path); if (!keyFile.exists()) { receiveKey(keyFile, keyID); } InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile)); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); key = pgpRing.getPublicKey(keyID); } finally { if (key == null) { deleteFile(keyFile); } } return key; }
@SuppressWarnings("unchecked") private final static List<Result> validate (CHkpSearch.Info candidate, String q, IGetter getter) throws IOException { List<Result> ret = new ArrayList<Result>(); if (shouldSkip(candidate, q)) { return ret; } // 1. pull down keys from the candidate. PGPPublicKeyRingCollection pkrc = CHkpSearch.get (candidate.getKeyId(), getter); if ((pkrc == null) || (pkrc.size() <= 0)) { return ret; } // 2. Validate each keyring. Iterator<PGPPublicKeyRing> pkrit = pkrc.getKeyRings(); while (pkrit.hasNext()) { Result r = validateKeyRing(pkrit.next(), q, getter); if (r != null) { ret.add(r); } } return ret; }
@Test public void verifyGoodSignature() throws Exception { final PGPPublicKeyRingCollection publicKeyRing = getPublicKeyRingWithTrustedKeys(); final PGPSignatureList sl = readSignatureFile("/content1.sig"); assertThat(sl.isEmpty()).isFalse(); assertThat(sl.size()).isEqualTo(1); PGPSignature signature = sl.get(0); signature.init(new BcPGPContentVerifierBuilderProvider(), publicKeyRing.getPublicKey(signature.getKeyID())); InputStream contentIn = PGPTest.class.getResourceAsStream("/content1"); byte[] buf = new byte[4096]; int len; while (0 <= (len = contentIn.read(buf))) { signature.update(buf, 0, len); } contentIn.close(); assertThat(signature.verify()).isTrue(); }
@Test public void verifyBadSignature() throws Exception { final PGPPublicKeyRingCollection publicKeyRing = getPublicKeyRingWithTrustedKeys(); final PGPSignatureList sl = readSignatureFile("/content1.sig"); assertThat(sl.isEmpty()).isFalse(); assertThat(sl.size()).isEqualTo(1); PGPSignature signature = sl.get(0); signature.init(new BcPGPContentVerifierBuilderProvider(), publicKeyRing.getPublicKey(signature.getKeyID())); InputStream contentIn = PGPTest.class.getResourceAsStream("/content1"); byte[] buf = new byte[4096]; int len; while (0 <= (len = contentIn.read(buf))) { buf[0] = 0; signature.update(buf, 0, len); } contentIn.close(); assertThat(signature.verify()).isFalse(); }
/** * A simple routine that opens a key ring file and loads the first available * key suitable for encryption. * * @param input * data stream containing the public key data * @return the first public key found. * @throws IOException * @throws PGPException */ static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for // encryption, in the real // world you would probably want to be a bit smarter about this. // Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
public static PGPPublicKey readPublicKey(InputStream in, int algorithm) throws IOException, PGPException { // Get the decoder stream (auto-disarming) in = PGPUtil.getDecoderStream(in); // Open the key ring PGPPublicKeyRingCollection coll = new PGPPublicKeyRingCollection(in); // Find key encryption key for algorithm, if given return readPublicKey(coll, algorithm); }
public static String getKeyInfo(PGPPublicKeyRingCollection coll) { StringBuffer info = new StringBuffer(); // Iterate through key rings Iterator<?> rings = coll.getKeyRings(); while (rings.hasNext()) { PGPPublicKeyRing ring = (PGPPublicKeyRing)rings.next(); Iterator<?> keys = ring.getPublicKeys(); while (keys.hasNext()) { info.append(getKeyInfo((PGPPublicKey)keys.next())).append("\n"); } } return info.toString(); }
static public void addPublicKeyToKeyring(String gpgHomeDirectory, String keyringFile) throws FileNotFoundException, IOException, PGPException { Security.addProvider(new BouncyCastleProvider()); FileInputStream in = new FileInputStream(gpgHomeDirectory + "/pubring.gpg"); PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(in, new JcaKeyFingerprintCalculator()); PGPPublicKeyRing pgpKeyring = new PGPPublicKeyRing(PGPUtil.getDecoderStream(new FileInputStream(keyringFile)), new JcaKeyFingerprintCalculator()); pubRings = PGPPublicKeyRingCollection.addPublicKeyRing(pubRings, pgpKeyring); try (FileOutputStream out = new FileOutputStream(new File(gpgHomeDirectory + "/pubring.gpg"))) { pubRings.encode(out); } }
public void test6() throws Exception { PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(pub6, new BcKeyFingerprintCalculator()); Iterator rIt = pubRings.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next(); Iterator it = pgpPub.getPublicKeys(); while (it.hasNext()) { PGPPublicKey k = (PGPPublicKey)it.next(); if (k.getKeyID() == 0x5ce086b5b5a18ff4L) { int count = 0; Iterator sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); count++; } if (count != 1) { fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.getEncoded(); }
private void signKeyAndPrintIds( KeyPair first, KeyPair second, String password ) throws IOException, PGPException { InputStream firstPublicStream = new ByteArrayInputStream( first.getPubKeyring() ); InputStream secondPublicStream = new ByteArrayInputStream( second.getPubKeyring() ); InputStream secondSecretStream = new ByteArrayInputStream( second.getSecKeyring() ); PGPPublicKeyRingCollection keyrings = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( firstPublicStream ), new JcaKeyFingerprintCalculator() ); PGPPublicKeyRing firstPublicKeyRing = null; if ( keyrings.getKeyRings().hasNext() ) { firstPublicKeyRing = keyrings.getKeyRings().next(); PGPSecretKey secondSecretKey = PGPEncryptionUtil.findSecretKeyById( secondSecretStream, second.getPrimaryKeyId() ); PGPPublicKey secondPublicKey = PGPEncryptionUtil.findPublicKeyById( secondPublicStream, second.getPrimaryKeyId() ); if ( secondSecretKey != null ) { String keyId = Long.toHexString( secondSecretKey.getKeyID() ); PGPPublicKeyRing firstSignedPublicKeyRing = PGPEncryptionUtil.signPublicKey( firstPublicKeyRing, keyId, secondSecretKey, password ); printPublicKeySignatures( firstSignedPublicKeyRing.getPublicKey(), secondPublicKey ); first.setPubKeyring( firstSignedPublicKeyRing.getEncoded() ); } } }
@Test public void testVerifyClearSign() throws Exception { InputStream secondPublicStream = findFile( PLUGIN_PUBLIC_KEY ); PGPPublicKeyRingCollection secondPublicKeyRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( secondPublicStream ), new JcaKeyFingerprintCalculator() ); PGPPublicKeyRing pgpKeyring = secondPublicKeyRingCollection .getPublicKeyRing( secondPublicKeyRingCollection.iterator().next().getPublicKey().getKeyID() ); String signedMessage = IOUtils.toString( findFile( "signedMessage.txt" ) ); logger.info( "\n" + signedMessage ); boolean result = PGPEncryptionUtil.verifyClearSign( signedMessage.getBytes(), pgpKeyring ); if ( result ) { logger.info( "signature verified." ); } else { logger.info( "signature verification failed." ); } assertEquals( true, result ); }
@SuppressWarnings("unchecked") public List<PGPPublicKeyRing> getTrustedKeys() { if (!ROO_PGP_FILE.exists()) { return new ArrayList<PGPPublicKeyRing>(); } FileInputStream fis = null; try { fis = new FileInputStream(ROO_PGP_FILE); final PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(fis)); final Iterator<PGPPublicKeyRing> rIt = pubRings.getKeyRings(); final List<PGPPublicKeyRing> result = new ArrayList<PGPPublicKeyRing>(); while (rIt.hasNext()) { final PGPPublicKeyRing pgpPub = rIt.next(); rememberKey(pgpPub); result.add(pgpPub); } return result; } catch (final Exception e) { throw new IllegalArgumentException( "Unable to get trusted keys", ObjectUtils.defaultIfNull(ExceptionUtils.getRootCause(e), e)); } finally { IOUtils.closeQuietly(fis); } }
private PGPPublicKeyRing trust(final PGPPublicKeyRing keyRing) { rememberKey(keyRing); // Get the keys we currently trust final List<PGPPublicKeyRing> trusted = getTrustedKeys(); // Do not store if the first key is revoked Validate.validState( !keyRing.getPublicKey().isRevoked(), "The public key ID '%s' has been revoked and cannot be trusted", new PgpKeyId(keyRing.getPublicKey())); // trust it and write back to disk trusted.add(keyRing); OutputStream fos = null; try { final PGPPublicKeyRingCollection newCollection = new PGPPublicKeyRingCollection( trusted); fos = new FileOutputStream(ROO_PGP_FILE); newCollection.encode(fos); } catch (final Exception e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(fos); } return keyRing; }
/** * Reads the public key from the specified key file. * * @param in - Stream pointing to key store. * @param fingerPrintCalculator - An alogrithm to be used for fingerprint calculation. * This sample uses BcKeyFingerprintCalculator algorithm. * @return Returns a public key read from the specified key file. * @throws IOException * @throws PGPException * @throws CryptDecryptException */ private PGPPublicKey readPublicKey() throws IOException, PGPException, CryptDecryptException { if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.readPublicKey", "Entry"); PGPPublicKey publicKey = null; InputStream publicKeyStream = new FileInputStream(keyRing); // Read the key file using BouncyCastle utility class to build a collection. PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyStream), fingerPrintCalculator); // Iterate through the key rings to find a key that can be used for encryption Iterator<PGPPublicKeyRing> rIt = keyRingCollection.getKeyRings(); while (publicKey == null && rIt.hasNext()) { PGPPublicKeyRing kRing = rIt.next(); Iterator<PGPPublicKey> kIt = kRing.getPublicKeys(); while (publicKey == null && kIt.hasNext()) { PGPPublicKey key = kIt.next(); if (key.isEncryptionKey()) { publicKey = key; } } } // The key store does not contain any key. if (publicKey == null) { throw new CryptDecryptException("Can't find public key in the key ring."); } // Check if the key can be used for encryption. If not throw an exception if (!isForEncryption(publicKey)) { throw new CryptDecryptException("KeyID " + publicKey.getKeyID() + " not flagged for encryption."); } if(enableDebugLog)Trace.logInfo("CryptDecryptUtil.readPublicKey", "Exit"); return publicKey; }
/** Always returns a {@link InMemoryKeyring} instance. */ @Provides static Keyring provideKeyring() { PGPKeyPair dummyKey; try (InputStream publicInput = PGP_PUBLIC_KEYRING.openStream(); InputStream privateInput = PGP_PRIVATE_KEYRING.openStream()) { PGPPublicKeyRingCollection publicKeys = new BcPGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicInput)); PGPSecretKeyRingCollection privateKeys = new BcPGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateInput)); dummyKey = lookupKeyPair(publicKeys, privateKeys, EMAIL_ADDRESS, ENCRYPT_SIGN); } catch (PGPException | IOException e) { throw new VerifyException("Failed to load PGP keys from jar", e); } // Use the same dummy PGP keypair for all required PGP keys -- a real production system would // have different values for these keys. Pass dummy values for all Strings. return new InMemoryKeyring( dummyKey, dummyKey, dummyKey.getPublicKey(), dummyKey, dummyKey.getPublicKey(), "not a real key", "not a real key", "not a real password", "not a real login", "not a real password", "not a real login", "not a real credential", "not a real key"); }
public static PGPPublicKeyRingCollection getPublicKeyRingCollection(CamelContext context, String filename, byte[] keyRing, boolean forEncryption) throws IOException, PGPException { InputStream is = determineKeyRingInputStream(context, filename, keyRing, forEncryption); try { return new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(is), new BcKeyFingerprintCalculator()); } finally { IOHelper.close(is); } }
private static PGPPublicKey findPublicKeyWithKeyId(InputStream input, long keyid) throws IOException, PGPException, NoSuchProviderException { PGPPublicKeyRingCollection pgpSec = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); return pgpSec.getPublicKey(keyid); }
private static List<PGPPublicKey> findPublicKeys(InputStream input, List<String> userids, boolean forEncryption) throws IOException, PGPException, NoSuchProviderException { PGPPublicKeyRingCollection pgpSec = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); return findPublicKeys(userids, forEncryption, pgpSec); }
public static List<PGPPublicKey> findPublicKeys(List<String> useridParts, boolean forEncryption, PGPPublicKeyRingCollection pgpPublicKeyringCollection) { List<PGPPublicKey> result = new ArrayList<PGPPublicKey>(useridParts.size()); for (Iterator<PGPPublicKeyRing> keyRingIter = pgpPublicKeyringCollection.getKeyRings(); keyRingIter.hasNext();) { PGPPublicKeyRing keyRing = keyRingIter.next(); PGPPublicKey primaryKey = keyRing.getPublicKey(); String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey); if (foundKeyUserIdForUserIdPart == null) { LOG.debug("No User ID found in primary key with key ID {} containing one of the parts {}", primaryKey.getKeyID(), useridParts); continue; } LOG.debug("User ID {} found in primary key with key ID {} containing one of the parts {}", new Object[] { foundKeyUserIdForUserIdPart[0], primaryKey.getKeyID(), useridParts }); // add adequate keys to the result for (Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); keyIter.hasNext();) { PGPPublicKey key = keyIter.next(); if (forEncryption) { if (isEncryptionKey(key)) { LOG.debug("Public encryption key with key user ID {} and key ID {} added to the encryption keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID())); result.add(key); } } else if (!forEncryption && isSignatureKey(key)) { // not used! result.add(key); LOG.debug("Public key with key user ID {} and key ID {} added to the signing keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID())); } } } return result; }
@Override public void initialize(String privateKey, String privateKeyPass, String publicKey) throws IOException, PGPException, NoSuchProviderException { _provider = new BouncyCastleProvider(); _passphrase = privateKeyPass; _secretKeyRing = new PGPSecretKeyRing(PGPUtil.getDecoderStream(new ByteArrayInputStream(privateKey.getBytes()))); _remotePublicKeyRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new ByteArrayInputStream(publicKey.getBytes()))); }
/** * A simple routine that opens a key ring file and loads the first available key * suitable for encryption. * * @param input * @return * @throws IOException * @throws PGPException */ static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(input)); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing)keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey)keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
public static final byte[] encrypt(File pubring, long keyid, byte[] in){ if(!pubring.exists() || !pubring.isFile()) return null; try { byte[] ret = null; FileInputStream fis = new FileInputStream(pubring); InputStream is = PGPUtil.getDecoderStream(fis); PGPPublicKeyRingCollection ring = new PGPPublicKeyRingCollection(is); PGPPublicKey pubkey = ring.getPublicKey(keyid); if(pubkey.isMasterKey()) { System.err.println("Tried to use a non-encryption key. This should never happen."); return null; } PublicKey key = new JcaPGPKeyConverter().getPublicKey(pubkey); Cipher cipher = Cipher.getInstance(key.getAlgorithm() + "/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); ret = cipher.doFinal(in); is.close(); fis.close(); return ret; } catch (Exception e) { System.err.println(e.getLocalizedMessage()); return null; } }
private static PGPPublicKey getSigner( PublicKeyStore store, PGPSignature sig, String userId, PGPPublicKey key, List<CheckResult> results) { try { PGPPublicKeyRingCollection signers = store.get(sig.getKeyID()); if (!signers.getKeyRings().hasNext()) { results.add( CheckResult.ok( "Key " + keyIdToString(sig.getKeyID()) + " used for certification is not in store")); return null; } PGPPublicKey signer = PublicKeyStore.getSigner(signers, sig, userId, key); if (signer == null) { results.add( CheckResult.ok("Certification by " + keyIdToString(sig.getKeyID()) + " is not valid")); return null; } return signer; } catch (PGPException | IOException e) { results.add( CheckResult.ok("Error checking certification by " + keyIdToString(sig.getKeyID()))); return null; } }
@SuppressWarnings("rawtypes") private static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException { in = PGPUtil.getDecoderStream(in); PGPPublicKeyRingCollection pgpPub = new BcPGPPublicKeyRingCollection(in); // // we just loop through the collection till we find a key suitable for // encryption, in the real // world you would probably want to be a bit smarter about this. // // // iterate through the key rings. // Iterator rIt = pgpPub.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next(); Iterator kIt = kRing.getPublicKeys(); while (kIt.hasNext()) { PGPPublicKey k = (PGPPublicKey) kIt.next(); if (k.isEncryptionKey()) { return k; } } } throw new IllegalArgumentException( "Can't find encryption key in key ring."); }
/** * <p>Return the first suitable key for encryption in the key ring * collection. For this case we only expect there to be one key available * for encryption.</p> * * @param input - the input stream of the PGP key ring * @return the first suitable PGP public key found for encryption * @throws IOException on I/O related errors * @throws PGPException on signing errors */ private static final PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input)); PGPPublicKey pubKey = null; @SuppressWarnings("unchecked") Iterator<PGPPublicKeyRing> keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && pubKey == null) { PGPPublicKeyRing keyRing = keyRingIter.next(); @SuppressWarnings("unchecked") Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = keyIter.next(); if (key.isEncryptionKey()) { pubKey = key; break; } } } if (pubKey != null) { return pubKey; } else { throw new IllegalArgumentException("Can't find encryption key in key ring."); } }
/** * A simple routine that opens a key ring file and loads the first available key * suitable for encryption. * * @param input data stream containing the public key data * @return the first public key found. * @throws IOException * @throws PGPException */ static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(input)); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing)keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey)keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
public void test6() throws Exception { PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(pub6); Iterator rIt = pubRings.getKeyRings(); while (rIt.hasNext()) { PGPPublicKeyRing pgpPub = (PGPPublicKeyRing)rIt.next(); Iterator it = pgpPub.getPublicKeys(); while (it.hasNext()) { PGPPublicKey k = (PGPPublicKey)it.next(); if (k.getKeyID() == 0x5ce086b5b5a18ff4L) { int count = 0; Iterator sIt = k.getSignaturesOfType(PGPSignature.SUBKEY_REVOCATION); while (sIt.hasNext()) { PGPSignature sig = (PGPSignature)sIt.next(); count++; } if (count != 1) { fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.getEncoded(); }