Java Code Examples for org.jivesoftware.smack.SmackException#NotLoggedInException

The following examples show how to use org.jivesoftware.smack.SmackException#NotLoggedInException . 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: OmemoManagerSetupHelper.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static void trustAllIdentities(OmemoManager alice, OmemoManager bob)
        throws InterruptedException, SmackException.NotConnectedException, SmackException.NotLoggedInException,
        SmackException.NoResponseException, CannotEstablishOmemoSessionException, CorruptedOmemoKeyException,
        XMPPException.XMPPErrorException, PubSubException.NotALeafNodeException, IOException {
    Roster roster = Roster.getInstanceFor(alice.getConnection());

    if (alice.getOwnJid() != bob.getOwnJid() &&
            (!roster.iAmSubscribedTo(bob.getOwnJid()) || !roster.isSubscribedToMyPresence(bob.getOwnJid()))) {
        throw new IllegalStateException("Before trusting identities of a user, we must be subscribed to one another.");
    }

    alice.requestDeviceListUpdateFor(bob.getOwnJid());
    HashMap<OmemoDevice, OmemoFingerprint> fingerprints = alice.getActiveFingerprints(bob.getOwnJid());

    for (OmemoDevice device : fingerprints.keySet()) {
        OmemoFingerprint fingerprint = fingerprints.get(device);
        alice.trustOmemoIdentity(device, fingerprint);
    }
}
 
Example 2
Source File: OXInstantMessagingManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Wrap some {@code payload} into a {@link SigncryptElement}, sign and encrypt it for {@code contacts} and ourselves.
 *
 * @param contacts recipients of the message
 * @param payload payload which will be encrypted and signed
 *
 * @return encrypted and signed {@link OpenPgpElement}, along with {@link OpenPgpMetadata} about the
 * encryption + signatures.
 *
 * @throws SmackException.NotLoggedInException in case we are not logged in
 * @throws IOException IO is dangerous (we need to read keys)
 * @throws PGPException in case encryption goes wrong
 */
public OpenPgpElementAndMetadata signAndEncrypt(Set<OpenPgpContact> contacts, List<ExtensionElement> payload)
        throws SmackException.NotLoggedInException, IOException, PGPException {

    Set<Jid> jids = new HashSet<>();
    for (OpenPgpContact contact : contacts) {
        jids.add(contact.getJid());
    }
    jids.add(openPgpManager.getOpenPgpSelf().getJid());

    SigncryptElement signcryptElement = new SigncryptElement(jids, payload);
    OpenPgpElementAndMetadata encrypted = openPgpManager.getOpenPgpProvider().signAndEncrypt(signcryptElement,
            openPgpManager.getOpenPgpSelf(), contacts);

    return encrypted;
}
 
Example 3
Source File: OmemoManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Get the fingerprint of a contacts device.
 *
 * @param device contacts OmemoDevice
 * @return fingerprint of the given OMEMO device.
 *
 * @throws CannotEstablishOmemoSessionException if we have no session yet, and are unable to create one.
 * @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
 * @throws CorruptedOmemoKeyException if the copy of the fingerprint we have is corrupted.
 * @throws SmackException.NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException.NoResponseException if there was no response from the remote entity.
 * @throws IOException if an I/O error occurred.
 */
public synchronized OmemoFingerprint getFingerprint(OmemoDevice device)
        throws CannotEstablishOmemoSessionException, SmackException.NotLoggedInException,
        CorruptedOmemoKeyException, SmackException.NotConnectedException, InterruptedException,
        SmackException.NoResponseException, IOException {
    if (getOwnJid() == null) {
        throw new SmackException.NotLoggedInException();
    }

    if (device.equals(getOwnDevice())) {
        return getOwnFingerprint();
    }

    return getOmemoService().getOmemoStoreBackend()
            .getFingerprintAndMaybeBuildSession(new LoggedInOmemoManager(this), device);
}
 
