org.bouncycastle.openpgp.PGPPublicKeyRing Java Examples

The following examples show how to use org.bouncycastle.openpgp.PGPPublicKeyRing. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyInfoTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubKeyMach() throws IOException, PGPException {

    try (InputStream inputStream = getClass().getResourceAsStream("/EFE8086F9E93774E.asc")) {
        Optional<PGPPublicKeyRing> aPublicKeyRing = PublicKeyUtils.loadPublicKeyRing(inputStream, PGPKeyId.from(0xEFE8086F9E93774EL));

        assertThat(aPublicKeyRing)
                .hasValueSatisfying(publicKeyRing -> {
                    // keyInfo with master key fingerprint
                    KeyInfo keyInfo = new KeyInfo(PublicKeyUtils.fingerprint(publicKeyRing.getPublicKey()));

                    assertThat(keyInfo.isKeyMatch(publicKeyRing.getPublicKey(0xEFE8086F9E93774EL), publicKeyRing))
                            .isTrue();
                });
    }
}
 
Example #2
Source File: Ring.java    From jpgpj with MIT License 6 votes vote down vote up
/**
 * Loads all keys from the specified input stream,
 * and adds them to this ring's existing list of keys.
 */
public List<Key> load(InputStream stream) throws IOException, PGPException {
    List<Key> keys = new ArrayList<Key>();

    Iterator<?> packets = parse(stream);
    while (packets.hasNext()) {
        Object packet = packets.next();

        if (packet instanceof PGPSecretKeyRing)
            keys.add(newKey((PGPSecretKeyRing) packet));
        else if (packet instanceof PGPPublicKeyRing)
            keys.add(newKey((PGPPublicKeyRing) packet));
        else if (packet instanceof PublicKeyRingBlob)
            keys.add(newKey(
                ((PublicKeyRingBlob) packet).getPGPPublicKeyRing()));
    }

    this.keys.addAll(keys);
    return keys;
}
 
Example #3
Source File: KeyDataPgp.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
	ois.defaultReadObject();

	try {
		if (ois.readBoolean()) {
			secretKeyRing = new PGPSecretKeyRing(initInputStream(ois),
					KeyFilesOperationsPgpImpl.fingerprintCalculator);
		}
		if (ois.readBoolean()) {
			publicKeyRing = new PGPPublicKeyRing(initInputStream(ois),
					KeyFilesOperationsPgpImpl.fingerprintCalculator);
		}
	} catch (PGPException e) {
		throw new IOException("Failed to read key", e);
	}
}
 
Example #4
Source File: PGPVerifyMojo.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
private boolean verifySignatureStatus(boolean signatureStatus, Artifact artifact,
        PGPPublicKey publicKey, PGPPublicKeyRing publicKeyRing) {

    if (signatureStatus) {
        logWithQuiet.accept(() -> String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(),
                "OK", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing),
                PublicKeyUtils.getUserIDs(publicKey, publicKeyRing)));
        return true;
    } else if (keysMap.isBrokenSignature(artifact)) {
        logWithQuiet.accept(() ->
                String.format("%s PGP Signature is broken, consistent with keys map.", artifact.getId()));
        return true;
    }
    getLog().error(String.format(PGP_VERIFICATION_RESULT_FORMAT, artifact.getId(),
            "INVALID", PublicKeyUtils.keyIdDescription(publicKey, publicKeyRing),
            PublicKeyUtils.getUserIDs(publicKey, publicKeyRing)));
    return false;
}
 
Example #5
Source File: PGPKeysCache.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
public PGPPublicKeyRing getKeyRing(PGPKeyId keyID) throws IOException, PGPException {

        Optional<PGPPublicKeyRing> keyRing = Optional.empty();

        String path = keyID.getHashPath();
        File keyFile = new File(cachePath, path);

        synchronized (LOCK) {

            if (!keyFile.exists()) {
                keyServerList.execute(keysServerClient -> receiveKey(keyFile, keyID, keysServerClient));
            }

            try (InputStream keyFileStream = new FileInputStream(keyFile)) {
                keyRing = PublicKeyUtils.loadPublicKeyRing(keyFileStream, keyID);
                return keyRing.orElseThrow(() ->
                        new PGPException(String.format("Can't find public key %s in download file: %s",
                                keyID, keyFile)));
            } finally {
                if (!keyRing.isPresent()) {
                    deleteFile(keyFile);
                }
            }
        }
    }
 
