Java Code Examples for org.whispersystems.libsignal.IdentityKey

The following examples show how to use org.whispersystems.libsignal.IdentityKey. 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 boolean isTrustedForSending(IdentityKey identityKey, IdentityRecord identityRecord) {
    if (identityRecord == null) {
        Log.w(TAG, "Nothing here, returning true...");
        return true;
    }

    if (!identityKey.equals(identityRecord.getIdentityKey())) {
        Log.w(TAG, "Identity keys don't match...");
        return false;
    }

    if (identityRecord.getVerifyStatus() == IdentityRepo.VerifiedStatus.UNVERIFIED) {
        Log.w(TAG, "Needs unverified approval!");
        return false;
    }

    if (isNonBlockingApprovalRequired(identityRecord)) {
        Log.w(TAG, "Needs non-blocking approval!");
        return false;
    }

    return true;
}
 
Example 2
@Override
public boolean isTrustedIdentity(SignalProtocolAddress address, IdentityKey identityKey, Direction direction) {
    // TODO implement possibility for different handling of incoming/outgoing trust decisions
    SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
    boolean trustOnFirstUse = true;

    for (Identity id : identities) {
        if (!id.address.matches(serviceAddress)) {
            continue;
        }

        if (id.identityKey.equals(identityKey)) {
            return id.isTrusted();
        } else {
            trustOnFirstUse = false;
        }
    }

    return trustOnFirstUse;
}
 
Example 3
public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
    Set<IdentityKey> identityKeys = new HashSet<>();
    Cursor cursor = getIdentityKeyCursor(account, name, false);

    while (cursor.moveToNext()) {
        if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
            continue;
        }
        try {
            String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
            if (key != null) {
                identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
            } else {
                Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().asBareJid() + ", address: " + name);
            }
        } catch (InvalidKeyException e) {
            Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().asBareJid() + ", address: " + name);
        }
    }
    cursor.close();

    return identityKeys;
}
 
Example 4
public void testDifferentVersionsMakeSameFingerPrintsButDifferentScannable() throws Exception {
  IdentityKey aliceIdentityKey = new IdentityKey(ALICE_IDENTITY, 0);
  IdentityKey bobIdentityKey   = new IdentityKey(BOB_IDENTITY, 0);
  byte[]      aliceStableId    = "+14152222222".getBytes();
  byte[]      bobStableId      = "+14153333333".getBytes();

  NumericFingerprintGenerator generator          = new NumericFingerprintGenerator(5200);

  Fingerprint aliceFingerprintV1 = generator.createFor(VERSION_1,
                                                       aliceStableId, aliceIdentityKey,
                                                       bobStableId, bobIdentityKey);

  Fingerprint aliceFingerprintV2 = generator.createFor(VERSION_2,
                                                       aliceStableId, aliceIdentityKey,
                                                       bobStableId, bobIdentityKey);


  assertTrue(aliceFingerprintV1.getDisplayableFingerprint().getDisplayText().equals(
             aliceFingerprintV2.getDisplayableFingerprint().getDisplayText()));

  assertFalse(Arrays.equals(aliceFingerprintV1.getScannableFingerprint().getSerialized(),
                            aliceFingerprintV2.getScannableFingerprint().getSerialized()));
}
 
Example 5
private AliceSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourBaseKey,
                                      IdentityKey theirIdentityKey, ECPublicKey theirSignedPreKey,
                                      ECPublicKey theirRatchetKey, Optional<ECPublicKey> theirOneTimePreKey)
{
  this.ourIdentityKey     = ourIdentityKey;
  this.ourBaseKey         = ourBaseKey;
  this.theirIdentityKey   = theirIdentityKey;
  this.theirSignedPreKey  = theirSignedPreKey;
  this.theirRatchetKey    = theirRatchetKey;
  this.theirOneTimePreKey = theirOneTimePreKey;

  if (ourIdentityKey == null || ourBaseKey == null || theirIdentityKey == null ||
      theirSignedPreKey == null || theirRatchetKey == null || theirOneTimePreKey == null)
  {
    throw new IllegalArgumentException("Null values!");
  }
}
 
