org.whispersystems.libsignal.protocol.PreKeySignalMessage Java Examples

The following examples show how to use org.whispersystems.libsignal.protocol.PreKeySignalMessage. 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: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleUntrustedIdentityMessage(@NonNull SignalServiceProtos.Envelope envelope) {
    ALog.i(TAG, "handleUntrustedIdentityMessage");
    try {
        PrivateChatRepo chatRepo = repository.getChatRepo();
        Address sourceAddress = Address.from(accountContext, envelope.getSource());
        byte[] serialized = envelope.hasLegacyMessage() ? envelope.getLegacyMessage().toByteArray() : envelope.getContent().toByteArray();
        PreKeySignalMessage whisperMessage = new PreKeySignalMessage(serialized);
        String encoded = Base64.encodeBytes(serialized);

        IncomingTextMessage textMessage = new IncomingTextMessage(sourceAddress,
                envelope.getSourceDevice(),
                envelope.getTimestamp(), encoded,
                Optional.absent(), 0);

        IncomingPreKeyBundleMessage bundleMessage = new IncomingPreKeyBundleMessage(textMessage, encoded, envelope.hasLegacyMessage());

        chatRepo.insertIncomingTextMessage(bundleMessage);
    } catch (InvalidMessageException | InvalidVersionException e) {
        throw new AssertionError(e);
    }
}
 
Example #2
Source File: SmsCipher.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public IncomingEncryptedMessage decrypt(Context context, IncomingPreKeyBundleMessage message)
    throws InvalidVersionException, InvalidMessageException, DuplicateMessageException,
           UntrustedIdentityException, LegacyMessageException
{
  try {
    byte[]              decoded       = transportDetails.getDecodedMessage(message.getMessageBody().getBytes());
    PreKeySignalMessage preKeyMessage = new PreKeySignalMessage(decoded);
    SessionCipher       sessionCipher = new SessionCipher(signalProtocolStore, new SignalProtocolAddress(message.getSender(), 1));
    byte[]              padded        = sessionCipher.decrypt(preKeyMessage);
    byte[]              plaintext     = transportDetails.getStrippedPaddingMessageBody(padded);

    return new IncomingEncryptedMessage(message, new String(plaintext));
  } catch (IOException | InvalidKeyException | InvalidKeyIdException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example #3
Source File: SessionBuilder.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Build a new session from a received {@link PreKeySignalMessage}.
 *
 * After a session is constructed in this way, the embedded {@link SignalMessage}
 * can be decrypted.
 *
 * @param message The received {@link PreKeySignalMessage}.
 * @throws org.whispersystems.libsignal.InvalidKeyIdException when there is no local
 *                                                             {@link org.whispersystems.libsignal.state.PreKeyRecord}
 *                                                             that corresponds to the PreKey ID in
 *                                                             the message.
 * @throws org.whispersystems.libsignal.InvalidKeyException when the message is formatted incorrectly.
 * @throws org.whispersystems.libsignal.UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
 */
/*package*/ Optional<Integer> process(SessionRecord sessionRecord, PreKeySignalMessage message)
    throws InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
  IdentityKey theirIdentityKey = message.getIdentityKey();

  if (!identityKeyStore.isTrustedIdentity(remoteAddress, theirIdentityKey, IdentityKeyStore.Direction.RECEIVING)) {
    throw new UntrustedIdentityException(remoteAddress.getName(), theirIdentityKey);
  }

  Optional<Integer> unsignedPreKeyId = processV3(sessionRecord, message);

  identityKeyStore.saveIdentity(remoteAddress, theirIdentityKey);

  return unsignedPreKeyId;
}
 
Example #4
Source File: SessionBuilder.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Build a new session from a received {@link PreKeySignalMessage}.
 *
 * After a session is constructed in this way, the embedded {@link SignalMessage}
 * can be decrypted.
 *
 * @param message The received {@link PreKeySignalMessage}.
 * @throws org.whispersystems.libsignal.InvalidKeyIdException when there is no local
 *                                                             {@link org.whispersystems.libsignal.state.PreKeyRecord}
 *                                                             that corresponds to the PreKey ID in
 *                                                             the message.
 * @throws org.whispersystems.libsignal.InvalidKeyException when the message is formatted incorrectly.
 * @throws org.whispersystems.libsignal.UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
 */
/*package*/ Optional<Integer> process(SessionRecord sessionRecord, PreKeySignalMessage message)
    throws InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
  IdentityKey theirIdentityKey = message.getIdentityKey();

  if (!identityKeyStore.isTrustedIdentity(remoteAddress, theirIdentityKey, IdentityKeyStore.Direction.RECEIVING)) {
    throw new UntrustedIdentityException(remoteAddress.getName(), theirIdentityKey);
  }

  Optional<Integer> unsignedPreKeyId = processV3(sessionRecord, message);

  identityKeyStore.saveIdentity(remoteAddress, theirIdentityKey);
  return unsignedPreKeyId;
}
 