Example #6
Source File: BerkeleyPGPLocalKeyring.java    From tigase-extension with GNU General Public License v3.0 6 votes vote down vote up
private PGPPublicKeyRing importKey(PGPPublicKeyRing keyring) throws IOException, PGPException {
    String fpr = PGPUtils.getFingerprint(keyring);
    PGPPublicKeyRing newring;
    PGPPublicKeyRing oldring = getKey(fpr);
    if (oldring != null) {
        newring = PGPUtils.merge(oldring, keyring);
    }
    else {
        newring = keyring;
    }

    try {
        db.put(null, new DatabaseEntry(fingerprintKey(fpr)), new DatabaseEntry(newring.getEncoded()));
    }
    catch (DatabaseException e) {
        throw new IOException("Database error", e);
    }
    return newring;
}
 
Example #7
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static PGPPublicKeyRing removeSignature( PGPPublicKeyRing keyToRemoveFrom, String id ) throws PGPException
{
    try
    {
        PGPPublicKey oldKey = keyToRemoveFrom.getPublicKey();
        PGPPublicKey newKey = PGPPublicKey.removeCertification( oldKey, id );

        PGPPublicKeyRing newPublicKeyRing = PGPPublicKeyRing.removePublicKey( keyToRemoveFrom, oldKey );
        return PGPPublicKeyRing.insertPublicKey( newPublicKeyRing, newKey );
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new PGPException( "Error removing signature", e );
    }
}
 
Example #8
Source File: PeerEnvironmentKeyTask.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public Peer call() throws Exception
{
    RelationLinkDto relationLinkDto = new RelationLinkDto( environment );
    PublicKeyContainer publicKeyContainer = peer.createPeerEnvironmentKeyPair( relationLinkDto );

    PGPPublicKeyRing pubRing = getPublicKey( publicKeyContainer );

    PGPPublicKeyRing signedPEK = keyManager.setKeyTrust( envSecKeyRing, pubRing, KeyTrustLevel.FULL.getId() );

    peer.updatePeerEnvironmentPubKey( environment.getEnvironmentId(), signedPEK );
    peer.addPeerEnvironmentPubKey( localPeer.getId() + "_" + environment.getEnvironmentId().getId(),
            localPeerSignedPEK );

    localPeer.addPeerEnvironmentPubKey( peer.getId() + "_" + environment.getEnvironmentId().getId(), signedPEK );

    return peer;
}
 
Example #9
Source File: RemotePeerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void addPeerEnvironmentPubKey( final String keyId, final PGPPublicKeyRing pek ) throws PeerException
{
    Preconditions.checkNotNull( keyId, "Invalid key ID" );
    Preconditions.checkNotNull( pek, "Public key ring is null" );


    try
    {
        String exportedPubKeyRing = securityManager.getEncryptionTool().armorByteArrayToString( pek.getEncoded() );
        peerWebClient.addPeerEnvironmentPubKey( keyId, exportedPubKeyRing );
    }
    catch ( IOException | PGPException e )
    {
        throw new PeerException( e.getMessage() );
    }
}
 
Example #10
Source File: OpenPgpContact.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Return a {@link Set} of {@link OpenPgpV4Fingerprint}s of all keys in {@code publicKeys}, which are marked with the
 * {@link OpenPgpTrustStore.Trust} of {@code trust}.
 *
 * @param publicKeys {@link PGPPublicKeyRingCollection} of keys which are iterated.
 * @param trust {@link OpenPgpTrustStore.Trust} state.
 * @return {@link Set} of fingerprints
 *
 * @throws IOException IO error
 */
public Set<OpenPgpV4Fingerprint> getFingerprintsOfKeysWithState(PGPPublicKeyRingCollection publicKeys,
                                                                OpenPgpTrustStore.Trust trust)
        throws IOException {
    PGPPublicKeyRingCollection keys = getPublicKeysOfTrustState(publicKeys, trust);
    Set<OpenPgpV4Fingerprint> fingerprints = new HashSet<>();

    if (keys == null) {
        return fingerprints;
    }

    for (PGPPublicKeyRing ring : keys) {
        fingerprints.add(new OpenPgpV4Fingerprint(ring));
    }

    return fingerprints;
}
 
Example #11
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public PGPPublicKeyRing signKey( PGPSecretKeyRing sourceSecRing, PGPPublicKeyRing targetPubRing, int trustLevel )
{
    try
    {
        String sigId = PGPKeyUtil.encodeNumericKeyId( targetPubRing.getPublicKey().getKeyID() );

        targetPubRing = encryptionTool.signPublicKey( targetPubRing, sigId, sourceSecRing.getSecretKey(), "" );
    }
    catch ( Exception ignored )
    {
        //ignore
    }

    return targetPubRing;
}
 
