org.whispersystems.libsignal.InvalidMessageException Java Examples

The following examples show how to use org.whispersystems.libsignal.InvalidMessageException. 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: AttachmentCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void test_attachment_decryptFailOnNullDigest() throws IOException{
  File    cipherFile          = null;
  boolean hitCorrectException = false;

  try {
    byte[]        key             = Util.getSecretBytes(64);
    byte[]        plaintextInput  = "Aunt May".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, key);

    cipherFile = writeToFile(encryptResult.ciphertext);

    AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, key, null);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  } finally {
    if (cipherFile != null) {
      cipherFile.delete();
    }
  }

  assertTrue(hitCorrectException);
}
 
Example #2
Source File: SmsCipher.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public OutgoingKeyExchangeMessage process(Context context, IncomingKeyExchangeMessage message)
    throws UntrustedIdentityException, StaleKeyExchangeException,
           InvalidVersionException, LegacyMessageException, InvalidMessageException
{
  try {
    Recipients            recipients            = RecipientFactory.getRecipientsFromString(context, message.getSender(), false);
    SignalProtocolAddress signalProtocolAddress = new SignalProtocolAddress(message.getSender(), 1);
    KeyExchangeMessage    exchangeMessage       = new KeyExchangeMessage(transportDetails.getDecodedMessage(message.getMessageBody().getBytes()));
    SessionBuilder        sessionBuilder        = new SessionBuilder(signalProtocolStore, signalProtocolAddress);

    KeyExchangeMessage response        = sessionBuilder.process(exchangeMessage);

    if (response != null) {
      byte[] serializedResponse = transportDetails.getEncodedMessage(response.serialize());
      return new OutgoingKeyExchangeMessage(recipients, new String(serializedResponse), message.getSubscriptionId());
    } else {
      return null;
    }
  } catch (IOException | InvalidKeyException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example #3
Source File: TextSecurePreKeyStore.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private byte[] loadSerializedRecord(File recordFile)
        throws IOException, InvalidMessageException {
    FileInputStream fin = new FileInputStream(recordFile);
    int recordVersion = readInteger(fin);

    try {
        if (recordVersion > CURRENT_VERSION_MARKER) {
            throw new AssertionError("Invalid version: " + recordVersion);
        }

        byte[] serializedRecord = readBlob(fin);

        if (recordVersion < PLAINTEXT_VERSION && masterSecret != null) {
            MasterCipher masterCipher = new MasterCipher(masterSecret);
            serializedRecord = masterCipher.decryptBytes(serializedRecord);
        } else if (recordVersion < PLAINTEXT_VERSION) {
            throw new AssertionError("Migration didn't happen! " + recordFile.getAbsolutePath() + ", " + recordVersion);
        }

        fin.close();
        return serializedRecord;
    } catch (AssertionError e) {
        Logger.e(e, "loadSerializedRecord failed");
        throw new IOException(e);
    }
}
 
Example #4
Source File: AsymmetricMasterCipher.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public String decryptBody(String body) throws IOException, InvalidMessageException {
  try {
    byte[]    combined       = Base64.decode(body);
    byte[][]  parts          = Util.split(combined, PublicKey.KEY_SIZE, combined.length - PublicKey.KEY_SIZE);
    PublicKey theirPublicKey = new PublicKey(parts[0], 0);

    ECPrivateKey ourPrivateKey = asymmetricMasterSecret.getPrivateKey();
    byte[]       secret        = Curve.calculateAgreement(theirPublicKey.getKey(), ourPrivateKey);
    MasterCipher masterCipher  = getMasterCipherForSecret(secret);
    byte[]       decryptedBody = masterCipher.decryptBytes(parts[1]);

    return new String(decryptedBody);
  } catch (InvalidKeyException | InvalidMessageException ike) {
    throw new InvalidMessageException(ike);
  }
}
 
Example #5
Source File: SignalServiceGroupContext.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static SignalServiceGroupContext create(SignalServiceGroup groupV1, SignalServiceGroupV2 groupV2)
    throws InvalidMessageException
{
  if (groupV1 == null && groupV2 == null) {
    return null;
  }

  if (groupV1 != null && groupV2 != null) {
    throw new InvalidMessageException("Message cannot have both V1 and V2 group contexts.");
  }

  if (groupV1 != null) {
    return new SignalServiceGroupContext(groupV1);
  } else {
    return new SignalServiceGroupContext(groupV2);
  }
}
 
Example #6
Source File: AttachmentCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void test_sticker_decryptFailOnBadMac() throws IOException {
  boolean hitCorrectException = false;

  try {
    byte[]        packKey          = Util.getSecretBytes(32);
    byte[]        plaintextInput   = "Uncle Ben".getBytes();
    EncryptResult encryptResult    = encryptData(plaintextInput, expandPackKey(packKey));
    byte[]        badMacCiphertext = Arrays.copyOf(encryptResult.ciphertext, encryptResult.ciphertext.length);

    badMacCiphertext[badMacCiphertext.length - 1] = 0;

    AttachmentCipherInputStream.createForStickerData(badMacCiphertext, packKey);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  }

  assertTrue(hitCorrectException);
}
 
Example #7
Source File: SignalServiceMessageReceiver.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves a {@link SignalServiceStickerManifest}.
 *
 * @param packId The 16-byte packId that identifies the sticker pack.
 * @param packKey The 32-byte packKey that decrypts the sticker pack.
 * @return The {@link SignalServiceStickerManifest} representing the sticker pack.
 * @throws IOException
 * @throws InvalidMessageException
 */
public SignalServiceStickerManifest retrieveStickerManifest(byte[] packId, byte[] packKey)
    throws IOException, InvalidMessageException
{
  byte[] manifestBytes = socket.retrieveStickerManifest(packId);

  InputStream           cipherStream = AttachmentCipherInputStream.createForStickerData(manifestBytes, packKey);
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

  Util.copy(cipherStream, outputStream);

  StickerProtos.Pack                             pack     = StickerProtos.Pack.parseFrom(outputStream.toByteArray());
  List<SignalServiceStickerManifest.StickerInfo> stickers = new ArrayList<>(pack.getStickersCount());
  SignalServiceStickerManifest.StickerInfo       cover    = pack.hasCover() ? new SignalServiceStickerManifest.StickerInfo(pack.getCover().getId(), pack.getCover().getEmoji())
                                                                        : null;

  for (StickerProtos.Pack.Sticker sticker : pack.getStickersList()) {
    stickers.add(new SignalServiceStickerManifest.StickerInfo(sticker.getId(), sticker.getEmoji()));
  }

  return new SignalServiceStickerManifest(pack.getTitle(), pack.getAuthor(), cover, stickers);
}
 
Example #8
Source File: EncryptingJobSerializer.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Job deserialize(EncryptionKeys keys, boolean encrypted, String serialized) throws IOException {
  try {
    String plaintext;

    if (encrypted) {
      MasterSecret masterSecret = ParcelUtil.deserialize(keys.getEncoded(), MasterSecret.CREATOR);
      MasterCipher masterCipher = new MasterCipher(masterSecret);
      plaintext = masterCipher.decryptBody(serialized);
    } else {
      plaintext = serialized;
    }

    return delegate.deserialize(keys, encrypted, plaintext);
  } catch (InvalidMessageException e) {
    throw new IOException(e);
  }
}
 
Example #9
Source File: AttachmentCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void test_attachment_decryptFailOnBadKey() throws IOException{
  File    cipherFile          = null;
  boolean hitCorrectException = false;

  try {
    byte[]        key             = Util.getSecretBytes(64);
    byte[]        plaintextInput  = "Gwen Stacy".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, key);
    byte[]        badKey          = new byte[64];

    cipherFile = writeToFile(encryptResult.ciphertext);

    AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, badKey, encryptResult.digest);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  } finally {
    if (cipherFile != null) {
      cipherFile.delete();
    }
  }

  assertTrue(hitCorrectException);
}
 