Example 6
public void registerPreKeys(IdentityKey identityKey,
                            SignedPreKeyRecord signedPreKey,
                            List<PreKeyRecord> records)
    throws IOException
{
  List<PreKeyEntity> entities = new LinkedList<>();

  for (PreKeyRecord record : records) {
    PreKeyEntity entity = new PreKeyEntity(record.getId(),
                                           record.getKeyPair().getPublicKey());

    entities.add(entity);
  }

  SignedPreKeyEntity signedPreKeyEntity = new SignedPreKeyEntity(signedPreKey.getId(),
                                                                 signedPreKey.getKeyPair().getPublicKey(),
                                                                 signedPreKey.getSignature());

  makeServiceRequest(String.format(PREKEY_PATH, ""), "PUT",
                     JsonUtil.toJson(new PreKeyState(entities, signedPreKeyEntity, identityKey)));
}
 
Example 7
private void saveIdentityInternal(@NonNull RecipientId recipientId, IdentityKey identityKey, VerifiedStatus verifiedStatus,
                                  boolean firstUse, long timestamp, boolean nonBlockingApproval)
{
  SQLiteDatabase database          = databaseHelper.getWritableDatabase();
  String         identityKeyString = Base64.encodeBytes(identityKey.serialize());

  ContentValues contentValues = new ContentValues();
  contentValues.put(RECIPIENT_ID, recipientId.serialize());
  contentValues.put(IDENTITY_KEY, identityKeyString);
  contentValues.put(TIMESTAMP, timestamp);
  contentValues.put(VERIFIED, verifiedStatus.toInt());
  contentValues.put(NONBLOCKING_APPROVAL, nonBlockingApproval ? 1 : 0);
  contentValues.put(FIRST_USE, firstUse ? 1 : 0);

  database.replace(TABLE_NAME, null, contentValues);

  EventBus.getDefault().post(new IdentityRecord(recipientId, identityKey, verifiedStatus,
      firstUse, timestamp, nonBlockingApproval));
}
 
Example 8
Source Project: signald   Source File: IdentityKeyStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public IdentityKey getIdentity(SignalProtocolAddress address) {
    List<IdentityKeyStore.Identity> identities = trustedKeys.get(address.getName());
    if (identities == null || identities.size() == 0) {
        return null;
    }

    long maxDate = 0;
    IdentityKeyStore.Identity maxIdentity = null;
    for (IdentityKeyStore.Identity id : identities) {
        final long time = id.getDateAdded().getTime();
        if (maxIdentity == null || maxDate <= time) {
            maxDate = time;
            maxIdentity = id;
        }
    }
    return maxIdentity.getIdentityKey();
}
 
Example 9
private void setIdentityKey(Recipient recipient, String identityKeyValue) {
  try {
    if (TextUtils.isEmpty(identityKeyValue)) {
      Log.w(TAG, "Identity key is missing on profile!");
      return;
    }

    IdentityKey identityKey = new IdentityKey(Base64.decode(identityKeyValue), 0);

    if (!DatabaseFactory.getIdentityDatabase(context)
                        .getIdentity(recipient.getId())
                        .isPresent())
    {
      Log.w(TAG, "Still first use...");
      return;
    }

    IdentityUtil.saveIdentity(context, recipient.requireServiceId(), identityKey);
  } catch (InvalidKeyException | IOException e) {
    Log.w(TAG, e);
  }
}
 
Example 10
BobSignalProtocolParameters(IdentityKeyPair ourIdentityKey, ECKeyPair ourSignedPreKey,
                            ECKeyPair ourRatchetKey, Optional<ECKeyPair> ourOneTimePreKey,
                            IdentityKey theirIdentityKey, ECPublicKey theirBaseKey)
{
  this.ourIdentityKey   = ourIdentityKey;
  this.ourSignedPreKey  = ourSignedPreKey;
  this.ourRatchetKey    = ourRatchetKey;
  this.ourOneTimePreKey = ourOneTimePreKey;
  this.theirIdentityKey = theirIdentityKey;
  this.theirBaseKey     = theirBaseKey;

  if (ourIdentityKey == null || ourSignedPreKey == null || ourRatchetKey == null ||
      ourOneTimePreKey == null || theirIdentityKey == null || theirBaseKey == null)
  {
    throw new IllegalArgumentException("Null value!");
  }
}
 