Example #12
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public String signPublicKey( String sourceIdentityId, String keyText, int trustLevel )
{
    String keyStr = "";

    try
    {
        PGPPublicKeyRing targetPubRing = PGPKeyUtil.readPublicKeyRing( keyText );
        PGPSecretKeyRing sourceSecRing = getSecretKeyRing( sourceIdentityId );

        targetPubRing = signKey( sourceSecRing, targetPubRing, trustLevel );
        keyStr = encryptionTool.armorByteArrayToString( targetPubRing.getEncoded() );
    }
    catch ( Exception ex )
    {
        LOG.error( "**** Error !!! Error signing key, IdentityId: " + sourceIdentityId, ex );
    }
    return keyStr;
}
 
Example #13
Source File: PGPKeysCacheTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void getKeyFromCache() throws IOException, PGPException {

    PGPKeysCache pgpKeysCache = new PGPKeysCache(cachePath.toFile(), keysServerClients, true);

    // first call retrieve key from server
    PGPPublicKeyRing keyRing = pgpKeysCache.getKeyRing(PGPKeyId.from(0xEFE8086F9E93774EL));

    assertThat(keyRing)
            .hasSize(2)
            .anyMatch(key -> key.getKeyID() == 0xEFE8086F9E93774EL);

    verify(keysServerClients.get(0)).getUriForGetKey(any(PGPKeyId.class));
    verify(keysServerClients.get(0)).copyKeyToOutputStream(any(PGPKeyIdLong.class), any(OutputStream.class), any(PGPKeysServerClient.OnRetryConsumer.class));
    verifyNoMoreInteractions(keysServerClients.get(0));
    clearInvocations(keysServerClients.get(0));

    // second from cache
    keyRing = pgpKeysCache.getKeyRing(PGPKeyId.from(0xEFE8086F9E93774EL));

    assertThat(keyRing)
            .hasSize(2)
            .anyMatch(key -> key.getKeyID() == 0xEFE8086F9E93774EL);

    verifyNoInteractions(keysServerClients.get(0));
}
 
Example #14
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public PGPPublicKeyRing getPublicKeyRingByFingerprint( String fingerprint )
{
    try
    {
        byte[] aKeyData = keyServer.getPublicKeyByFingerprint( fingerprint ).getKeyData();

        if ( aKeyData != null )
        {
            return PGPKeyUtil.readPublicKeyRing( aKeyData );
        }
    }
    catch ( Exception e )
    {
        return null;
    }
    return null;
}
 
Example #15
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public PGPPublicKey getRemoteHostPublicKey( final String hostIdTarget )
{
    try
    {
        PGPPublicKeyRing pubRing;

        pubRing = getPublicKeyRing( hostIdTarget );

        if ( pubRing != null )
        {
            return PGPKeyUtil.readPublicKey( pubRing );
        }
    }
    catch ( Exception ex )
    {
        // ignore
    }
    return null;
}
 
Example #16
Source File: EncryptionToolImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * Signs a public key
 *
 * @param publicKeyRing a public key ring containing the single public key to sign
 * @param id the id we are certifying against the public key
 * @param secretKey the signing key
 * @param secretKeyPassword the signing key password
 *
 * @return a public key ring with the signed public key
 */
@Override
public PGPPublicKeyRing signPublicKey( PGPPublicKeyRing publicKeyRing, String id, PGPSecretKey secretKey,
                                       String secretKeyPassword )
{
    try
    {
        if ( StringUtils.isBlank( secretKeyPassword ) )
        {
            secretKeyPassword = keyManager.getSecurityKeyData().getSecretKeyringPwd();
        }

        return PGPEncryptionUtil.signPublicKey( publicKeyRing, id, secretKey, secretKeyPassword );
    }
    catch ( Exception e )
    {
        //throw custom  exception
        throw new ActionFailedException( e );
    }
}
 
Example #17
Source File: EnvironmentManagerImpl.java    From peer-os with Apache License 2.0 6 votes vote down vote up
PGPSecretKeyRing createEnvironmentKeyPair( EnvironmentId envId ) throws EnvironmentCreationException
{
    KeyManager keyManager = securityManager.getKeyManager();
    String pairId = envId.getId();
    try
    {
        KeyPair keyPair = keyManager.generateKeyPair( pairId, false );

        //******Create PEK *****************************************************************
        PGPSecretKeyRing secRing = pgpKeyUtil.getSecretKeyRing( keyPair.getSecKeyring() );
        PGPPublicKeyRing pubRing = pgpKeyUtil.getPublicKeyRing( keyPair.getPubKeyring() );

        //***************Save Keys *********************************************************
        keyManager.saveSecretKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), secRing );
        keyManager.savePublicKeyRing( pairId, SecurityKeyType.ENVIRONMENT_KEY.getId(), pubRing );


        return secRing;
    }
    catch ( PGPException ex )
    {
        throw new EnvironmentCreationException( ex );
    }
}
 