Example #10
Source File: AttachmentCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void test_sticker_decryptFailOnBadKey() throws IOException{
  boolean hitCorrectException = false;

  try {
    byte[]        packKey         = Util.getSecretBytes(32);
    byte[]        plaintextInput  = "Gwen Stacy".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, expandPackKey(packKey));
    byte[]        badPackKey      = new byte[32];

    AttachmentCipherInputStream.createForStickerData(encryptResult.ciphertext, badPackKey);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  }

  assertTrue(hitCorrectException);
}
 
Example #11
Source File: AttachmentCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void test_attachment_decryptFailOnBadDigest() throws IOException{
  File    cipherFile          = null;
  boolean hitCorrectException = false;

  try {
    byte[]        key             = Util.getSecretBytes(64);
    byte[]        plaintextInput  = "Mary Jane Watson".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, key);
    byte[]        badDigest       = new byte[32];

    cipherFile = writeToFile(encryptResult.ciphertext);

    AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, key, badDigest);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  } finally {
    if (cipherFile != null) {
      cipherFile.delete();
    }
  }

  assertTrue(hitCorrectException);
}
 
Example #12
Source File: MasterCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private byte[] verifyMacBody(@NonNull Mac hmac, @NonNull byte[] encryptedAndMac) throws InvalidMessageException {
  if (encryptedAndMac.length < hmac.getMacLength()) {
    throw new InvalidMessageException("length(encrypted body + MAC) < length(MAC)");
  }

  byte[] encrypted = new byte[encryptedAndMac.length - hmac.getMacLength()];
  System.arraycopy(encryptedAndMac, 0, encrypted, 0, encrypted.length);

  byte[] remoteMac = new byte[hmac.getMacLength()];
  System.arraycopy(encryptedAndMac, encryptedAndMac.length - remoteMac.length, remoteMac, 0, remoteMac.length);

  byte[] localMac  = hmac.doFinal(encrypted);

  if (!Arrays.equals(remoteMac, localMac))
    throw new InvalidMessageException("MAC doesen't match.");

  return encrypted;
}
 
