Java Code Examples for org.whispersystems.libsignal.SignalProtocolAddress

The following examples show how to use org.whispersystems.libsignal.SignalProtocolAddress. These examples are extracted from open source projects. 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
private OutgoingPushMessageList getEncryptedMessages(PushServiceSocket            socket,
                                                     SignalServiceAddress         recipient,
                                                     Optional<UnidentifiedAccess> unidentifiedAccess,
                                                     long                         timestamp,
                                                     byte[]                       plaintext,
                                                     boolean                      online)
    throws IOException, InvalidKeyException, UntrustedIdentityException
{
  List<OutgoingPushMessage> messages = new LinkedList<>();

  if (!recipient.matches(localAddress) || unidentifiedAccess.isPresent()) {
    messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, SignalServiceAddress.DEFAULT_DEVICE_ID, plaintext));
  }

  for (int deviceId : store.getSubDeviceSessions(recipient.getIdentifier())) {
    if (store.containsSession(new SignalProtocolAddress(recipient.getIdentifier(), deviceId))) {
      messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, deviceId, plaintext));
    }
  }

  return new OutgoingPushMessageList(recipient.getIdentifier(), timestamp, messages, online);
}
 
Example 2
private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
    for (Integer deviceId : deviceIds) {
        SignalProtocolAddress axolotlAddress = new SignalProtocolAddress(bareJid, deviceId);
        IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
        if (Config.X509_VERIFICATION) {
            X509Certificate certificate = store.getFingerprintCertificate(CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()));
            if (certificate != null) {
                Bundle information = CryptoHelper.extractCertificateInformation(certificate);
                try {
                    final String cn = information.getString("subject_cn");
                    final Jid jid = Jid.of(bareJid);
                    Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
                    account.getRoster().getContact(jid).setCommonName(cn);
                } catch (final IllegalArgumentException ignored) {
                    //ignored
                }
            }
        }
        this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
    }
}
 
Example 3
Source Project: Silence   Source File: SmsCipher.java    License: GNU General Public License v3.0 6 votes vote down vote up
public OutgoingTextMessage encrypt(OutgoingTextMessage message)
  throws NoSessionException, UntrustedIdentityException
{
  byte[] paddedBody      = transportDetails.getPaddedMessageBody(message.getMessageBody().getBytes());
  String recipientNumber = message.getRecipients().getPrimaryRecipient().getNumber();

  if (!signalProtocolStore.containsSession(new SignalProtocolAddress(recipientNumber, 1))) {
    throw new NoSessionException("No session for: " + recipientNumber);
  }

  SessionCipher     cipher            = new SessionCipher(signalProtocolStore, new SignalProtocolAddress(recipientNumber, 1));
  CiphertextMessage ciphertextMessage = cipher.encrypt(paddedBody);
  String            encodedCiphertext = new String(transportDetails.getEncodedMessage(ciphertextMessage.serialize()));

  if (ciphertextMessage.getType() == CiphertextMessage.PREKEY_TYPE) {
    return new OutgoingPrekeyBundleMessage(message, encodedCiphertext);
  } else {
    return message.withBody(encodedCiphertext);
  }
}
 