Example 11
Source Project: signald   Source File: JsonIdentityKeyStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public IdentityKey getIdentity(SignalProtocolAddress address) {
    List<Identity> identities = trustedKeys.get(address.getName());
    if (identities == null || identities.size() == 0) {
        return null;
    }

    long maxDate = 0;
    Identity maxIdentity = null;
    for (Identity id : identities) {
        final long time = id.getDateAdded().getTime();
        if (maxIdentity == null || maxDate <= time) {
            maxDate = time;
            maxIdentity = id;
        }
    }
    return maxIdentity.getIdentityKey();
}
 
Example 12
Source Project: bcm-android   Source File: WebRtcViewModel.java    License: GNU General Public License v3.0 6 votes vote down vote up
public WebRtcViewModel(@NonNull State state,
                       boolean videoCall,
                       @Nullable Recipient recipient,
                       @Nullable IdentityKey identityKey,
                       @NonNull CameraState localCameraState,
                       @Nullable SurfaceViewRenderer localRenderer,
                       @Nullable SurfaceViewRenderer remoteRenderer,
                       boolean remoteVideoEnabled,
                       boolean isBluetoothAvailable,
                       boolean isMicrophoneEnabled) {
    this.state = state;
    this.videoCall = videoCall;
    this.recipient = recipient;
    this.localCameraState = localCameraState;
    this.localRenderer = localRenderer;
    this.remoteRenderer = remoteRenderer;
    this.identityKey = identityKey;
    this.remoteVideoEnabled = remoteVideoEnabled;
    this.isBluetoothAvailable = isBluetoothAvailable;
    this.isMicrophoneEnabled = isMicrophoneEnabled;
}
 
Example 13
/**
 * Generate a scannable and displayable fingerprint.
 *
 * @param version The version of fingerprint you are generating.
 * @param localStableIdentifier The client's "stable" identifier.
 * @param localIdentityKey The client's identity key.
 * @param remoteStableIdentifier The remote party's "stable" identifier.
 * @param remoteIdentityKey The remote party's identity key.
 * @return A unique fingerprint for this conversation.
 */
@Override
public Fingerprint createFor(int version,
                             byte[] localStableIdentifier,
                             final IdentityKey localIdentityKey,
                             byte[] remoteStableIdentifier,
                             final IdentityKey remoteIdentityKey)
{
  return createFor(version,
                   localStableIdentifier,
                   new LinkedList<IdentityKey>() {{
                     add(localIdentityKey);
                   }},
                   remoteStableIdentifier,
                   new LinkedList<IdentityKey>() {{
                     add(remoteIdentityKey);
                   }});
}
 
Example 14
Source Project: signald   Source File: JsonIdentityKeyStore.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Adds or updates the given identityKey for the user name and sets the trustLevel and added timestamp.
 *
 * @param name        User name, i.e. phone number
 * @param identityKey The user's public key
 * @param trustLevel
 * @param added       Added timestamp, if null and the key is newly added, the current time is used.
 */
public boolean saveIdentity(String name, IdentityKey identityKey, TrustLevel trustLevel, Date added) {
    List<Identity> identities = trustedKeys.get(name);
    if (identities == null) {
        identities = new ArrayList<>();
        trustedKeys.put(name, identities);
    } else {
        for (Identity id : identities) {
            if (!id.identityKey.equals(identityKey))
                continue;

            if (id.trustLevel.compareTo(trustLevel) < 0) {
                id.trustLevel = trustLevel;
            }
            if (added != null) {
                id.added = added;
            }
            return true;
        }
    }
    identities.add(new Identity(identityKey, trustLevel, added != null ? added : new Date()));
    return false;
}
 
Example 15
Source Project: Silence   Source File: MessagingDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void addMismatchedIdentity(long messageId, long recipientId, IdentityKey identityKey) {
  try {
    addToDocument(messageId, MISMATCHED_IDENTITIES,
                  new IdentityKeyMismatch(recipientId, identityKey),
                  IdentityKeyMismatchList.class);
  } catch (IOException e) {
    Log.w(TAG, e);
  }
}
 