Example #13
Source File: MmsDatabase.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private @Nullable String getDecryptedBody(@NonNull MasterSecret masterSecret,
                                          @Nullable String body, long outboxType)
{
  try {
    if (!TextUtils.isEmpty(body) && Types.isSymmetricEncryption(outboxType)) {
      MasterCipher masterCipher = new MasterCipher(masterSecret);
      return masterCipher.decryptBody(body);
    } else {
      return body;
    }
  } catch (InvalidMessageException e) {
    Log.w(TAG, e);
  }

  return null;
}
 
Example #14
Source File: StickerPackPreviewRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private Optional<StickerManifestResult> getManifestRemote(@NonNull String packId, @NonNull String packKey) {
  try {
    byte[]                       packIdBytes    = Hex.stringToBytes(packId);
    byte[]                       packKeyBytes   = Hex.stringToBytes(packKey);
    SignalServiceStickerManifest remoteManifest = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes);
    StickerManifest              localManifest  = new StickerManifest(packId,
                                                                      packKey,
                                                                      remoteManifest.getTitle(),
                                                                      remoteManifest.getAuthor(),
                                                                      toOptionalSticker(packId, packKey, remoteManifest.getCover()),
                                                                      Stream.of(remoteManifest.getStickers())
                                                                            .map(s -> toSticker(packId, packKey, s))
                                                                            .toList());

    return Optional.of(new StickerManifestResult(localManifest, false));
  } catch (IOException | InvalidMessageException e) {
    Log.w(TAG, "Failed to retrieve pack manifest.", e);
  }

  return Optional.absent();
}
 
Example #15
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 #16
Source File: AttachmentCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void test_attachment_decryptFailOnBadDigest() throws IOException{
  File    cipherFile          = null;
  boolean hitCorrectException = false;

  try {
    byte[]        key             = Util.getSecretBytes(64);
    byte[]        plaintextInput  = "Mary Jane Watson".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, key);
    byte[]        badDigest       = new byte[32];

    cipherFile = writeToFile(encryptResult.ciphertext);

    AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, key, badDigest);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  } finally {
    if (cipherFile != null) {
      cipherFile.delete();
    }
  }

  assertTrue(hitCorrectException);
}
 
Example #17
Source File: AttachmentCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void test_attachment_decryptFailOnBadKey() throws IOException{
  File    cipherFile          = null;
  boolean hitCorrectException = false;

  try {
    byte[]        key             = Util.getSecretBytes(64);
    byte[]        plaintextInput  = "Gwen Stacy".getBytes();
    EncryptResult encryptResult   = encryptData(plaintextInput, key);
    byte[]        badKey          = new byte[64];

    cipherFile = writeToFile(encryptResult.ciphertext);

    AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, badKey, encryptResult.digest);
  } catch (InvalidMessageException e) {
    hitCorrectException = true;
  } finally {
    if (cipherFile != null) {
      cipherFile.delete();
    }
  }

  assertTrue(hitCorrectException);
}
 