Example 4
Source Project: Silence   Source File: SilenceSessionStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void storeSession(SignalProtocolAddress address, SessionRecord record) {
  synchronized (FILE_LOCK) {
    try {
      MasterCipher     masterCipher = new MasterCipher(masterSecret);
      RandomAccessFile sessionFile  = new RandomAccessFile(getSessionFile(address), "rw");
      FileChannel      out          = sessionFile.getChannel();

      out.position(0);
      writeInteger(CURRENT_VERSION, out);
      writeBlob(masterCipher.encryptBytes(record.serialize()), out);
      out.truncate(out.position());

      sessionFile.close();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }
}
 
Example 5
Source Project: Silence   Source File: KeyExchangeInitiator.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void initiateKeyExchange(Context context, MasterSecret masterSecret, Recipients recipients, int subscriptionId) {
  Recipient         recipient         = recipients.getPrimaryRecipient();
  SessionStore      sessionStore      = new SilenceSessionStore(context, masterSecret, subscriptionId);
  PreKeyStore       preKeyStore       = new SilencePreKeyStore(context, masterSecret, subscriptionId);
  SignedPreKeyStore signedPreKeyStore = new SilencePreKeyStore(context, masterSecret, subscriptionId);
  IdentityKeyStore  identityKeyStore  = new SilenceIdentityKeyStore(context, masterSecret, subscriptionId);

  SessionBuilder    sessionBuilder    = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
                                                           identityKeyStore, new SignalProtocolAddress(recipient.getNumber(), 1));

  if (identityKeyStore.getIdentityKeyPair() != null) {
    KeyExchangeMessage         keyExchangeMessage = sessionBuilder.process();
    String                     serializedMessage  = Base64.encodeBytesWithoutPadding(keyExchangeMessage.serialize());
    OutgoingKeyExchangeMessage textMessage        = new OutgoingKeyExchangeMessage(recipients, serializedMessage, subscriptionId);

    MessageSender.send(context, masterSecret, textMessage, -1, false);
  } else {
    Toast.makeText(context, R.string.VerifyIdentityActivity_you_do_not_have_an_identity_key,
            Toast.LENGTH_LONG).show();
  }
}
 
Example 6
Source Project: mollyim-android   Source File: IdentityUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void saveIdentity(Context context, String user, IdentityKey identityKey) {
  synchronized (SESSION_LOCK) {
    IdentityKeyStore      identityKeyStore = new TextSecureIdentityKeyStore(context);
    SessionStore          sessionStore     = new TextSecureSessionStore(context);
    SignalProtocolAddress address          = new SignalProtocolAddress(user, 1);

    if (identityKeyStore.saveIdentity(address, identityKey)) {
      if (sessionStore.containsSession(address)) {
        SessionRecord sessionRecord = sessionStore.loadSession(address);
        sessionRecord.archiveCurrentState();

        sessionStore.storeSession(address, sessionRecord);
      }
    }
  }
}
 