Example #18
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRing removeSignature( String sourceFingerprint, String targetFingerprint )
{
    PGPPublicKeyRing targetPubRing = getPublicKeyRingByFingerprint( targetFingerprint );
    PGPPublicKeyRing sourcePubRing = getPublicKeyRingByFingerprint( sourceFingerprint );
    PGPPublicKey sourcePublicKey = sourcePubRing.getPublicKey();

    return removeSignature( sourcePublicKey, targetPubRing );
}
 
Example #19
Source File: BerkeleyPGPLocalKeyringTest.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testImportKey() throws Exception {
    InputStream in = getClass().getResourceAsStream(TEST_KEY);
    PGPPublicKeyRing key = keyring.importKey(in);
    in.close();
    assertNotNull(key);
}
 
Example #20
Source File: KyotoPGPLocalKeyringTest.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testImportKey() throws Exception {
    InputStream in = getClass().getResourceAsStream(TEST_KEY);
    PGPPublicKeyRing key = keyring.importKey(in);
    in.close();
    assertNotNull(key);
}
 
Example #21
Source File: KeyManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public PGPPublicKeyRing getPublicKeyRing( String identityId )
{
    PGPPublicKeyRing publicKeyRing;

    if ( StringUtils.isBlank( identityId ) )
    {
        identityId = keyData.getManHostId();
    }

    try
    {
        SecurityKey keyIden = securityDataService.getKeyData( identityId );

        if ( keyIden == null )
        {
            LOG.warn( "*******  SecurityKey (getPublicKeyRing) not found for identityID:" + identityId );

            return null;
        }
        else
        {

            byte[] aKeyData = keyServer.getPublicKeyByFingerprint( keyIden.getPublicKeyFingerprint() ).getKeyData();

            publicKeyRing = PGPKeyUtil.readPublicKeyRing( aKeyData );

            return publicKeyRing;
        }
    }
    catch ( Exception ex )
    {
        LOG.error( " ***** Error getting Public key:" + ex.toString() );
        return null;
    }
}
 
Example #22
Source File: PGPKeyHelper.java    From peer-os with Apache License 2.0 5 votes vote down vote up
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." );
}
 
Example #23
Source File: OpenPGPKeyBasedEncryptor.java    From nifi with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated

    // Read in from the public keyring file
    try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {

        // Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
        PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());

        // Iterate over all public keyrings
        Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
        PGPPublicKeyRing keyRing;
        while (iter.hasNext()) {
            keyRing = iter.next();

            // Iterate over each public key in this keyring
            Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
            while (keyIter.hasNext()) {
                PGPPublicKey publicKey = keyIter.next();

                // Iterate over each userId attached to the public key
                Iterator userIdIterator = publicKey.getUserIDs();
                while (userIdIterator.hasNext()) {
                    String id = (String) userIdIterator.next();
                    if (userId.equalsIgnoreCase(id)) {
                        return publicKey;
                    }
                }
            }
        }
    }

    // If this point is reached, no public key could be extracted with the given userId
    throw new PGPException("Could not find a public key with the given userId");
}
 
Example #24
Source File: RelationMessageManagerImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public Relation decryptAndVerifyMessage( final String signedMessage, final String secretKeyId )
        throws UnsupportedEncodingException, RelationVerificationException
{
    try
    {
        KeyManager keyManager = securityManager.getKeyManager();
        EncryptionTool encryptionTool = securityManager.getEncryptionTool();

        PGPSecretKeyRing secretKeyRing = keyManager.getSecretKeyRing( secretKeyId );

        byte[] extractedText = encryptionTool.extractClearSignContent( signedMessage.getBytes() );
        byte[] decrypted = encryptionTool.decrypt( extractedText, secretKeyRing, "" );

        String decryptedMessage = new String( decrypted, StandardCharsets.UTF_8 );
        RelationImpl relation = JsonUtil.fromJson( decryptedMessage, RelationImpl.class );

        PGPPublicKeyRing publicKey = keyManager.getPublicKeyRing( relation.getKeyId() );
        if ( publicKey == null || !encryptionTool.verifyClearSign( signedMessage.getBytes(), publicKey ) )
        {
            throw new RelationVerificationException( "Relation message verification failed." );
        }

        return relation;
    }
    catch ( Exception ex )
    {
        throw new RelationVerificationException( "Relation verification failed.", ex );
    }
}
 