Example #5
Source File: SessionBuilder.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Integer> processV3(SessionRecord sessionRecord, PreKeySignalMessage message)
    throws UntrustedIdentityException, InvalidKeyIdException, InvalidKeyException
{

  if (sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize())) {
    Log.w(TAG, "We've already setup a session for this V3 message, letting bundled message fall through...");
    return Optional.absent();
  }

  ECKeyPair ourSignedPreKey = signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair();

  BobSignalProtocolParameters.Builder parameters = BobSignalProtocolParameters.newBuilder();

  parameters.setTheirBaseKey(message.getBaseKey())
            .setTheirIdentityKey(message.getIdentityKey())
            .setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
            .setOurSignedPreKey(ourSignedPreKey)
            .setOurRatchetKey(ourSignedPreKey);

  if (message.getPreKeyId().isPresent()) {
    parameters.setOurOneTimePreKey(Optional.of(preKeyStore.loadPreKey(message.getPreKeyId().get()).getKeyPair()));
  } else {
    parameters.setOurOneTimePreKey(Optional.<ECKeyPair>absent());
  }

  if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();

  RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());

  sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
  sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId());
  sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize());

  if (message.getPreKeyId().isPresent() && message.getPreKeyId().get() != Medium.MAX_VALUE) {
    return message.getPreKeyId();
  } else {
    return Optional.absent();
  }
}
 
Example #6
Source File: SessionBuilder.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Integer> processV3(SessionRecord sessionRecord, PreKeySignalMessage message)
    throws UntrustedIdentityException, InvalidKeyIdException, InvalidKeyException
{

  if (sessionRecord.hasSessionState(message.getMessageVersion(), message.getBaseKey().serialize())) {
    Log.w(TAG, "We've already setup a session for this V3 message, letting bundled message fall through...");
    return Optional.absent();
  }

  ECKeyPair ourSignedPreKey = signedPreKeyStore.loadSignedPreKey(message.getSignedPreKeyId()).getKeyPair();

  BobSignalProtocolParameters.Builder parameters = BobSignalProtocolParameters.newBuilder();

  parameters.setTheirBaseKey(message.getBaseKey())
            .setTheirIdentityKey(message.getIdentityKey())
            .setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
            .setOurSignedPreKey(ourSignedPreKey)
            .setOurRatchetKey(ourSignedPreKey);

  if (message.getPreKeyId().isPresent()) {
    parameters.setOurOneTimePreKey(Optional.of(preKeyStore.loadPreKey(message.getPreKeyId().get()).getKeyPair()));
  } else {
    parameters.setOurOneTimePreKey(Optional.<ECKeyPair>absent());
  }

  if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();

  RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());

  sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
  sessionRecord.getSessionState().setRemoteRegistrationId(message.getRegistrationId());
  sessionRecord.getSessionState().setAliceBaseKey(message.getBaseKey().serialize());

  if (message.getPreKeyId().isPresent()) {
    return message.getPreKeyId();
  } else {
    return Optional.absent();
  }
}
 