Example 16
public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, byte[] serialized, IdentityKey identityKey) throws InvalidMessageException {
  try {
    SignalProtos.DeviceConsistencyCodeMessage message = SignalProtos.DeviceConsistencyCodeMessage.parseFrom(serialized);
    byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKey.getPublicKey(), commitment.toByteArray(), message.getSignature().toByteArray());

    this.generation = message.getGeneration();
    this.signature  = new DeviceConsistencySignature(message.getSignature().toByteArray(), vrfOutputBytes);
    this.serialized = serialized;
  } catch (InvalidProtocolBufferException | InvalidKeyException | VrfSignatureVerificationFailedException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 17
public void removeMismatchedIdentity(long messageId, @NonNull RecipientId recipientId, IdentityKey identityKey) {
  try {
    removeFromDocument(messageId, MISMATCHED_IDENTITIES,
                       new IdentityKeyMismatch(recipientId, identityKey),
                       IdentityKeyMismatchList.class);
  } catch (IOException e) {
    Log.w(TAG, e);
  }
}
 
Example 18
Source Project: Silence   Source File: IdentityKeyMismatch.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public IdentityKey deserialize(JsonParser jsonParser, DeserializationContext ctxt)
    throws IOException
{
  try {
    return new IdentityKey(Base64.decode(jsonParser.getValueAsString()), 0);
  } catch (InvalidKeyException e) {
    Log.w(TAG, e);
    throw new IOException(e);
  }
}
 
Example 19
public void setVerified(@NonNull RecipientId recipientId, IdentityKey identityKey, VerifiedStatus verifiedStatus) {
  SQLiteDatabase database = databaseHelper.getWritableDatabase();

  ContentValues contentValues = new ContentValues(1);
  contentValues.put(VERIFIED, verifiedStatus.toInt());

  int updated = database.update(TABLE_NAME, contentValues, RECIPIENT_ID + " = ? AND " + IDENTITY_KEY + " = ?",
                                new String[] {recipientId.serialize(), Base64.encodeBytes(identityKey.serialize())});

  if (updated > 0) {
    Optional<IdentityRecord> record = getIdentity(recipientId);
    if (record.isPresent()) EventBus.getDefault().post(record.get());
    DatabaseFactory.getRecipientDatabase(context).markDirty(recipientId, RecipientDatabase.DirtyState.UPDATE);
  }
}
 
Example 20
private boolean hasMatchingKey(@NonNull RecipientId id, IdentityKey identityKey) {
  SQLiteDatabase db    = databaseHelper.getReadableDatabase();
  String         query = RECIPIENT_ID + " = ? AND " + IDENTITY_KEY + " = ?";
  String[]       args  = new String[]{id.serialize(), Base64.encodeBytes(identityKey.serialize())};

  try (Cursor cursor = db.query(TABLE_NAME, null, query, args, null, null, null)) {
    return cursor != null && cursor.moveToFirst();
  }
}
 
Example 21
private boolean hasMatchingStatus(@NonNull RecipientId id, IdentityKey identityKey, VerifiedStatus verifiedStatus) {
  SQLiteDatabase db    = databaseHelper.getReadableDatabase();
  String         query = RECIPIENT_ID + " = ? AND " + IDENTITY_KEY + " = ? AND " + VERIFIED + " = ?";
  String[]       args  = new String[]{id.serialize(), Base64.encodeBytes(identityKey.serialize()), String.valueOf(verifiedStatus.toInt())};

  try (Cursor cursor = db.query(TABLE_NAME, null, query, args, null, null, null)) {
    return cursor != null && cursor.moveToFirst();
  }
}
 
Example 22
private IdentityRecord(@NonNull RecipientId recipientId,
                       IdentityKey identitykey, VerifiedStatus verifiedStatus,
                       boolean firstUse, long timestamp, boolean nonblockingApproval)
{
  this.recipientId         = recipientId;
  this.identitykey         = identitykey;
  this.verifiedStatus      = verifiedStatus;
  this.firstUse            = firstUse;
  this.timestamp           = timestamp;
  this.nonblockingApproval = nonblockingApproval;
}
 
Example 23
public static Intent newIntent(@NonNull Context context,
                               @NonNull RecipientId recipientId,
                               @NonNull IdentityKey identityKey,
                               boolean verified)
{
  Intent intent = new Intent(context, VerifyIdentityActivity.class);

  intent.putExtra(RECIPIENT_EXTRA, recipientId);
  intent.putExtra(IDENTITY_EXTRA, new IdentityKeyParcelable(identityKey));
  intent.putExtra(VERIFIED_EXTRA, verified);

  return intent;
}
 
Example 24
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 25
Source Project: Smack   Source File: SignalOmemoRatchet.java    License: Apache License 2.0 5 votes vote down vote up
SignalOmemoRatchet(OmemoManager omemoManager,
                          OmemoStore<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord,
                                         SessionRecord, SignalProtocolAddress, ECPublicKey, PreKeyBundle,
                                         SessionCipher> store) {
    super(omemoManager, store);
    this.storeConnector = new SignalOmemoStoreConnector(omemoManager, store);
}
 
Example 26
Source Project: Silence   Source File: KeyExchangeMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public KeyExchangeMessage(byte[] serialized)
    throws InvalidMessageException, InvalidVersionException, LegacyMessageException
{
  try {
    byte[][] parts        = ByteUtil.split(serialized, 1, serialized.length - 1);
    this.version          = ByteUtil.highBitsToInt(parts[0][0]);
    this.supportedVersion = ByteUtil.lowBitsToInt(parts[0][0]);

    if (this.version < CiphertextMessage.CURRENT_VERSION) {
      throw new LegacyMessageException("Unsupported legacy version: " + this.version);
    }

    if (this.version > CiphertextMessage.CURRENT_VERSION) {
      throw new InvalidVersionException("Unknown version: " + this.version);
    }

    SignalProtos.KeyExchangeMessage message = SignalProtos.KeyExchangeMessage.parseFrom(parts[1]);

    if (!message.hasId()           || !message.hasBaseKey()     ||
        !message.hasRatchetKey()   || !message.hasIdentityKey() ||
        !message.hasBaseKeySignature())
    {
      throw new InvalidMessageException("Some required fields missing!");
    }

    this.sequence         = message.getId() >> 5;
    this.flags            = message.getId() & 0x1f;
    this.serialized       = serialized;
    this.baseKey          = Curve.decodePoint(message.getBaseKey().toByteArray(), 0);
    this.baseKeySignature = message.getBaseKeySignature().toByteArray();
    this.ratchetKey       = Curve.decodePoint(message.getRatchetKey().toByteArray(), 0);
    this.identityKey      = new IdentityKey(message.getIdentityKey().toByteArray(), 0);
  } catch (InvalidKeyException | IOException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 27
public static void generateIdentityKeys(Context context) {
  ECKeyPair    djbKeyPair     = Curve.generateKeyPair();
  IdentityKey  djbIdentityKey = new IdentityKey(djbKeyPair.getPublicKey());
  ECPrivateKey djbPrivateKey  = djbKeyPair.getPrivateKey();

  save(context, IDENTITY_PUBLIC_KEY_PREF, Base64.encodeBytes(djbIdentityKey.serialize()));
  save(context, IDENTITY_PRIVATE_KEY_PREF, Base64.encodeBytes(djbPrivateKey.serialize()));
}
 
Example 28
public IdentityKeyParcelable(Parcel in) throws InvalidKeyException {
  int    serializedLength = in.readInt();
  byte[] serialized       = new byte[serializedLength];

  in.readByteArray(serialized);
  this.identityKey = new IdentityKey(serialized, 0);
}
 
Example 29
public IdentityKey getLocalIdentityKey() {
  try {
    return new IdentityKey(this.sessionStructure.getLocalIdentityPublic().toByteArray(), 0);
  } catch (InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 30
Source Project: Conversations   Source File: AxolotlService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
    Set<IdentityKey> keys = new HashSet<>();
    for (Jid jid : jids) {
        keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toString(), status));
    }
    return keys;
}