Example 7
Source Project: Silence   Source File: SmsCipher.java    License: GNU General Public License v3.0 6 votes vote down vote up
public IncomingTextMessage decrypt(Context context, IncomingTextMessage message)
    throws LegacyMessageException, InvalidMessageException, DuplicateMessageException,
           NoSessionException, UntrustedIdentityException
{
  try {
    byte[]        decoded       = transportDetails.getDecodedMessage(message.getMessageBody().getBytes());
    SignalMessage signalMessage = new SignalMessage(decoded);
    SessionCipher sessionCipher = new SessionCipher(signalProtocolStore, new SignalProtocolAddress(message.getSender(), 1));
    byte[]        padded        = sessionCipher.decrypt(signalMessage);
    byte[]        plaintext     = transportDetails.getStrippedPaddingMessageBody(padded);

    if (message.isEndSession() && "TERMINATE".equals(new String(plaintext))) {
      signalProtocolStore.deleteSession(new SignalProtocolAddress(message.getSender(), 1));
    }

    return message.withMessageBody(new String(plaintext));
  } catch (IOException | IllegalArgumentException | NullPointerException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 8
Source Project: bcm-android   Source File: IdentityUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void saveIdentity(Context context, AccountContext accountContext, String number, IdentityKey identityKey) {
    synchronized (SESSION_LOCK) {
        IdentityKeyStore identityKeyStore = new TextSecureIdentityKeyStore(context, accountContext);
        SessionStore sessionStore = new TextSecureSessionStore(context, accountContext);
        SignalProtocolAddress address = new SignalProtocolAddress(number, 1);

        if (identityKeyStore.saveIdentity(address, identityKey)) {
            if (sessionStore.containsSession(address)) {
                SessionRecord sessionRecord = sessionStore.loadSession(address);
                sessionRecord.archiveCurrentState();

                sessionStore.storeSession(address, sessionRecord);
            }
        }
    }
}
 
Example 9
private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
    List<Integer> devices = new ArrayList<>();
    String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
    String[] selectionArgs = {account.getUuid(),
            contact.getName()};
    Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
            columns,
            SQLiteAxolotlStore.ACCOUNT + " = ? AND "
                    + SQLiteAxolotlStore.NAME + " = ?",
            selectionArgs,
            null, null, null);

    while (cursor.moveToNext()) {
        devices.add(cursor.getInt(
                cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
    }

    cursor.close();
    return devices;
}
 
Example 10
@Override
public void storeSession(@NonNull SignalProtocolAddress address, @NonNull SessionRecord record) {
    synchronized (FILE_LOCK) {
        try {
            RandomAccessFile sessionFile = new RandomAccessFile(getSessionFile(address), "rw");
            FileChannel out = sessionFile.getChannel();

            out.position(0);
            writeInteger(CURRENT_VERSION, out);
            writeBlob(record.serialize(), out);
            out.truncate(out.position());

            sessionFile.close();
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }
}
 
Example 11
public void processPostponed() {
    if (postponedSessions.size() > 0) {
        if (axolotlStore.flushPreKeys()) {
            publishBundlesIfNeeded(false, false);
        }
    }
    final Iterator<XmppAxolotlSession> iterator = postponedSessions.iterator();
    while (iterator.hasNext()) {
        final XmppAxolotlSession session = iterator.next();
        if (trustedOrPreviouslyResponded(session)) {
            completeSession(session);
        }
        iterator.remove();
    }
    final Iterator<SignalProtocolAddress> postponedHealingAttemptsIterator = postponedHealing.iterator();
    while (postponedHealingAttemptsIterator.hasNext()) {
        notifyRequiresHealing(postponedHealingAttemptsIterator.next());
        postponedHealingAttemptsIterator.remove();
    }
}
 
Example 12
public void migrateSessions() {
    synchronized (FILE_LOCK) {
        File directory = getSessionDirectory();

        for (File session : directory.listFiles()) {
            if (session.isFile()) {
                SignalProtocolAddress address = getAddressName(session);

                if (address != null) {
                    SessionRecord sessionRecord = loadSession(address);
                    storeSession(address, sessionRecord);
                }
            }
        }
    }
}
 
Example 13
private @Nullable
SignalProtocolAddress getAddressName(File sessionFile) {
    try {
        String[] parts = sessionFile.getName().split("[.]");

        int deviceId;

        if (parts.length > 1) deviceId = Integer.parseInt(parts[1]);
        else deviceId = SignalServiceAddress.DEFAULT_DEVICE_ID;

        return new SignalProtocolAddress(parts[0], deviceId);
    } catch (NumberFormatException e) {
        Log.w(TAG, e);
        return null;
    }
}
 
Example 14
Source Project: signald   Source File: JsonSessionStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonSessionStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    Map<SignalProtocolAddress, byte[]> sessionMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode session : node) {
            String sessionName = session.get("name").asText();
            try {
                sessionMap.put(new SignalProtocolAddress(sessionName, session.get("deviceId").asInt()), Base64.decode(session.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding session for: %s", sessionName));
            }
        }
    }

    JsonSessionStore sessionStore = new JsonSessionStore();
    sessionStore.addSessions(sessionMap);

    return sessionStore;

}
 
Example 15
Source Project: signald   Source File: JsonIdentityKeyStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
    // TODO implement possibility for different handling of incoming/outgoing trust decisions
    List<Identity> identities = trustedKeys.get(address.getName());
    if (identities == null) {
        // Trust on first use
        return true;
    }

    for (Identity id : identities) {
        if (id.identityKey.equals(identityKey)) {
            return id.isTrusted();
        }
    }

    return false;
}
 
Example 16
private OutgoingPushMessageList getEncryptedMessages(PushServiceSocket            socket,
                                                     SignalServiceAddress         recipient,
                                                     Optional<UnidentifiedAccess> unidentifiedAccess,
                                                     long                         timestamp,
                                                     byte[]                       plaintext,
                                                     boolean                      online)
    throws IOException, InvalidKeyException, UntrustedIdentityException
{
  List<OutgoingPushMessage> messages = new LinkedList<>();

  if (!recipient.matches(localAddress) || unidentifiedAccess.isPresent()) {
    messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, SignalServiceAddress.DEFAULT_DEVICE_ID, plaintext));
  }

  for (int deviceId : store.getSubDeviceSessions(recipient.getIdentifier())) {
    if (store.containsSession(new SignalProtocolAddress(recipient.getIdentifier(), deviceId))) {
      messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, deviceId, plaintext));
    }
  }

  return new OutgoingPushMessageList(recipient.getIdentifier(), timestamp, messages, online);
}
 