Example #7
Source File: SignalServiceCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
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 #8
Source File: SessionBuilderTest.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testRepeatBundleMessageV3() throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException, InvalidMessageException, InvalidKeyIdException, DuplicateMessageException, LegacyMessageException, NoSessionException {
  SignalProtocolStore aliceStore          = new TestInMemorySignalProtocolStore();
  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);

  SignalProtocolStore bobStore = new TestInMemorySignalProtocolStore();

  ECKeyPair bobPreKeyPair            = Curve.generateKeyPair();
  ECKeyPair bobSignedPreKeyPair      = Curve.generateKeyPair();
  byte[]    bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                                bobSignedPreKeyPair.getPublicKey().serialize());

  PreKeyBundle bobPreKey = new PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                            31337, bobPreKeyPair.getPublicKey(),
                                            22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                            bobStore.getIdentityKeyPair().getPublicKey());

  bobStore.storePreKey(31337, new PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair));
  bobStore.storeSignedPreKey(22, new SignedPreKeyRecord(22, System.currentTimeMillis(), bobSignedPreKeyPair, bobSignedPreKeySignature));

  aliceSessionBuilder.process(bobPreKey);

  String            originalMessage    = "L'homme est condamné à être libre";
  SessionCipher     aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  CiphertextMessage outgoingMessageOne = aliceSessionCipher.encrypt(originalMessage.getBytes());
  CiphertextMessage outgoingMessageTwo = aliceSessionCipher.encrypt(originalMessage.getBytes());

  assertTrue(outgoingMessageOne.getType() == CiphertextMessage.PREKEY_TYPE);
  assertTrue(outgoingMessageTwo.getType() == CiphertextMessage.PREKEY_TYPE);

  PreKeySignalMessage incomingMessage = new PreKeySignalMessage(outgoingMessageOne.serialize());

  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  byte[]        plaintext        = bobSessionCipher.decrypt(incomingMessage);
  assertTrue(originalMessage.equals(new String(plaintext)));

  CiphertextMessage bobOutgoingMessage = bobSessionCipher.encrypt(originalMessage.getBytes());

  byte[] alicePlaintext = aliceSessionCipher.decrypt(new SignalMessage(bobOutgoingMessage.serialize()));
  assertTrue(originalMessage.equals(new String(alicePlaintext)));

  // The test

  PreKeySignalMessage incomingMessageTwo = new PreKeySignalMessage(outgoingMessageTwo.serialize());

  plaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(incomingMessageTwo.serialize()));
  assertTrue(originalMessage.equals(new String(plaintext)));

  bobOutgoingMessage = bobSessionCipher.encrypt(originalMessage.getBytes());
  alicePlaintext = aliceSessionCipher.decrypt(new SignalMessage(bobOutgoingMessage.serialize()));
  assertTrue(originalMessage.equals(new String(alicePlaintext)));

}
 
Example #9
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testSimultaneousInitiateLostMessage()
      throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException,
      InvalidMessageException, DuplicateMessageException, LegacyMessageException,
      InvalidKeyIdException, NoSessionException
  {
    SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
    SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();

    PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
    PreKeyBundle bobPreKeyBundle = createBobPreKeyBundle(bobStore);

    SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
    SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

    SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
    SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

    aliceSessionBuilder.process(bobPreKeyBundle);
    bobSessionBuilder.process(alicePreKeyBundle);

    CiphertextMessage messageForBob   = aliceSessionCipher.encrypt("hey there".getBytes());
    CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

    assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
    assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    byte[] alicePlaintext = aliceSessionCipher.decrypt(new PreKeySignalMessage(messageForAlice.serialize()));
    byte[] bobPlaintext   = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

    assertTrue(new String(alicePlaintext).equals("sample message"));
    assertTrue(new String(bobPlaintext).equals("hey there"));

    assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);
    assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

    assertTrue(aliceResponse.getType() == CiphertextMessage.WHISPER_TYPE);

