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

The following examples show how to use org.whispersystems.signalservice.internal.util.Util. 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: AttachmentCipherOutputStream.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
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 #2
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: AESCipher.java    From mollyim-android with 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 #4
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 #5
Source File: WebSocketConnection.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: ProfileCipher.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 File: ProvisioningCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: AttachmentCipherOutputStream.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #9
Source File: SignalServiceMessageSender.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #10
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 #11
Source File: SignalServiceMessageSender.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #12
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: ContactDiscoveryCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #14
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 #15
Source File: AttachmentCipherOutputStream.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: ProvisioningCipher.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #17
Source File: SignalServiceMessageReceiver.java    From libsignal-service-java 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 #18
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #19
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 #20
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 #21
Source File: AttachmentCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #22
Source File: AttachmentCipherTest.java    From mollyim-android 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] += 1;

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

  assertTrue(hitCorrectException);
}
 
Example #23
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_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 #24
Source File: ProvisioningCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
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 #25
Source File: ProfileCipherTest.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #26
Source File: ProfileCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #27
Source File: DefaultMessageNotifier.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #28
Source File: SignalServiceMessageSender.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #29
Source File: AttachmentCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public void test_attachment_encryptDecrypt() throws IOException, InvalidMessageException {
  byte[]        key             = Util.getSecretBytes(64);
  byte[]        plaintextInput  = "Peter Parker".getBytes();
  EncryptResult encryptResult   = encryptData(plaintextInput, key);
  File          cipherFile      = writeToFile(encryptResult.ciphertext);
  InputStream   inputStream     = AttachmentCipherInputStream.createForAttachment(cipherFile, plaintextInput.length, key, encryptResult.digest);
  byte[]        plaintextOutput = readInputStreamFully(inputStream);

  assertTrue(Arrays.equals(plaintextInput, plaintextOutput));

  cipherFile.delete();
}
 
Example #30
Source File: ProfileCipherTest.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public void testEncryptDecrypt() throws InvalidCiphertextException {
  byte[]        key       = Util.getSecretBytes(32);
  ProfileCipher cipher    = new ProfileCipher(key);
  byte[]        name      = cipher.encryptName("Clement Duval".getBytes(), 26);
  byte[]        plaintext = cipher.decryptName(name);
  assertEquals(new String(plaintext), "Clement Duval");
}