Example 17
private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, SignalProtocolAddress contact) {
    List<Integer> devices = new ArrayList<>();
    String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
    String[] selectionArgs = {account.getUuid(),
            contact.getName()};
    Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
            columns,
            SQLiteAxolotlStore.ACCOUNT + " = ? AND "
                    + SQLiteAxolotlStore.NAME + " = ?",
            selectionArgs,
            null, null, null);

    while (cursor.moveToNext()) {
        devices.add(cursor.getInt(
                cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
    }

    cursor.close();
    return devices;
}
 
Example 18
/**
 * Save a remote client's identity key
 * <p/>
 * Store a remote client's identity key as trusted.
 *
 * @param address     The address of the remote client.
 * @param identityKey The remote client's identity key.
 * @return true on success
 */
@Override
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey) {
	if (!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, address.getName()).contains(identityKey)) {
		String fingerprint = CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize());
		FingerprintStatus status = getFingerprintStatus(fingerprint);
		if (status == null) {
			if (mXmppConnectionService.blindTrustBeforeVerification() && !account.getAxolotlService().hasVerifiedKeys(address.getName())) {
				Log.d(Config.LOGTAG,account.getJid().asBareJid()+": blindly trusted "+fingerprint+" of "+address.getName());
				status = FingerprintStatus.createActiveTrusted();
			} else {
				status = FingerprintStatus.createActiveUndecided();
			}
		} else {
			status = status.toActive();
		}
		mXmppConnectionService.databaseBackend.storeIdentityKey(account, address.getName(), identityKey, status);
		trustCache.remove(fingerprint);
	}
	return true;
}
 
Example 19
private static SignalProtocolAddress getPreferredProtocolAddress(SignalProtocolStore store, SignalServiceAddress address, int sourceDevice) {
  SignalProtocolAddress uuidAddress = address.getUuid().isPresent() ? new SignalProtocolAddress(address.getUuid().get().toString(), sourceDevice) : null;
  SignalProtocolAddress e164Address = address.getNumber().isPresent() ? new SignalProtocolAddress(address.getNumber().get(), sourceDevice) : null;

  if (uuidAddress != null && store.containsSession(uuidAddress)) {
    return uuidAddress;
  } else if (e164Address != null && store.containsSession(e164Address)) {
    return e164Address;
  } else {
    return new SignalProtocolAddress(address.getLegacyIdentifier(), sourceDevice);
  }
}
 