//    byte[] responsePlaintext = bobSessionCipher.decrypt(new WhisperMessage(aliceResponse.serialize()));
//
//    assertTrue(new String(responsePlaintext).equals("second message"));
//    assertTrue(isSessionIdEqual(aliceStore, bobStore));
    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

    assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

    byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

    assertTrue(new String(finalPlaintext).equals("third message"));
    assertTrue(isSessionIdEqual(aliceStore, bobStore));
  }
 
Example #10
Source File: SessionBuilderTest.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testOptionalOneTimePreKey() throws Exception {
  SignalProtocolStore aliceStore          = new TestInMemorySignalProtocolStore();
  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);

  SignalProtocolStore bobStore = new TestInMemorySignalProtocolStore();

  ECKeyPair bobPreKeyPair            = Curve.generateKeyPair();
  ECKeyPair bobSignedPreKeyPair      = Curve.generateKeyPair();
  byte[]    bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                                bobSignedPreKeyPair.getPublicKey().serialize());

  PreKeyBundle bobPreKey = new PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                            0, null,
                                            22, bobSignedPreKeyPair.getPublicKey(),
                                            bobSignedPreKeySignature,
                                            bobStore.getIdentityKeyPair().getPublicKey());

  aliceSessionBuilder.process(bobPreKey);

  assertTrue(aliceStore.containsSession(BOB_ADDRESS));
  assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);

  String            originalMessage    = "L'homme est condamné à être libre";
  SessionCipher     aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  CiphertextMessage outgoingMessage    = aliceSessionCipher.encrypt(originalMessage.getBytes());

  assertTrue(outgoingMessage.getType() == CiphertextMessage.PREKEY_TYPE);

  PreKeySignalMessage incomingMessage = new PreKeySignalMessage(outgoingMessage.serialize());
  assertTrue(!incomingMessage.getPreKeyId().isPresent());

  bobStore.storePreKey(31337, new PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair));
  bobStore.storeSignedPreKey(22, new SignedPreKeyRecord(22, System.currentTimeMillis(), bobSignedPreKeyPair, bobSignedPreKeySignature));

  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);
  byte[]        plaintext        = bobSessionCipher.decrypt(incomingMessage);

  assertTrue(bobStore.containsSession(ALICE_ADDRESS));
  assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);
  assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getAliceBaseKey() != null);
  assertTrue(originalMessage.equals(new String(plaintext)));
}
 
Example #11
Source File: SessionBuilderTest.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testBadMessageBundle() throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException, InvalidMessageException, DuplicateMessageException, LegacyMessageException, InvalidKeyIdException {
  SignalProtocolStore aliceStore          = new TestInMemorySignalProtocolStore();
  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);

  SignalProtocolStore bobStore = new TestInMemorySignalProtocolStore();

  ECKeyPair bobPreKeyPair            = Curve.generateKeyPair();
  ECKeyPair bobSignedPreKeyPair      = Curve.generateKeyPair();
  byte[]    bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                                bobSignedPreKeyPair.getPublicKey().serialize());

  PreKeyBundle bobPreKey = new PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                            31337, bobPreKeyPair.getPublicKey(),
                                            22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                            bobStore.getIdentityKeyPair().getPublicKey());

  bobStore.storePreKey(31337, new PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair));
  bobStore.storeSignedPreKey(22, new SignedPreKeyRecord(22, System.currentTimeMillis(), bobSignedPreKeyPair, bobSignedPreKeySignature));

  aliceSessionBuilder.process(bobPreKey);

  String            originalMessage    = "L'homme est condamné à être libre";
  SessionCipher     aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  CiphertextMessage outgoingMessageOne = aliceSessionCipher.encrypt(originalMessage.getBytes());

  assertTrue(outgoingMessageOne.getType() == CiphertextMessage.PREKEY_TYPE);

  byte[] goodMessage = outgoingMessageOne.serialize();
  byte[] badMessage  = new byte[goodMessage.length];
  System.arraycopy(goodMessage, 0, badMessage, 0, badMessage.length);

  badMessage[badMessage.length-10] ^= 0x01;

  PreKeySignalMessage incomingMessage  = new PreKeySignalMessage(badMessage);
  SessionCipher        bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  byte[] plaintext = new byte[0];

  try {
    plaintext = bobSessionCipher.decrypt(incomingMessage);
    throw new AssertionError("Decrypt should have failed!");
  } catch (InvalidMessageException e) {
    // good.
  }

  assertTrue(bobStore.containsPreKey(31337));

  plaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(goodMessage));

  assertTrue(originalMessage.equals(new String(plaintext)));
  assertTrue(!bobStore.containsPreKey(31337));
}
 
