Java Code Examples for org.whispersystems.signalservice.internal.util.Util

The following examples show how to use org.whispersystems.signalservice.internal.util.Util. 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
public SignalServiceAttachmentPointer uploadAttachment(SignalServiceAttachmentStream attachment) throws IOException {
  byte[]             attachmentKey    = attachment.getResumableUploadSpec().transform(ResumableUploadSpec::getSecretKey).or(() -> Util.getSecretBytes(64));
  byte[]             attachmentIV     = attachment.getResumableUploadSpec().transform(ResumableUploadSpec::getIV).or(() -> Util.getSecretBytes(16));
  long               paddedLength     = PaddingInputStream.getPaddedSize(attachment.getLength());
  InputStream        dataStream       = new PaddingInputStream(attachment.getInputStream(), attachment.getLength());
  long               ciphertextLength = AttachmentCipherOutputStream.getCiphertextLength(paddedLength);
  PushAttachmentData attachmentData   = new PushAttachmentData(attachment.getContentType(),
                                                               dataStream,
                                                               ciphertextLength,
                                                               new AttachmentCipherOutputStreamFactory(attachmentKey, attachmentIV),
                                                               attachment.getListener(),
                                                               attachment.getCancelationSignal(),
                                                               attachment.getResumableUploadSpec().orNull());

  if (attachmentsV3.get()) {
    return uploadAttachmentV3(attachment, attachmentKey, attachmentData);
  } else {
    return uploadAttachmentV2(attachment, attachmentKey, attachmentData);
  }
}
 
Example 2
private SignalServiceAttachmentPointer uploadAttachmentV3(SignalServiceAttachmentStream attachment, byte[] attachmentKey, PushAttachmentData attachmentData) throws IOException {
  byte[] digest = socket.uploadAttachment(attachmentData);
  return new SignalServiceAttachmentPointer(attachmentData.getResumableUploadSpec().getCdnNumber(),
                                            new SignalServiceAttachmentRemoteId(attachmentData.getResumableUploadSpec().getCdnKey()),
                                            attachment.getContentType(),
                                            attachmentKey,
                                            Optional.of(Util.toIntExact(attachment.getLength())),
                                            attachment.getPreview(),
                                            attachment.getWidth(),
                                            attachment.getHeight(),
                                            Optional.of(digest),
                                            attachment.getFileName(),
                                            attachment.getVoiceNote(),
                                            attachment.getCaption(),
                                            attachment.getBlurHash(),
                                            attachment.getUploadTimestamp());
}
 
Example 3
private void sendMessage(VerifiedMessage message, Optional<UnidentifiedAccessPair> unidentifiedAccess)
    throws IOException, UntrustedIdentityException
{
  byte[] nullMessageBody = DataMessage.newBuilder()
                                      .setBody(Base64.encodeBytes(Util.getRandomLengthBytes(140)))
                                      .build()
                                      .toByteArray();

  NullMessage nullMessage = NullMessage.newBuilder()
                                       .setPadding(ByteString.copyFrom(nullMessageBody))
                                       .build();

  byte[] content          = Content.newBuilder()
                                   .setNullMessage(nullMessage)
                                   .build()
                                   .toByteArray();

  SendMessageResult result = sendMessage(message.getDestination(), getTargetUnidentifiedAccess(unidentifiedAccess), message.getTimestamp(), content, false);

  if (result.getSuccess().isNeedsSync()) {
    byte[] syncMessage = createMultiDeviceVerifiedContent(message, nullMessage.toByteArray());
    sendMessage(localAddress, Optional.<UnidentifiedAccess>absent(), message.getTimestamp(), syncMessage, false);
  }
}
 
Example 4
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 5
public AttachmentCipherOutputStream(byte[] combinedKeyMaterial,
                                    byte[] iv,
                                    OutputStream outputStream)
    throws IOException
{
  super(outputStream);
  try {
    this.cipher       = initializeCipher();
    this.mac          = initializeMac();
    byte[][] keyParts = Util.split(combinedKeyMaterial, 32, 32);

    if (iv == null) {
      this.cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyParts[0], "AES"));
    } else {
      this.cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyParts[0], "AES"), new IvParameterSpec(iv));
    }

    this.mac.init(new SecretKeySpec(keyParts[1], "HmacSHA256"));

    mac.update(cipher.getIV());
    super.write(cipher.getIV());
  } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example 6
public byte[] encryptName(byte[] input, int paddedLength) {
  try {
    byte[] inputPadded = new byte[paddedLength];

    if (input.length > inputPadded.length) {
      throw new IllegalArgumentException("Input is too long: " + new String(input));
    }

    System.arraycopy(input, 0, inputPadded, 0, input.length);

    byte[] nonce = Util.getSecretBytes(12);

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.serialize(), "AES"), new GCMParameterSpec(128, nonce));

    return ByteUtil.combine(nonce, cipher.doFinal(inputPadded));
  } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 7