Example #18
Source File: MmsDatabase.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private DisplayRecord.Body getBody(Cursor cursor) {
    try {
        String body = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.BODY));
        long box = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_BOX));

        if (!TextUtils.isEmpty(body) && masterCipher != null && Types.isSymmetricEncryption(box)) {
            return new DisplayRecord.Body(masterCipher.decryptBody(body), true);
        } else if (!TextUtils.isEmpty(body) && masterCipher == null && Types.isSymmetricEncryption(box)) {
            return new DisplayRecord.Body(body, false);
        } else if (!TextUtils.isEmpty(body) && Types.isAsymmetricEncryption(box)) {
            return new DisplayRecord.Body(body, false);
        } else {
            return new DisplayRecord.Body(body == null ? "" : body, true);
        }
    } catch (InvalidMessageException e) {
        Log.w("MmsDatabase", e);
        return new DisplayRecord.Body(context.getString(R.string.MmsDatabase_error_decrypting_message), true);
    }
}
 
Example #19
Source File: AttachmentDownloadJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void retrieveAttachment(long messageId,
                                final AttachmentId attachmentId,
                                final Attachment attachment)
    throws IOException
{

  AttachmentDatabase database       = DatabaseFactory.getAttachmentDatabase(context);
  File               attachmentFile = database.getOrCreateTransferFile(attachmentId);

  try {
    SignalServiceMessageReceiver   messageReceiver = ApplicationDependencies.getSignalServiceMessageReceiver();
    SignalServiceAttachmentPointer pointer         = createAttachmentPointer(attachment);
    InputStream                    stream          = messageReceiver.retrieveAttachment(pointer, attachmentFile, MAX_ATTACHMENT_SIZE, (total, progress) -> EventBus.getDefault().postSticky(new PartProgressEvent(attachment, PartProgressEvent.Type.NETWORK, total, progress)));

    database.insertAttachmentsForPlaceholder(messageId, attachmentId, stream);
  } catch (InvalidPartException | NonSuccessfulResponseCodeException | InvalidMessageException | MmsException | MissingConfigurationException e) {
    Log.w(TAG, "Experienced exception while trying to download an attachment.", e);
    markFailed(messageId, attachmentId);
  }
}
 
Example #20
Source File: SmsCipher.java    From Silence with 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 #21
Source File: SignalServiceCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private SignalServiceTypingMessage createTypingMessage(Metadata metadata, TypingMessage content) throws ProtocolInvalidMessageException {
  SignalServiceTypingMessage.Action action;

  if      (content.getAction() == TypingMessage.Action.STARTED) action = SignalServiceTypingMessage.Action.STARTED;
  else if (content.getAction() == TypingMessage.Action.STOPPED) action = SignalServiceTypingMessage.Action.STOPPED;
  else                                                          action = SignalServiceTypingMessage.Action.UNKNOWN;

  if (content.hasTimestamp() && content.getTimestamp() != metadata.getTimestamp()) {
    throw new ProtocolInvalidMessageException(new InvalidMessageException("Timestamps don't match: " + content.getTimestamp() + " vs " + metadata.getTimestamp()),
                                              metadata.getSender().getIdentifier(),
                                              metadata.getSenderDevice());
  }

  return new SignalServiceTypingMessage(action, content.getTimestamp(),
                                        content.hasGroupId() ? Optional.of(content.getGroupId().toByteArray()) :
                                                               Optional.<byte[]>absent());
}
 
Example #22
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 #23
Source File: MasterCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private byte[] decodeAndDecryptBytes(String body) throws InvalidMessageException {
  try {
    byte[] decodedBody = Base64.decode(body);
    return decryptBytes(decodedBody);
  } catch (IOException e) {
    throw new InvalidMessageException("Bad Base64 Encoding...", e);
  }
}
 