Example 20
Source Project: Conversations   Source File: AxolotlService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean fetchMapHasErrors(List<Jid> jids) {
    for (Jid jid : jids) {
        if (deviceIds.get(jid) != null) {
            for (Integer foreignId : this.deviceIds.get(jid)) {
                SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
                if (fetchStatusMap.getAll(address.getName()).containsValue(FetchStatus.ERROR)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 21
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
  synchronized (LOCK) {
    if (DatabaseFactory.getRecipientDatabase(context).containsPhoneOrUuid(address.getName())) {
      IdentityDatabase identityDatabase = DatabaseFactory.getIdentityDatabase(context);
      RecipientId      ourRecipientId   = Recipient.self().getId();
      RecipientId      theirRecipientId = Recipient.external(context, address.getName()).getId();

      if (ourRecipientId.equals(theirRecipientId)) {
        return identityKey.equals(IdentityKeyUtil.getIdentityKey(context));
      }

      switch (direction) {
        case SENDING:   return isTrustedForSending(identityKey, identityDatabase.getIdentity(theirRecipientId));
        case RECEIVING: return true;
        default:        throw new AssertionError("Unknown direction: " + direction);
      }
    } else {
      Log.w(TAG, "Tried to check if identity is trusted for " + address.getName() + ", but no matching recipient existed!");
      switch (direction) {
        case SENDING:   return false;
        case RECEIVING: return true;
        default:        throw new AssertionError("Unknown direction: " + direction);
      }
    }
  }
}
 
Example 22
private static SignalProtocolAddress getPreferredProtocolAddress(SignalProtocolStore store, SignalServiceAddress address, int sourceDevice) {
  SignalProtocolAddress uuidAddress = address.getUuid().isPresent() ? new SignalProtocolAddress(address.getUuid().get().toString(), sourceDevice) : null;
  SignalProtocolAddress e164Address = address.getNumber().isPresent() ? new SignalProtocolAddress(address.getNumber().get(), sourceDevice) : null;

  if (uuidAddress != null && store.containsSession(uuidAddress)) {
    return uuidAddress;
  } else if (e164Address != null && store.containsSession(e164Address)) {
    return e164Address;
  } else {
    return new SignalProtocolAddress(address.getIdentifier(), sourceDevice);
  }
}
 
Example 23
private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
    SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
    Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName());
    Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName());
    if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
        FetchStatus report = null;
        if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
            report = FetchStatus.SUCCESS;
        } else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
            report = FetchStatus.SUCCESS_VERIFIED;
        } else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
            report = FetchStatus.SUCCESS_TRUSTED;
        } else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
            report = FetchStatus.ERROR;
        }
        mXmppConnectionService.keyStatusUpdated(report);
    }
    if (Config.REMOVE_BROKEN_DEVICES) {
        Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
        boolean publish = false;
        for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
            int id = entry.getKey();
            if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
                publish = true;
                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
            }
        }
        if (publish) {
            publishOwnDeviceId(ownDeviceIds);
        }
    }
}
 
Example 24
private byte[] decrypt(SignalServiceProtos.Envelope envelope, byte[] ciphertext)
    throws InvalidVersionException, InvalidMessageException, InvalidKeyException,
           DuplicateMessageException, InvalidKeyIdException, UntrustedIdentityException,
           LegacyMessageException, NoSessionException
{
  SignalProtocolAddress sourceAddress = new SignalProtocolAddress(envelope.getSource(), envelope.getSourceDevice());
  SessionCipher         sessionCipher = new SessionCipher(signalProtocolStore, sourceAddress);

  byte[] paddedMessage;

  if (envelope.getType() == Type.PREKEY_BUNDLE) {
    paddedMessage = sessionCipher.decrypt(new PreKeySignalMessage(ciphertext));
      //纠正remote register id
      SessionRecord sessionRecord = signalProtocolStore.loadSession(sourceAddress);
      if (sessionRecord.getSessionState().getRemoteRegistrationId() == 0) {
          sessionRecord.getSessionState().setRemoteRegistrationId(envelope.getSourceRegistration());
          signalProtocolStore.storeSession(sourceAddress, sessionRecord);
      }

  } else if (envelope.getType() == Type.CIPHERTEXT) {
    paddedMessage = sessionCipher.decrypt(new SignalMessage(ciphertext));
  } else {
    throw new InvalidMessageException("Unknown type: " + envelope.getType());
  }

  PushTransportDetails transportDetails = new PushTransportDetails(sessionCipher.getSessionVersion());
  return transportDetails.getStrippedPaddingMessageBody(paddedMessage);
}
 