Source Project: mollyim-android   Source File: AESCipher.java    License: GNU General Public License v3.0 6 votes vote down vote up
static AESEncryptedResult encrypt(byte[] key, byte[] aad, byte[] requestData) {
  try {
    byte[] iv     = Util.getSecretBytes(12);
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, iv));
    cipher.updateAAD(aad);

    byte[]   cipherText = cipher.doFinal(requestData);
    byte[][] parts      = ByteUtil.split(cipherText, cipherText.length - TAG_LENGTH_BYTES, TAG_LENGTH_BYTES);

    byte[] mac  = parts[1];
    byte[] data = parts[0];

    return new AESEncryptedResult(iv, data, mac, aad);
  } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example 8
private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns) {
  try {
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagers, null);

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                                                   .sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
                                                   .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
                                                   .dns(dns.or(Dns.SYSTEM));

    builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
           .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
           .build();

    for (Interceptor interceptor : interceptors) {
      builder.addInterceptor(interceptor);
    }

    return builder.build();
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example 9
public synchronized WebSocketRequestMessage readRequest(long timeoutMillis)
    throws TimeoutException, IOException
{
  if (client == null) {
    throw new IOException("Connection closed!");
  }

  long startTime = System.currentTimeMillis();

  while (client != null && incomingRequests.isEmpty() && elapsedTime(startTime) < timeoutMillis) {
    Util.wait(this, Math.max(1, timeoutMillis - elapsedTime(startTime)));
  }

  if      (incomingRequests.isEmpty() && client == null) throw new IOException("Connection closed!");
  else if (incomingRequests.isEmpty())                   throw new TimeoutException("Timeout exceeded");
  else                                                   return incomingRequests.removeFirst();
}
 
Example 10
public byte[] encrypt(ProvisionMessage message) throws InvalidKeyException {
  ECKeyPair ourKeyPair    = Curve.generateKeyPair();
  byte[]    sharedSecret  = Curve.calculateAgreement(theirPublicKey, ourKeyPair.getPrivateKey());
  byte[]    derivedSecret = new HKDFv3().deriveSecrets(sharedSecret, "TextSecure Provisioning Message".getBytes(), 64);
  byte[][]  parts         = Util.split(derivedSecret, 32, 32);

  byte[] version    = {0x01};
  byte[] ciphertext = getCiphertext(parts[0], message.toByteArray());
  byte[] mac        = getMac(parts[1], Util.join(version, ciphertext));
  byte[] body       = Util.join(version, ciphertext, mac);

  return ProvisionEnvelope.newBuilder()
                          .setPublicKey(ByteString.copyFrom(ourKeyPair.getPublicKey().serialize()))
                          .setBody(ByteString.copyFrom(body))
                          .build()
                          .toByteArray();
}
 
Example 11
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 12
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 13
public void test_attachment_decryptFailOnBadMac() throws IOException {
  File    cipherFile          = null;
  boolean hitCorrectException = false;

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

    badMacCiphertext[badMacCiphertext.length - 1] += 1;

    cipherFile = writeToFile(badMacCiphertext);

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

  assertTrue(hitCorrectException);
}
 
Example 14
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] += 1;

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

  assertTrue(hitCorrectException);
}
 
Example 15
public void testStreams() throws Exception {
  ProfileKey                key  = new ProfileKey(Util.getSecretBytes(32));
  ByteArrayOutputStream     baos = new ByteArrayOutputStream();
  ProfileCipherOutputStream out  = new ProfileCipherOutputStream(baos, key);

  out.write("This is an avatar".getBytes());
  out.flush();
  out.close();

  ByteArrayInputStream     bais = new ByteArrayInputStream(baos.toByteArray());
  ProfileCipherInputStream in   = new ProfileCipherInputStream(bais, key);

  ByteArrayOutputStream result = new ByteArrayOutputStream();
  byte[]                buffer = new byte[2048];

  int read;

  while ((read = in.read(buffer)) != -1) {
    result.write(buffer, 0, read);
  }

  assertEquals(new String(result.toByteArray()), "This is an avatar");
}
 
Example 16
@Override
public void run() {
  long delayMillis = delayUntil - System.currentTimeMillis();
  Log.i(TAG, "Waiting to notify: " + delayMillis);

  if (delayMillis > 0) {
    Util.sleep(delayMillis);
  }

  if (!canceled.get()) {
    Log.i(TAG, "Not canceled, notifying...");
    ApplicationDependencies.getMessageNotifier().updateNotification(context, threadId, true);
    ApplicationDependencies.getMessageNotifier().cancelDelayedNotifications();
  } else {
    Log.w(TAG, "Canceled, not notifying...");
  }
}
 