Example #24
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException, MissingConfigurationException {
    IOUtils.createPrivateDirectories(pathConfig.getAvatarsPath());
    if (attachment.isPointer()) {
        SignalServiceAttachmentPointer pointer = attachment.asPointer();
        return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
    } else {
        SignalServiceAttachmentStream stream = attachment.asStream();
        return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
    }
}
 
Example #25
Source File: TextSecurePreKeyStore.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
    synchronized (FILE_LOCK) {
        try {
            return new PreKeyRecord(loadSerializedRecord(getPreKeyFile(preKeyId)));
        } catch (IOException | InvalidMessageException e) {
            Log.w(TAG, e);
            throw new InvalidKeyIdException(e);
        }
    }
}
 
Example #26
Source File: DraftDatabase.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public List<Draft> getDrafts(MasterCipher masterCipher, long threadId) {
  SQLiteDatabase db   = databaseHelper.getReadableDatabase();
  List<Draft> results = new LinkedList<Draft>();
  Cursor cursor       = null;

  try {
    cursor = db.query(TABLE_NAME, null, THREAD_ID + " = ?", new String[] {threadId+""}, null, null, null);

    while (cursor != null && cursor.moveToNext()) {
      try {
          if (masterCipher == null) {
              results.add(new Draft(cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_TYPE)), cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_VALUE))));
          } else {
              String encryptedType = cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_TYPE));
              String encryptedValue = cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_VALUE));

              results.add(new Draft(masterCipher.decryptBody(encryptedType),
                      masterCipher.decryptBody(encryptedValue)));
          }

      } catch (InvalidMessageException ime) {
        Log.w("DraftDatabase", ime);
      }
    }

    return results;
  } finally {
    if (cursor != null)
      cursor.close();
  }
}
 
Example #27
Source File: AttachmentDownloadJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private FileInfo retrieveAttachment(MasterSecret masterSecret, SignalServiceAttachmentPointer pointer, File destination, int maxSizeBytes, SignalServiceAttachment.ProgressListener listener)
        throws IOException, InvalidMessageException {
    if (!pointer.getDigest().isPresent())
        throw new InvalidMessageException("No attachment digest!");

    String url;
    if (pointer.getUrl().isPresent()) {
        url = pointer.getUrl().get();
    } else {
        url = BcmHttpApiHelper.INSTANCE.getDownloadApi(String.format("/attachments/%s", Long.toString(pointer.getId())));
    }

    ChatFileHttp.INSTANCE.downloadAttachment(url, destination, pointer.getSize().or(0), maxSizeBytes, listener);
    return ChatFileEncryptDecryptUtil.decryptAndSaveFile(accountContext, masterSecret, destination, pointer, ChatFileEncryptDecryptUtil.FileType.PRIVATE);
}
 
Example #28
Source File: AttachmentFileNameJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun(MasterSecret masterSecret) throws IOException, InvalidMessageException {
    if (encryptedFileName == null) return;

    String plaintextFileName = new AsymmetricMasterCipher(MasterSecretUtil.getAsymmetricMasterSecret(accountContext, masterSecret)).decryptBody(encryptedFileName);

    AttachmentRepo attachmentRepo = Repository.getAttachmentRepo(accountContext);
    if (attachmentRepo != null) {
        attachmentRepo.updateFileName(attachmentRowId, attachmentUniqueId, plaintextFileName);
    }
}
 
Example #29
Source File: ConversationActivity.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private String getMessage() throws InvalidMessageException {
  String rawText = composeText.getText().toString();

  if (rawText.length() < 1 && !attachmentManager.isAttachmentPresent())
    throw new InvalidMessageException(getString(R.string.ConversationActivity_message_is_empty_exclamation));

  if (!isEncryptedConversation &&
      AutoInitiate.isTaggableMessage(rawText) &&
      AutoInitiate.isTaggableDestination(getRecipients())) {
    rawText = AutoInitiate.getTaggedMessage(rawText);
  }

  return rawText;
}
 
Example #30
Source File: MasterCipher.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private byte[] decodeAndDecryptBytes(String body) throws InvalidMessageException {
  try {
    byte[] decodedBody = Base64.decode(body);
    return decryptBytes(decodedBody);
  } catch (IOException e) {
    throw new InvalidMessageException("Bad Base64 Encoding...", e);
  }
}