Example 25
public boolean saveIdentity(SignalProtocolAddress address, IdentityKey identityKey, boolean nonBlockingApproval) {
    synchronized (LOCK) {
        IdentityRepo identityRepo = Repository.getIdentityRepo(accountContext);
        Address signalAddress = Address.from(accountContext, address.getName());
        IdentityRecord identityRecord = identityRepo.getIdentityRecord(signalAddress.serialize());

        if (identityRecord == null) {
            Log.w(TAG, "Saving new identity...");
            identityRepo.saveIdentity(signalAddress.serialize(), identityKey, IdentityRepo.VerifiedStatus.DEFAULT, true, System.currentTimeMillis(), nonBlockingApproval);
            return false;
        }

        if (!identityRecord.getIdentityKey().equals(identityKey)) {
            Log.w(TAG, "Replacing existing identity...");
            IdentityRepo.VerifiedStatus verifiedStatus;

            if (identityRecord.getVerifyStatus() == IdentityRepo.VerifiedStatus.VERIFIED ||
                    identityRecord.getVerifyStatus() == IdentityRepo.VerifiedStatus.UNVERIFIED) {
                verifiedStatus = IdentityRepo.VerifiedStatus.UNVERIFIED;
            } else {
                verifiedStatus = IdentityRepo.VerifiedStatus.DEFAULT;
            }

            identityRepo.saveIdentity(signalAddress.serialize(), identityKey, verifiedStatus, false, System.currentTimeMillis(), nonBlockingApproval);

            SessionUtil.archiveSiblingSessions(context, accountContext, address);
            return true;
        }

        if (isNonBlockingApprovalRequired(identityRecord)) {
            Log.w(TAG, "Setting approval status...");

            identityRepo.setApproval(signalAddress.serialize(), nonBlockingApproval);
            return false;
        }

        return false;
    }
}
 
Example 26
Source Project: Silence   Source File: KeyExchangeInitiator.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean hasInitiatedSession(Context context, MasterSecret masterSecret,
                                           Recipients recipients, int subscriptionId)
{
  Recipient     recipient     = recipients.getPrimaryRecipient();
  SessionStore  sessionStore  = new SilenceSessionStore(context, masterSecret, subscriptionId);
  SessionRecord sessionRecord = sessionStore.loadSession(new SignalProtocolAddress(recipient.getNumber(), 1));

  return sessionRecord.getSessionState().hasPendingKeyExchange();
}
 
Example 27
@Override
public void deleteAllSessions(String name) {
    List<Integer> devices = getSubDeviceSessions(name);

    deleteSession(new SignalProtocolAddress(name, SignalServiceAddress.DEFAULT_DEVICE_ID));

    for (int device : devices) {
        deleteSession(new SignalProtocolAddress(name, device));
    }
}
 
Example 28
Source Project: Smack   Source File: SignalOmemoService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected SignalOmemoRatchet instantiateOmemoRatchet(
        OmemoManager manager,
        OmemoStore<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord, SessionRecord,
                SignalProtocolAddress, ECPublicKey, PreKeyBundle, SessionCipher> store) {

    return new SignalOmemoRatchet(manager, getOmemoStoreBackend());
}
 
Example 29
public void storeSession(Account account, SignalProtocolAddress contact, SessionRecord session) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(SQLiteAxolotlStore.NAME, contact.getName());
    values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
    values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
    values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
    db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
}
 
Example 30
Source Project: signald   Source File: JsonSessionStore.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized SessionRecord loadSession(SignalProtocolAddress remoteAddress) {
    try {
        if (containsSession(remoteAddress)) {
            return new SessionRecord(sessions.get(remoteAddress));
        } else {
            return new SessionRecord();
        }
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}