Example #25
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeyPair( String userId, String secretPwd, boolean armored ) throws PGPException
{
    try
    {
        KeyPair keyPair = new KeyPair();

        PGPKeyRingGenerator krgen = generateKeyRingGenerator( userId, secretPwd, keyPair );

        // Generate public key ring
        PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();
        ByteArrayOutputStream pubOut = new ByteArrayOutputStream();
        pkr.encode( pubOut );
        pubOut.close();

        // Generate private key
        PGPSecretKeyRing skr = krgen.generateSecretKeyRing();
        ByteArrayOutputStream secOut = new ByteArrayOutputStream();
        skr.encode( secOut );
        secOut.close();

        keyPair.setPubKeyring( armored ? armorByteArray( pubOut.toByteArray() ) : pubOut.toByteArray() );
        keyPair.setSecKeyring( armored ? armorByteArray( secOut.toByteArray() ) : secOut.toByteArray() );

        return keyPair;
    }
    catch ( Exception e )
    {
        throw new PGPException( "Error in generateKeyPair", e );
    }
}
 
Example #26
Source File: SecurityKeyUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
/********************************************
 * Convert BouncyCastle PGPKeyRing to SecurityKey entity
 */
public static PublicKeyStore convert( PGPPublicKeyRing pgpKeyRing ) throws IOException
{
    try
    {
        PGPPublicKey pgpKey = PGPKeyUtil.readPublicKey( pgpKeyRing );

        if ( pgpKey != null )
        {
            String fingerprint = new String( Hex.encodeHex( pgpKey.getFingerprint(), false ) );

            PublicKeyStore pk = new PublicKeyStoreEntity();

            pk.setFingerprint( fingerprint );
            pk.setKeyId( PGPKeyUtil.getKeyId( fingerprint ) );
            pk.setShortKeyId( PGPKeyUtil.getShortKeyId( fingerprint ) );
            pk.setKeyData( pgpKeyRing.getEncoded() );

            return pk;
        }
        else
        {
            return null;
        }
    }
    catch ( Exception ex )
    {
        return null;
    }
}
 
Example #27
Source File: PersonalKey.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static X509Certificate createX509Certificate(PGPKeyPair keyPair,
        PGPPublicKeyRing keyRing)
        throws KonException {
    try {
        return X509Bridge.createCertificate(keyPair, keyRing.getEncoded());
    } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException |
            SignatureException | CertificateException | NoSuchProviderException |
            PGPException | IOException | OperatorCreationException ex) {
        LOGGER.log(Level.WARNING, "can't create X.509 certificate");
        throw new KonException(KonException.Error.LOAD_KEY, ex);
    }
}
 
Example #28
Source File: OpenPGPKeyBasedEncryptor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated

    // Read in from the public keyring file
    try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {

        // Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
        PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());

        // Iterate over all public keyrings
        Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
        PGPPublicKeyRing keyRing;
        while (iter.hasNext()) {
            keyRing = iter.next();

            // Iterate over each public key in this keyring
            Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
            while (keyIter.hasNext()) {
                PGPPublicKey publicKey = keyIter.next();

                // Iterate over each userId attached to the public key
                Iterator userIdIterator = publicKey.getUserIDs();
                while (userIdIterator.hasNext()) {
                    String id = (String) userIdIterator.next();
                    if (userId.equalsIgnoreCase(id)) {
                        return publicKey;
                    }
                }
            }
        }
    }

    // If this point is reached, no public key could be extracted with the given userId
    throw new PGPException("Could not find a public key with the given userId");
}
 
Example #29
Source File: PeerEnvironmentKeyTaskTest.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Test
public void testCall() throws Exception
{
    task.call();

    verify( LOCAL_PEER ).addPeerEnvironmentPubKey( anyString(), any( PGPPublicKeyRing.class ) );
}
 
Example #30
Source File: PeerEnvironmentKeyTask.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public PeerEnvironmentKeyTask( final LocalPeer localPeer, final PGPSecretKeyRing envSecKeyRing,
                               final PGPPublicKeyRing localPeerSignedPEK, final Environment environment,
                               final Peer peer, final KeyManager keyManager )
{
    this.localPeer = localPeer;
    this.envSecKeyRing = envSecKeyRing;
    this.localPeerSignedPEK = localPeerSignedPEK;
    this.environment = environment;
    this.peer = peer;
    this.keyManager = keyManager;
}