Example 17
public AttachmentCipherOutputStream(byte[] combinedKeyMaterial,
                                    OutputStream outputStream)
    throws IOException
{
  super(outputStream);
  try {
    this.cipher       = initializeCipher();
    this.mac          = initializeMac();
    byte[][] keyParts = Util.split(combinedKeyMaterial, 32, 32);

    this.cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyParts[0], "AES"));
    this.mac.init(new SecretKeySpec(keyParts[1], "HmacSHA256"));

    mac.update(cipher.getIV());
    super.write(cipher.getIV());
  } catch (InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 18
public void testStreams() throws Exception {
  byte[]                    key  = Util.getSecretBytes(32);
  ByteArrayOutputStream     baos = new ByteArrayOutputStream();
  ProfileCipherOutputStream out  = new ProfileCipherOutputStream(baos, key);

  out.write("This is an avatar".getBytes());
  out.flush();
  out.close();

  ByteArrayInputStream     bais = new ByteArrayInputStream(baos.toByteArray());
  ProfileCipherInputStream in   = new ProfileCipherInputStream(bais, key);

  ByteArrayOutputStream result = new ByteArrayOutputStream();
  byte[]                buffer = new byte[2048];

  int read;

  while ((read = in.read(buffer)) != -1) {
    result.write(buffer, 0, read);
  }

  assertEquals(new String(result.toByteArray()), "This is an avatar");
}
 
Example 19
public byte[] encrypt(ProvisionMessage message) throws InvalidKeyException {
  ECKeyPair ourKeyPair    = Curve.generateKeyPair();
  byte[]    sharedSecret  = Curve.calculateAgreement(theirPublicKey, ourKeyPair.getPrivateKey());
  byte[]    derivedSecret = new HKDFv3().deriveSecrets(sharedSecret, "TextSecure Provisioning Message".getBytes(), 64);
  byte[][]  parts         = Util.split(derivedSecret, 32, 32);

  byte[] version    = {0x01};
  byte[] ciphertext = getCiphertext(parts[0], message.toByteArray());
  byte[] mac        = getMac(parts[1], Util.join(version, ciphertext));
  byte[] body       = Util.join(version, ciphertext, mac);

  return ProvisionEnvelope.newBuilder()
                          .setPublicKey(ByteString.copyFrom(ourKeyPair.getPublicKey().serialize()))
                          .setBody(ByteString.copyFrom(body))
                          .build()
                          .toByteArray();
}
 
Example 20
public void test_attachment_decryptFailOnBadMac() throws IOException {
  File    cipherFile          = null;
  boolean hitCorrectException = false;

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

    badMacCiphertext[badMacCiphertext.length - 1] = 0;

    cipherFile = writeToFile(badMacCiphertext);

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

  assertTrue(hitCorrectException);
}
 
Example 21
private void sendMessage(VerifiedMessage message, Optional<UnidentifiedAccessPair> unidentifiedAccess)
    throws IOException, UntrustedIdentityException
{
  byte[] nullMessageBody = DataMessage.newBuilder()
                                      .setBody(Base64.encodeBytes(Util.getRandomLengthBytes(140)))
                                      .build()
                                      .toByteArray();

  NullMessage nullMessage = NullMessage.newBuilder()
                                       .setPadding(ByteString.copyFrom(nullMessageBody))
                                       .build();

  byte[] content          = Content.newBuilder()
                                   .setNullMessage(nullMessage)
                                   .build()
                                   .toByteArray();

  SendMessageResult result = sendMessage(message.getDestination(), getTargetUnidentifiedAccess(unidentifiedAccess), message.getTimestamp(), content, false);

  if (result.getSuccess().isNeedsSync()) {
    byte[] syncMessage = createMultiDeviceVerifiedContent(message, nullMessage.toByteArray());
    sendMessage(localAddress, Optional.<UnidentifiedAccess>absent(), message.getTimestamp(), syncMessage, false);
  }
}
 
Example 22
/**
 * 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 23
public AttachmentCipherOutputStream(byte[] combinedKeyMaterial,
                                    OutputStream outputStream)
    throws IOException
{
  super(outputStream);
  try {
    this.cipher       = initializeCipher();
    this.mac          = initializeMac();
    byte[][] keyParts = Util.split(combinedKeyMaterial, 32, 32);

    this.cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyParts[0], "AES"));
    this.mac.init(new SecretKeySpec(keyParts[1], "HmacSHA256"));

    mac.update(cipher.getIV());
    super.write(cipher.getIV());
  } catch (InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 24
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 25
public DiscoveryRequest createDiscoveryRequest(List<String> addressBook, RemoteAttestation remoteAttestation) {
  try {
    ByteArrayOutputStream requestDataStream = new ByteArrayOutputStream();

    for (String address : addressBook) {
      requestDataStream.write(ByteUtil.longToByteArray(Long.parseLong(address)));
    }

    byte[]         requestData = requestDataStream.toByteArray();
    byte[]         nonce       = Util.getSecretBytes(12);
    Cipher         cipher      = Cipher.getInstance("AES/GCM/NoPadding");

    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(remoteAttestation.getKeys().getClientKey(), "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, nonce));
    cipher.updateAAD(remoteAttestation.getRequestId());

    byte[]   cipherText = cipher.doFinal(requestData);
    byte[][] parts      = ByteUtil.split(cipherText, cipherText.length - TAG_LENGTH_BYTES, TAG_LENGTH_BYTES);

    return new DiscoveryRequest(addressBook.size(), remoteAttestation.getRequestId(), nonce, parts[0], parts[1]);
  } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example 26
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 27
public synchronized WebSocketRequestMessage readRequest(long timeoutMillis)
    throws TimeoutException, IOException
{
  if (client == null) {
    throw new IOException("Connection closed!");
  }

  long startTime = System.currentTimeMillis();

  while (client != null && incomingRequests.isEmpty() && elapsedTime(startTime) < timeoutMillis) {
    Util.wait(this, Math.max(1, timeoutMillis - elapsedTime(startTime)));
  }

  if      (incomingRequests.isEmpty() && client == null) throw new IOException("Connection closed!");
  else if (incomingRequests.isEmpty())                   throw new TimeoutException("Timeout exceeded");
  else                                                   return incomingRequests.removeFirst();
}
 
Example 28
public byte[] encrypt(ProvisionMessage message) throws InvalidKeyException {
  ECKeyPair ourKeyPair    = Curve.generateKeyPair();
  byte[]    sharedSecret  = Curve.calculateAgreement(theirPublicKey, ourKeyPair.getPrivateKey());
  byte[]    derivedSecret = new HKDFv3().deriveSecrets(sharedSecret, "TextSecure Provisioning Message".getBytes(), 64);
  byte[][]  parts         = Util.split(derivedSecret, 32, 32);

  byte[] version    = {0x01};
  byte[] ciphertext = getCiphertext(parts[0], message.toByteArray());
  byte[] mac        = getMac(parts[1], Util.join(version, ciphertext));
  byte[] body       = Util.join(version, ciphertext, mac);

  return ProvisionEnvelope.newBuilder()
                          .setPublicKey(ByteString.copyFrom(ourKeyPair.getPublicKey().serialize()))
                          .setBody(ByteString.copyFrom(body))
                          .build()
                          .toByteArray();
}
 
Example 29
private String createDirectoryServerToken(String e164number, boolean urlSafe) {
  try {
    MessageDigest digest  = MessageDigest.getInstance("SHA1");
    byte[]        token   = Util.trim(digest.digest(e164number.getBytes()), 10);
    String        encoded = Base64.encodeBytesWithoutPadding(token);

    if (urlSafe) return encoded.replace('+', '-').replace('/', '_');
    else         return encoded;
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 30
private SignalServiceAttachmentPointer uploadAttachmentV2(SignalServiceAttachmentStream attachment, byte[] attachmentKey, PushAttachmentData attachmentData) throws NonSuccessfulResponseCodeException, PushNetworkException {
  AttachmentV2UploadAttributes       v2UploadAttributes = null;
  Optional<SignalServiceMessagePipe> localPipe          = pipe.get();

  if (localPipe.isPresent()) {
    Log.d(TAG, "Using pipe to retrieve attachment upload attributes...");
    try {
      v2UploadAttributes = localPipe.get().getAttachmentV2UploadAttributes();
    } catch (IOException e) {
      Log.w(TAG, "Failed to retrieve attachment upload attributes using pipe. Falling back...");
    }
  }

  if (v2UploadAttributes == null) {
    Log.d(TAG, "Not using pipe to retrieve attachment upload attributes...");
    v2UploadAttributes = socket.getAttachmentV2UploadAttributes();
  }

  Pair<Long, byte[]> attachmentIdAndDigest = socket.uploadAttachment(attachmentData, v2UploadAttributes);

  return new SignalServiceAttachmentPointer(0,
                                            new SignalServiceAttachmentRemoteId(attachmentIdAndDigest.first()),
                                            attachment.getContentType(),
                                            attachmentKey,
                                            Optional.of(Util.toIntExact(attachment.getLength())),
                                            attachment.getPreview(),
                                            attachment.getWidth(), attachment.getHeight(),
                                            Optional.of(attachmentIdAndDigest.second()),
                                            attachment.getFileName(),
                                            attachment.getVoiceNote(),
                                            attachment.getCaption(),
                                            attachment.getBlurHash(),
                                            attachment.getUploadTimestamp());
}