Example 4
Source File: Client.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public boolean addToRoster(JID jid, String name) {
    if (!this.isConnected()) {
        LOGGER.info("not connected");
        return false;
    }

    if (!jid.isValid()) {
        LOGGER.warning("invalid JID: " + jid);
        return false;
    }

    try {
        // also sends presence subscription request
        Roster.getInstanceFor(mConn).createEntry(jid.toBareSmack(), name,
                null);
    } catch (SmackException.NotLoggedInException |
            SmackException.NoResponseException |
            XMPPException.XMPPErrorException |
            SmackException.NotConnectedException |
            InterruptedException ex) {
        LOGGER.log(Level.WARNING, "can't add contact to roster", ex);
        return false;
    }
    return true;
}
 
Example 5
Source File: ChatActivity.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
private void addChatGuyToContacts() {
    User userContact = new User();
    userContact.setLogin(XMPPUtils.fromJIDToUserName(mChat.getJid()));
    try {
        RosterManager.getInstance().addContact(userContact);
        setMenuChatWithContact();
        Toast.makeText(this, String.format(Locale.getDefault(), getString(R.string.user_added_to_contacts),
                userContact.getLogin()), Toast.LENGTH_SHORT).show();
    } catch (SmackException.NotLoggedInException | InterruptedException | SmackException.NotConnectedException | XMPPException.XMPPErrorException | XmppStringprepException | SmackException.NoResponseException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: ChatActivity.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
private boolean isChatWithContact() {
    try {
        HashMap<Jid, Presence.Type> buddies = RosterManager.getInstance().getContacts();
        for (Map.Entry pair : buddies.entrySet()) {
            if (mChat.getJid().equals(pair.getKey().toString())) {
                return true;
            }
        }
    } catch (SmackException.NotLoggedInException | InterruptedException | SmackException.NotConnectedException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 7
Source File: ChatActivity.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
private void removeChatGuyFromContacts() {
    User userNotContact = new User();
    userNotContact.setLogin(XMPPUtils.fromJIDToUserName(mChat.getJid()));
    try {
        RosterManager.getInstance().removeContact(userNotContact);
        setMenuChatNotContact();
        Toast.makeText(this, String.format(Locale.getDefault(), getString(R.string.user_removed_from_contacts),
                userNotContact.getLogin()), Toast.LENGTH_SHORT).show();
    } catch (SmackException.NotLoggedInException | InterruptedException |
            SmackException.NotConnectedException | XMPPException.XMPPErrorException |
            XmppStringprepException | SmackException.NoResponseException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void removeAllContacts()
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }
    for (RosterEntry entry : roster.getEntries()) {
        roster.removeEntry(entry);
        Presence presence = new Presence(Presence.Type.unsubscribe);
        presence.setTo(entry.getJid());
        XMPPSession.getInstance().sendStanza(presence);
    }
}
 
Example 9
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a fresh OpenPGP key pair, given we don't have one already.
 * Publish the public key to the Public Key Node and update the Public Key Metadata Node with our keys fingerprint.
 * Lastly register a {@link PepListener} which listens for updates to Public Key Metadata Nodes.
 *
 * @throws NoSuchAlgorithmException if we are missing an algorithm to generate a fresh key pair.
 * @throws NoSuchProviderException if we are missing a suitable {@link java.security.Provider}.
 * @throws InterruptedException if the thread gets interrupted.
 * @throws PubSubException.NotALeafNodeException if one of the PubSub nodes is not a {@link LeafNode}.
 * @throws XMPPException.XMPPErrorException in case of an XMPP protocol error.
 * @throws SmackException.NotConnectedException if we are not connected.
 * @throws SmackException.NoResponseException if the server doesn't respond.
 * @throws IOException IO is dangerous.
 * @throws InvalidAlgorithmParameterException if illegal algorithm parameters are used for key generation.
 * @throws SmackException.NotLoggedInException if we are not logged in.
 * @throws PGPException if something goes wrong during key loading/generating
 */
public void announceSupportAndPublish()
        throws NoSuchAlgorithmException, NoSuchProviderException, InterruptedException,
        PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
        SmackException.NotConnectedException, SmackException.NoResponseException, IOException,
        InvalidAlgorithmParameterException, SmackException.NotLoggedInException, PGPException {
    throwIfNoProviderSet();
    throwIfNotAuthenticated();

    OpenPgpV4Fingerprint primaryFingerprint = getOurFingerprint();

    if (primaryFingerprint == null) {
        primaryFingerprint = generateAndImportKeyPair(getJidOrThrow());
    }

    // Create <pubkey/> element
    PubkeyElement pubkeyElement;
    try {
        pubkeyElement = createPubkeyElement(getJidOrThrow(), primaryFingerprint, new Date());
    } catch (MissingOpenPgpKeyException e) {
        throw new AssertionError("Cannot publish our public key, since it is missing (MUST NOT happen!)");
    }

    // publish it
    publishPublicKey(pepManager, pubkeyElement, primaryFingerprint);

    // Subscribe to public key changes
    pepManager.addPepEventListener(PEP_NODE_PUBLIC_KEYS, PublicKeysListElement.class, pepPublicKeyListElementListener);
    ServiceDiscoveryManager.getInstanceFor(connection())
            .addFeature(PEP_NODE_PUBLIC_KEYS_NOTIFY);
}
 
Example 10
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch a secret key backup from the server and try to restore a selected secret key from it.
 *
 * @param codeCallback callback for prompting the user to provide the secret backup code.
 * @return fingerprint of the restored secret key
 *
 * @throws InterruptedException if the thread gets interrupted.
 * @throws PubSubException.NotALeafNodeException if the private node is not a {@link LeafNode}.
 * @throws XMPPException.XMPPErrorException in case of an XMPP protocol error.
 * @throws SmackException.NotConnectedException if we are not connected.
 * @throws SmackException.NoResponseException if the server doesn't respond.
 * @throws InvalidBackupCodeException if the user-provided backup code is invalid.
 * @throws SmackException.NotLoggedInException if we are not logged in
 * @throws IOException IO is dangerous
 * @throws MissingUserIdOnKeyException if the key that is to be imported is missing a user-id with our jid
 * @throws NoBackupFoundException if no secret key backup has been found
 * @throws PGPException in case the restored secret key is damaged.
 */
public OpenPgpV4Fingerprint restoreSecretKeyServerBackup(AskForBackupCodeCallback codeCallback)
        throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
        SmackException.NotConnectedException, SmackException.NoResponseException,
        InvalidBackupCodeException, SmackException.NotLoggedInException, IOException, MissingUserIdOnKeyException,
        NoBackupFoundException, PGPException {
    throwIfNoProviderSet();
    throwIfNotAuthenticated();
    SecretkeyElement backup = OpenPgpPubSubUtil.fetchSecretKey(pepManager);
    if (backup == null) {
        throw new NoBackupFoundException();
    }

    String backupCode = codeCallback.askForBackupCode();

    PGPSecretKeyRing secretKeys = SecretKeyBackupHelper.restoreSecretKeyBackup(backup, backupCode);
    provider.getStore().importSecretKey(getJidOrThrow(), secretKeys);
    provider.getStore().importPublicKey(getJidOrThrow(), BCUtil.publicKeyRingFromSecretKeyRing(secretKeys));

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048);
    for (PGPSecretKey sk : secretKeys) {
        PGPPublicKey pk = sk.getPublicKey();
        if (pk != null) pk.encode(buffer);
    }
    PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(buffer.toByteArray(), new BcKeyFingerprintCalculator());
    provider.getStore().importPublicKey(getJidOrThrow(), publicKeys);

    return new OpenPgpV4Fingerprint(secretKeys);
}
 
Example 11
Source File: MoodManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
public void clearMood()
        throws InterruptedException, SmackException.NotLoggedInException, SmackException.NoResponseException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException, PubSubException.NotALeafNodeException {
    MoodElement element = buildMood(null, null, null);
    publishMood(element);
}
 
Example 12
Source File: OXSecretKeyBackupIntegrationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@SmackIntegrationTest
public void test() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, IOException, InterruptedException, PubSubException.NotALeafNodeException,
        SmackException.NoResponseException, SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NotLoggedInException, SmackException.FeatureNotSupportedException,
        MissingUserIdOnKeyException, NoBackupFoundException, InvalidBackupCodeException, PGPException,
        MissingOpenPgpKeyException {

    OpenPgpStore beforeStore = new FileBasedOpenPgpStore(beforePath);
    beforeStore.setKeyRingProtector(new UnprotectedKeysProtector());
    PainlessOpenPgpProvider beforeProvider = new PainlessOpenPgpProvider(beforeStore);
    openPgpManager = OpenPgpManager.getInstanceFor(aliceConnection);
    openPgpManager.setOpenPgpProvider(beforeProvider);

    OpenPgpSelf self = openPgpManager.getOpenPgpSelf();

    assertNull(self.getSigningKeyFingerprint());

    OpenPgpV4Fingerprint keyFingerprint = openPgpManager.generateAndImportKeyPair(alice);
    assertEquals(keyFingerprint, self.getSigningKeyFingerprint());

    assertTrue(self.getSecretKeys().contains(keyFingerprint.getKeyId()));

    PGPSecretKeyRing beforeSec = beforeStore.getSecretKeyRing(alice, keyFingerprint);
    assertNotNull(beforeSec);

    PGPPublicKeyRing beforePub = beforeStore.getPublicKeyRing(alice, keyFingerprint);
    assertNotNull(beforePub);

    openPgpManager.backupSecretKeyToServer(new DisplayBackupCodeCallback() {
        @Override
        public void displayBackupCode(String backupCode) {
            OXSecretKeyBackupIntegrationTest.this.backupCode = backupCode;
        }
    }, new SecretKeyBackupSelectionCallback() {
        @Override
        public Set<OpenPgpV4Fingerprint> selectKeysToBackup(Set<OpenPgpV4Fingerprint> availableSecretKeys) {
            return availableSecretKeys;
        }
    });

    FileBasedOpenPgpStore afterStore = new FileBasedOpenPgpStore(afterPath);
    afterStore.setKeyRingProtector(new UnprotectedKeysProtector());
    PainlessOpenPgpProvider afterProvider = new PainlessOpenPgpProvider(afterStore);
    openPgpManager.setOpenPgpProvider(afterProvider);

    OpenPgpV4Fingerprint fingerprint = openPgpManager.restoreSecretKeyServerBackup(new AskForBackupCodeCallback() {
        @Override
        public String askForBackupCode() {
            return backupCode;
        }
    });

    assertEquals(keyFingerprint, fingerprint);

    assertTrue(self.getSecretKeys().contains(keyFingerprint.getKeyId()));

    assertEquals(keyFingerprint, self.getSigningKeyFingerprint());

    PGPSecretKeyRing afterSec = afterStore.getSecretKeyRing(alice, keyFingerprint);
    assertNotNull(afterSec);
    assertTrue(Arrays.equals(beforeSec.getEncoded(), afterSec.getEncoded()));

    PGPPublicKeyRing afterPub = afterStore.getPublicKeyRing(alice, keyFingerprint);
    assertNotNull(afterPub);
    assertTrue(Arrays.equals(beforePub.getEncoded(), afterPub.getEncoded()));
}
 
Example 13
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 4 votes vote down vote up
public boolean isContact(Jid jid)
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException {
    HashMap<Jid, Presence.Type> buddies = getContacts();
    return buddies.containsKey(jid);
}
 
Example 14
Source File: OXInstantMessagingManager.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Manually decrypt and verify an {@link OpenPgpElement}.
 *
 * @param element encrypted, signed {@link OpenPgpElement}.
 * @param sender sender of the message.
 *
 * @return decrypted, verified message
 *
 * @throws SmackException.NotLoggedInException In case we are not logged in (we need our jid to access our keys)
 * @throws PGPException in case of an PGP error
 * @throws IOException in case of an IO error (reading keys, streams etc)
 * @throws XmlPullParserException in case that the content of the {@link OpenPgpElement} is not a valid
 * {@link OpenPgpContentElement} or broken XML.
 * @throws IllegalArgumentException if the elements content is not a {@link SigncryptElement}. This happens, if the
 * element likely is not an OX message.
 */
public OpenPgpMessage decryptAndVerify(OpenPgpElement element, OpenPgpContact sender)
        throws SmackException.NotLoggedInException, PGPException, IOException, XmlPullParserException {

    OpenPgpMessage decrypted = openPgpManager.decryptOpenPgpElement(element, sender);
    if (decrypted.getState() != OpenPgpMessage.State.signcrypt) {
        throw new IllegalArgumentException("Decrypted message does appear to not be an OX message. (State: " + decrypted.getState() + ")");
    }

    return decrypted;
}
 
Example 15
Source File: OmemoManager.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * OMEMO encrypt a cleartext message for a single recipient.
 * Note that this method does NOT set the 'to' attribute of the message.
 *
 * @param recipient recipients bareJid
 * @param message text to encrypt
 * @return encrypted message
 *
 * @throws CryptoFailedException                when something crypto related fails
 * @throws UndecidedOmemoIdentityException      When there are undecided devices
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackException.NotConnectedException if the XMPP connection is not connected.
 * @throws SmackException.NoResponseException if there was no response from the remote entity.
 * @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
 * @throws IOException if an I/O error occurred.
 */
public OmemoMessage.Sent encrypt(BareJid recipient, String message)
        throws CryptoFailedException, UndecidedOmemoIdentityException,
        InterruptedException, SmackException.NotConnectedException,
        SmackException.NoResponseException, SmackException.NotLoggedInException, IOException {
    Set<BareJid> recipients = new HashSet<>();
    recipients.add(recipient);
    return encrypt(recipients, message);
}
 
Example 16
Source File: OXInstantMessagingManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Add an OX-IM message element to a message.
 *
 * @param messageBuilder a message builder.
 * @param contact recipient of the message
 * @param payload payload which will be encrypted and signed
 *
 * @return {@link OpenPgpMetadata} about the messages encryption + metadata.
 *
 * @throws SmackException.NotLoggedInException in case we are not logged in
 * @throws PGPException in case something goes wrong during encryption
 * @throws IOException IO is dangerous (we need to read keys)
 */
public OpenPgpMetadata addOxMessage(MessageBuilder messageBuilder, OpenPgpContact contact, List<ExtensionElement> payload)
        throws SmackException.NotLoggedInException, PGPException, IOException {
    return addOxMessage(messageBuilder, Collections.singleton(contact), payload);
}
 
Example 17
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Get our OpenPGP self.
 *
 * @return self TODO javadoc me please
 * @throws SmackException.NotLoggedInException if we are not logged in
 */
public OpenPgpSelf getOpenPgpSelf() throws SmackException.NotLoggedInException {
    throwIfNoProviderSet();
    return new OpenPgpSelf(getJidOrThrow(), provider.getStore());
}
 
Example 18
Source File: OmemoManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Decrypt messages from a MAM query.
 *
 * @param mamQuery The MAM query
 * @return list of decrypted OmemoMessages
 *
 * @throws SmackException.NotLoggedInException if the Manager is not authenticated.
 * @throws IOException if an I/O error occurred.
 */
public List<MessageOrOmemoMessage> decryptMamQueryResult(MamManager.MamQuery mamQuery)
        throws SmackException.NotLoggedInException, IOException {
    return new ArrayList<>(getOmemoService().decryptMamQueryResult(new LoggedInOmemoManager(this), mamQuery));
}
 
Example 19
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Return true, if we have a secret key available, otherwise false.
 *
 * @return true if secret key available
 *
 * @throws SmackException.NotLoggedInException If we are not logged in (we need to know our jid in order to look up
 * our keys in the key store.
 * @throws PGPException in case the keys in the store are damaged somehow.
 * @throws IOException IO is dangerous.
 */
public boolean hasSecretKeysAvailable() throws SmackException.NotLoggedInException, PGPException, IOException {
    throwIfNoProviderSet();
    return getOpenPgpSelf().hasSecretKeyAvailable();
}
 
Example 20
Source File: OpenPgpManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Decrypt and or verify an {@link OpenPgpElement} and return the decrypted {@link OpenPgpMessage}.
 *
 * @param element {@link OpenPgpElement} containing the message.
 * @param sender {@link OpenPgpContact} who sent the message.
 *
 * @return decrypted and/or verified message
 *
 * @throws SmackException.NotLoggedInException in case we aren't logged in (we need to know our jid)
 * @throws IOException IO error (reading keys, streams etc)
 * @throws PGPException in case of an PGP error
 */
public OpenPgpMessage decryptOpenPgpElement(OpenPgpElement element, OpenPgpContact sender)
        throws SmackException.NotLoggedInException, IOException, PGPException {
    return provider.decryptAndOrVerify(getAuthenticatedConnectionOrThrow(), element, getOpenPgpSelf(), sender);
}