Example #12
Source File: SessionCipher.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Decrypt a message.
 *
 * @param  ciphertext The {@link PreKeySignalMessage} to decrypt.
 * @param  callback   A callback that is triggered after decryption is complete,
 *                    but before the updated session state has been committed to the session
 *                    DB.  This allows some implementations to store the committed plaintext
 *                    to a DB first, in case they are concerned with a crash happening between
 *                    the time the session state is updated but before they're able to store
 *                    the plaintext to disk.
 *
 * @return The plaintext.
 * @throws InvalidMessageException if the input is not valid ciphertext.
 * @throws DuplicateMessageException if the input is a message that has already been received.
 * @throws LegacyMessageException if the input is a message formatted by a protocol version that
 *                                is no longer supported.
 * @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libsignal.state.PreKeyRecord}
 *                               that corresponds to the PreKey ID in the message.
 * @throws InvalidKeyException when the message is formatted incorrectly.
 * @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
 */
public byte[] decrypt(PreKeySignalMessage ciphertext, DecryptionCallback callback)
    throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
           InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
  synchronized (SESSION_LOCK) {
    SessionRecord     sessionRecord    = sessionStore.loadSession(remoteAddress);
    Optional<Integer> unsignedPreKeyId = sessionBuilder.process(sessionRecord, ciphertext);
    byte[]            plaintext        = decrypt(sessionRecord, ciphertext.getWhisperMessage());

    callback.handlePlaintext(plaintext);

    sessionStore.storeSession(remoteAddress, sessionRecord);

    if (unsignedPreKeyId.isPresent()) {
      preKeyStore.removePreKey(unsignedPreKeyId.get());
    }

    return plaintext;
  }
}
 
Example #13
Source File: SessionCipher.java    From libsignal-protocol-java with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Decrypt a message.
 *
 * @param  ciphertext The {@link PreKeySignalMessage} to decrypt.
 *
 * @return The plaintext.
 * @throws InvalidMessageException if the input is not valid ciphertext.
 * @throws DuplicateMessageException if the input is a message that has already been received.
 * @throws LegacyMessageException if the input is a message formatted by a protocol version that
 *                                is no longer supported.
 * @throws InvalidKeyIdException when there is no local {@link org.whispersystems.libsignal.state.PreKeyRecord}
 *                               that corresponds to the PreKey ID in the message.
 * @throws InvalidKeyException when the message is formatted incorrectly.
 * @throws UntrustedIdentityException when the {@link IdentityKey} of the sender is untrusted.
 */
public byte[] decrypt(PreKeySignalMessage ciphertext)
    throws DuplicateMessageException, LegacyMessageException, InvalidMessageException,
           InvalidKeyIdException, InvalidKeyException, UntrustedIdentityException
{
  return decrypt(ciphertext, new NullDecryptionCallback());
}
 
Example #14
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
public void testBasicSimultaneousInitiate()
    throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException,
    InvalidMessageException, DuplicateMessageException, LegacyMessageException,
    InvalidKeyIdException, NoSessionException
{
  SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
  SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();

  PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
  PreKeyBundle bobPreKeyBundle = createBobPreKeyBundle(bobStore);

  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
  SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

  SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  aliceSessionBuilder.process(bobPreKeyBundle);
  bobSessionBuilder.process(alicePreKeyBundle);

  CiphertextMessage messageForBob   = aliceSessionCipher.encrypt("hey there".getBytes());
  CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

  assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
  assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

  assertFalse(isSessionIdEqual(aliceStore, bobStore));

  byte[] alicePlaintext = aliceSessionCipher.decrypt(new PreKeySignalMessage(messageForAlice.serialize()));
  byte[] bobPlaintext   = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

  assertTrue(new String(alicePlaintext).equals("sample message"));
  assertTrue(new String(bobPlaintext).equals("hey there"));

  assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);
  assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

  assertFalse(isSessionIdEqual(aliceStore, bobStore));

  CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

  assertTrue(aliceResponse.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] responsePlaintext = bobSessionCipher.decrypt(new SignalMessage(aliceResponse.serialize()));

  assertTrue(new String(responsePlaintext).equals("second message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));

  CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

  assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

  assertTrue(new String(finalPlaintext).equals("third message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));
}
 
Example #15
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
public void testLostSimultaneousInitiate() throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException, InvalidMessageException, DuplicateMessageException, LegacyMessageException, InvalidKeyIdException, NoSessionException {
  SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
  SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();

  PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
  PreKeyBundle bobPreKeyBundle = createBobPreKeyBundle(bobStore);

  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
  SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

  SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  aliceSessionBuilder.process(bobPreKeyBundle);
  bobSessionBuilder.process(alicePreKeyBundle);

  CiphertextMessage messageForBob   = aliceSessionCipher.encrypt("hey there".getBytes());
  CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

  assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
  assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

  assertFalse(isSessionIdEqual(aliceStore, bobStore));

  byte[] bobPlaintext   = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

  assertTrue(new String(bobPlaintext).equals("hey there"));
  assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

  CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

  assertTrue(aliceResponse.getType() == CiphertextMessage.PREKEY_TYPE);

  byte[] responsePlaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(aliceResponse.serialize()));

  assertTrue(new String(responsePlaintext).equals("second message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));

  CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

  assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

  assertTrue(new String(finalPlaintext).equals("third message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));
}
 
Example #16
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
public void testSimultaneousInitiateRepeatedMessages()
    throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException,
    InvalidMessageException, DuplicateMessageException, LegacyMessageException,
    InvalidKeyIdException, NoSessionException
{
  SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
  SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();

  PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
  PreKeyBundle bobPreKeyBundle = createBobPreKeyBundle(bobStore);

  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
  SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

  SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  aliceSessionBuilder.process(bobPreKeyBundle);
  bobSessionBuilder.process(alicePreKeyBundle);

  CiphertextMessage messageForBob   = aliceSessionCipher.encrypt("hey there".getBytes());
  CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

  assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
  assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

  assertFalse(isSessionIdEqual(aliceStore, bobStore));

  byte[] alicePlaintext = aliceSessionCipher.decrypt(new PreKeySignalMessage(messageForAlice.serialize()));
  byte[] bobPlaintext   = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

  assertTrue(new String(alicePlaintext).equals("sample message"));
  assertTrue(new String(bobPlaintext).equals("hey there"));

  assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);
  assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

  assertFalse(isSessionIdEqual(aliceStore, bobStore));

  for (int i=0;i<50;i++) {
    CiphertextMessage messageForBobRepeat   = aliceSessionCipher.encrypt("hey there".getBytes());
    CiphertextMessage messageForAliceRepeat = bobSessionCipher.encrypt("sample message".getBytes());

    assertTrue(messageForBobRepeat.getType() == CiphertextMessage.WHISPER_TYPE);
    assertTrue(messageForAliceRepeat.getType() == CiphertextMessage.WHISPER_TYPE);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    byte[] alicePlaintextRepeat = aliceSessionCipher.decrypt(new SignalMessage(messageForAliceRepeat.serialize()));
    byte[] bobPlaintextRepeat   = bobSessionCipher.decrypt(new SignalMessage(messageForBobRepeat.serialize()));

    assertTrue(new String(alicePlaintextRepeat).equals("sample message"));
    assertTrue(new String(bobPlaintextRepeat).equals("hey there"));

    assertFalse(isSessionIdEqual(aliceStore, bobStore));
  }

  CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

  assertTrue(aliceResponse.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] responsePlaintext = bobSessionCipher.decrypt(new SignalMessage(aliceResponse.serialize()));

  assertTrue(new String(responsePlaintext).equals("second message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));

  CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

  assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

  assertTrue(new String(finalPlaintext).equals("third message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));
}
 
Example #17
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
public void testRepeatedSimultaneousInitiateRepeatedMessages()
    throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException,
    InvalidMessageException, DuplicateMessageException, LegacyMessageException,
    InvalidKeyIdException, NoSessionException
{
  SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
  SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();


  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
  SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

  SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  for (int i=0;i<15;i++) {
    PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
    PreKeyBundle bobPreKeyBundle   = createBobPreKeyBundle(bobStore);

    aliceSessionBuilder.process(bobPreKeyBundle);
    bobSessionBuilder.process(alicePreKeyBundle);

    CiphertextMessage messageForBob = aliceSessionCipher.encrypt("hey there".getBytes());
    CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

    assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
    assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    byte[] alicePlaintext = aliceSessionCipher.decrypt(new PreKeySignalMessage(messageForAlice.serialize()));
    byte[] bobPlaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

    assertTrue(new String(alicePlaintext).equals("sample message"));
    assertTrue(new String(bobPlaintext).equals("hey there"));

    assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);
    assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));
  }

  for (int i=0;i<50;i++) {
    CiphertextMessage messageForBobRepeat   = aliceSessionCipher.encrypt("hey there".getBytes());
    CiphertextMessage messageForAliceRepeat = bobSessionCipher.encrypt("sample message".getBytes());

    assertTrue(messageForBobRepeat.getType() == CiphertextMessage.WHISPER_TYPE);
    assertTrue(messageForAliceRepeat.getType() == CiphertextMessage.WHISPER_TYPE);

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    byte[] alicePlaintextRepeat = aliceSessionCipher.decrypt(new SignalMessage(messageForAliceRepeat.serialize()));
    byte[] bobPlaintextRepeat   = bobSessionCipher.decrypt(new SignalMessage(messageForBobRepeat.serialize()));

    assertTrue(new String(alicePlaintextRepeat).equals("sample message"));
    assertTrue(new String(bobPlaintextRepeat).equals("hey there"));

    assertFalse(isSessionIdEqual(aliceStore, bobStore));
  }

  CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

  assertTrue(aliceResponse.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] responsePlaintext = bobSessionCipher.decrypt(new SignalMessage(aliceResponse.serialize()));

  assertTrue(new String(responsePlaintext).equals("second message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));

  CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

  assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

  byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

  assertTrue(new String(finalPlaintext).equals("third message"));
  assertTrue(isSessionIdEqual(aliceStore, bobStore));
}
 
Example #18
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
public void testRepeatedSimultaneousInitiateLostMessageRepeatedMessages()
      throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException,
      InvalidMessageException, DuplicateMessageException, LegacyMessageException,
      InvalidKeyIdException, NoSessionException
  {
    SignalProtocolStore aliceStore = new TestInMemorySignalProtocolStore();
    SignalProtocolStore bobStore   = new TestInMemorySignalProtocolStore();


    SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);
    SessionBuilder bobSessionBuilder   = new SessionBuilder(bobStore, ALICE_ADDRESS);

    SessionCipher aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
    SessionCipher bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

//    PreKeyBundle aliceLostPreKeyBundle = createAlicePreKeyBundle(aliceStore);
    PreKeyBundle bobLostPreKeyBundle   = createBobPreKeyBundle(bobStore);

    aliceSessionBuilder.process(bobLostPreKeyBundle);
//    bobSessionBuilder.process(aliceLostPreKeyBundle);

    CiphertextMessage lostMessageForBob   = aliceSessionCipher.encrypt("hey there".getBytes());
//    CiphertextMessage lostMessageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

    for (int i=0;i<15;i++) {
      PreKeyBundle alicePreKeyBundle = createAlicePreKeyBundle(aliceStore);
      PreKeyBundle bobPreKeyBundle   = createBobPreKeyBundle(bobStore);

      aliceSessionBuilder.process(bobPreKeyBundle);
      bobSessionBuilder.process(alicePreKeyBundle);

      CiphertextMessage messageForBob = aliceSessionCipher.encrypt("hey there".getBytes());
      CiphertextMessage messageForAlice = bobSessionCipher.encrypt("sample message".getBytes());

      assertTrue(messageForBob.getType() == CiphertextMessage.PREKEY_TYPE);
      assertTrue(messageForAlice.getType() == CiphertextMessage.PREKEY_TYPE);

      assertFalse(isSessionIdEqual(aliceStore, bobStore));

      byte[] alicePlaintext = aliceSessionCipher.decrypt(new PreKeySignalMessage(messageForAlice.serialize()));
      byte[] bobPlaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(messageForBob.serialize()));

      assertTrue(new String(alicePlaintext).equals("sample message"));
      assertTrue(new String(bobPlaintext).equals("hey there"));

      assertTrue(aliceStore.loadSession(BOB_ADDRESS).getSessionState().getSessionVersion() == 3);
      assertTrue(bobStore.loadSession(ALICE_ADDRESS).getSessionState().getSessionVersion() == 3);

      assertFalse(isSessionIdEqual(aliceStore, bobStore));
    }

    for (int i=0;i<50;i++) {
      CiphertextMessage messageForBobRepeat   = aliceSessionCipher.encrypt("hey there".getBytes());
      CiphertextMessage messageForAliceRepeat = bobSessionCipher.encrypt("sample message".getBytes());

      assertTrue(messageForBobRepeat.getType() == CiphertextMessage.WHISPER_TYPE);
      assertTrue(messageForAliceRepeat.getType() == CiphertextMessage.WHISPER_TYPE);

      assertFalse(isSessionIdEqual(aliceStore, bobStore));

      byte[] alicePlaintextRepeat = aliceSessionCipher.decrypt(new SignalMessage(messageForAliceRepeat.serialize()));
      byte[] bobPlaintextRepeat   = bobSessionCipher.decrypt(new SignalMessage(messageForBobRepeat.serialize()));

      assertTrue(new String(alicePlaintextRepeat).equals("sample message"));
      assertTrue(new String(bobPlaintextRepeat).equals("hey there"));

      assertFalse(isSessionIdEqual(aliceStore, bobStore));
    }

    CiphertextMessage aliceResponse = aliceSessionCipher.encrypt("second message".getBytes());

    assertTrue(aliceResponse.getType() == CiphertextMessage.WHISPER_TYPE);

    byte[] responsePlaintext = bobSessionCipher.decrypt(new SignalMessage(aliceResponse.serialize()));

    assertTrue(new String(responsePlaintext).equals("second message"));
    assertTrue(isSessionIdEqual(aliceStore, bobStore));

    CiphertextMessage finalMessage = bobSessionCipher.encrypt("third message".getBytes());

    assertTrue(finalMessage.getType() == CiphertextMessage.WHISPER_TYPE);

    byte[] finalPlaintext = aliceSessionCipher.decrypt(new SignalMessage(finalMessage.serialize()));

    assertTrue(new String(finalPlaintext).equals("third message"));
    assertTrue(isSessionIdEqual(aliceStore, bobStore));

    byte[] lostMessagePlaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(lostMessageForBob.serialize()));
    assertTrue(new String(lostMessagePlaintext).equals("hey there"));

    assertFalse(isSessionIdEqual(aliceStore, bobStore));

    CiphertextMessage blastFromThePast          = bobSessionCipher.encrypt("unexpected!".getBytes());
    byte[]            blastFromThePastPlaintext = aliceSessionCipher.decrypt(new SignalMessage(blastFromThePast.serialize()));

    assertTrue(new String(blastFromThePastPlaintext).equals("unexpected!"));
    assertTrue(isSessionIdEqual(aliceStore, bobStore));
  }