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

The following examples show how to use org.whispersystems.signalservice.internal.util.Hex. 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: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Upload the sticker pack from path.
 *
 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
 * @return if successful, returns the URL to install the sticker pack in the signal app
 */
public String uploadStickerPack(String path) throws IOException, StickerPackInvalidException {
    SignalServiceStickerManifestUpload manifest = getSignalServiceStickerManifestUpload(path);

    SignalServiceMessageSender messageSender = getMessageSender();

    byte[] packKey = KeyUtils.createStickerUploadKey();
    String packId = messageSender.uploadStickerManifest(manifest, packKey);

    try {
        return new URI("https", "signal.art", "/addstickers/", "pack_id=" + URLEncoder.encode(packId, "utf-8") + "&pack_key=" + URLEncoder.encode(Hex.toStringCondensed(packKey), "utf-8"))
                .toString();
    } catch (URISyntaxException e) {
        throw new AssertionError(e);
    }
}
 
Example #2
Source File: KeyBackupService.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private TokenResponse putKbsData(byte[] kbsAccessKey, byte[] kbsData, String enclaveName, TokenResponse token)
    throws IOException, UnauthenticatedResponseException
{
  try {
    RemoteAttestation     remoteAttestation = getAndVerifyRemoteAttestation();
    KeyBackupRequest      request           = KeyBackupCipher.createKeyBackupRequest(kbsAccessKey, kbsData, token, remoteAttestation, Hex.fromStringCondensed(enclaveName), maxTries);
    KeyBackupResponse     response          = pushServiceSocket.putKbsData(authorization, request, remoteAttestation.getCookies(), enclaveName);
    BackupResponse        backupResponse    = KeyBackupCipher.getKeyBackupResponse(response, remoteAttestation);
    BackupResponse.Status status            = backupResponse.getStatus();

    switch (status) {
      case OK:
        return backupResponse.hasToken() ? new TokenResponse(token.getBackupId(), backupResponse.getToken().toByteArray(), maxTries) : token;
      case ALREADY_EXISTS:
        throw new UnauthenticatedResponseException("Already exists");
      case NOT_YET_VALID:
        throw new UnauthenticatedResponseException("Key is not valid yet, clock mismatch");
      default:
        throw new AssertionError("Unknown response status " + status);
    }
  } catch (InvalidCiphertextException e) {
    throw new UnauthenticatedResponseException(e);
  }
}
 
Example #3
Source File: ContactDiscoveryCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void verifyServerQuote(Quote quote, byte[] serverPublicStatic, String mrenclave)
    throws UnauthenticatedQuoteException
{
  try {
    byte[] theirServerPublicStatic = new byte[serverPublicStatic.length];
    System.arraycopy(quote.getReportData(), 0, theirServerPublicStatic, 0, theirServerPublicStatic.length);

    if (!MessageDigest.isEqual(theirServerPublicStatic, serverPublicStatic)) {
      throw new UnauthenticatedQuoteException("Response quote has unauthenticated report data!");
    }

    if (!MessageDigest.isEqual(Hex.fromStringCondensed(mrenclave), quote.getMrenclave())) {
      throw new UnauthenticatedQuoteException("The response quote has the wrong mrenclave value in it: " + Hex.toStringCondensed(quote.getMrenclave()));
    }

    if (quote.isDebugQuote()) {
      throw new UnauthenticatedQuoteException("Received quote for debuggable enclave");
    }
  } catch (IOException e) {
    throw new UnauthenticatedQuoteException(e);
  }
}
 
Example #4
Source File: RemoteAttestationCipher.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static void verifyServerQuote(Quote quote, byte[] serverPublicStatic, String mrenclave)
    throws UnauthenticatedQuoteException
{
  try {
    byte[] theirServerPublicStatic = new byte[serverPublicStatic.length];
    System.arraycopy(quote.getReportData(), 0, theirServerPublicStatic, 0, theirServerPublicStatic.length);

    if (!MessageDigest.isEqual(theirServerPublicStatic, serverPublicStatic)) {
      throw new UnauthenticatedQuoteException("Response quote has unauthenticated report data!");
    }

    if (!MessageDigest.isEqual(Hex.fromStringCondensed(mrenclave), quote.getMrenclave())) {
      throw new UnauthenticatedQuoteException("The response quote has the wrong mrenclave value in it: " + Hex.toStringCondensed(quote.getMrenclave()));
    }

    if (quote.isDebugQuote()) {
      throw new UnauthenticatedQuoteException("Received quote for debuggable enclave");
    }
  } catch (IOException e) {
    throw new UnauthenticatedQuoteException(e);
  }
}
 
Example #5
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public ProfileAndCredential retrieveVersionedProfileAndCredential(UUID target, ProfileKey profileKey, Optional<UnidentifiedAccess> unidentifiedAccess)
    throws NonSuccessfulResponseCodeException, PushNetworkException, VerificationFailedException
{
  ProfileKeyVersion                  profileKeyIdentifier = profileKey.getProfileKeyVersion(target);
  ProfileKeyCredentialRequestContext requestContext       = clientZkProfileOperations.createProfileKeyCredentialRequestContext(random, target, profileKey);
  ProfileKeyCredentialRequest        request              = requestContext.getRequest();

  String version           = profileKeyIdentifier.serialize();
  String credentialRequest = Hex.toStringCondensed(request.serialize());
  String subPath           = String.format("%s/%s/%s", target, version, credentialRequest);

  String response = makeServiceRequest(String.format(PROFILE_PATH, subPath), "GET", null, NO_HEADERS, unidentifiedAccess);

  try {
    SignalServiceProfile signalServiceProfile = JsonUtil.fromJson(response, SignalServiceProfile.class);

    ProfileKeyCredential profileKeyCredential = signalServiceProfile.getProfileKeyCredentialResponse() != null
                                              ? clientZkProfileOperations.receiveProfileKeyCredential(requestContext, signalServiceProfile.getProfileKeyCredentialResponse())
                                              : null;

    return new ProfileAndCredential(signalServiceProfile, SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL, Optional.fromNullable(profileKeyCredential));
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example #6
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public byte[] retrieveSticker(byte[] packId, int stickerId)
    throws NonSuccessfulResponseCodeException, PushNetworkException {
  String                hexPackId = Hex.toStringCondensed(packId);
  ByteArrayOutputStream output    = new ByteArrayOutputStream();

  try {
    downloadFromCdn(output, 0, 0, String.format(Locale.US, STICKER_PATH, hexPackId, stickerId), 1024 * 1024, null);
  } catch (MissingConfigurationException e) {
    throw new AssertionError(e);
  }

  return output.toByteArray();
}
 
Example #7
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public byte[] retrieveStickerManifest(byte[] packId)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                hexPackId = Hex.toStringCondensed(packId);
  ByteArrayOutputStream output    = new ByteArrayOutputStream();

  downloadFromCdn(output, String.format(STICKER_MANIFEST_PATH, hexPackId), 1024 * 1024, null);

  return output.toByteArray();
}
 
Example #8
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public byte[] retrieveSticker(byte[] packId, int stickerId)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                hexPackId = Hex.toStringCondensed(packId);
  ByteArrayOutputStream output    = new ByteArrayOutputStream();

  downloadFromCdn(output, String.format(Locale.US, STICKER_PATH, hexPackId, stickerId), 1024 * 1024, null);

  return output.toByteArray();
}
 
Example #9
Source File: ContactDiscoveryCipher.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public void verifyIasSignature(KeyStore trustStore, String certificates, String signatureBody, String signature, Quote quote)
    throws SignatureException
{
  if (certificates == null || certificates.isEmpty()) {
    throw new SignatureException("No certificates.");
  }

  try {
    SigningCertificate signingCertificate = new SigningCertificate(certificates, trustStore);
    signingCertificate.verifySignature(signatureBody, signature);

    SignatureBodyEntity signatureBodyEntity = JsonUtil.fromJson(signatureBody, SignatureBodyEntity.class);

    if (signatureBodyEntity.getVersion() != SIGNATURE_BODY_VERSION) {
      throw new SignatureException("Unexpected signed quote version " + signatureBodyEntity.getVersion());
    }

    if (!MessageDigest.isEqual(ByteUtil.trim(signatureBodyEntity.getIsvEnclaveQuoteBody(), 432), ByteUtil.trim(quote.getQuoteBytes(), 432))) {
      throw new SignatureException("Signed quote is not the same as RA quote: " + Hex.toStringCondensed(signatureBodyEntity.getIsvEnclaveQuoteBody()) + " vs " + Hex.toStringCondensed(quote.getQuoteBytes()));
    }

    if (!"OK".equals(signatureBodyEntity.getIsvEnclaveQuoteStatus())) {
      throw new SignatureException("Quote status is: " + signatureBodyEntity.getIsvEnclaveQuoteStatus());
    }

    if (Instant.from(ZonedDateTime.of(LocalDateTime.from(DateTimeFormatter.ofPattern("yyy-MM-dd'T'HH:mm:ss.SSSSSS").parse(signatureBodyEntity.getTimestamp())), ZoneId.of("UTC")))
               .plus(Period.ofDays(1))
               .isBefore(Instant.now()))
    {
      throw new SignatureException("Signature is expired");
    }

  } catch (CertificateException | CertPathValidatorException | IOException e) {
    throw new SignatureException(e);
  }
}
 
Example #10
Source File: SignalServiceEnvelope.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
private void verifyMac(byte[] ciphertext, SecretKeySpec macKey) throws IOException {
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(macKey);

    if (ciphertext.length < MAC_SIZE + 1)
      throw new IOException("Invalid MAC!");

    mac.update(ciphertext, 0, ciphertext.length - MAC_SIZE);

    byte[] ourMacFull  = mac.doFinal();
    byte[] ourMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ourMacFull, 0, ourMacBytes, 0, ourMacBytes.length);

    byte[] theirMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ciphertext, ciphertext.length-MAC_SIZE, theirMacBytes, 0, theirMacBytes.length);

    Log.w(TAG, "Our MAC: " + Hex.toString(ourMacBytes));
    Log.w(TAG, "Thr MAC: " + Hex.toString(theirMacBytes));

    if (!Arrays.equals(ourMacBytes, theirMacBytes)) {
      throw new IOException("Invalid MAC compare!");
    }
  } catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example #11
Source File: PinHasher_normalize_Test.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void vectors_normalize() throws IOException {
  for (PinSanitationVector vector : getKbsPinSanitationTestVectorList()) {
    byte[] normalized = PinHasher.normalize(vector.getPin());

    if (!Arrays.equals(vector.getBytes(), normalized)) {
      assertEquals(String.format("%s [%s]", vector.getName(), vector.getPin()),
                   Hex.toStringCondensed(vector.getBytes()),
                   Hex.toStringCondensed(normalized));
    }
  }
}
 
Example #12
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public byte[] retrieveStickerManifest(byte[] packId)
    throws NonSuccessfulResponseCodeException, PushNetworkException {
  String                hexPackId = Hex.toStringCondensed(packId);
  ByteArrayOutputStream output    = new ByteArrayOutputStream();

  try {
    downloadFromCdn(output, 0, 0, String.format(STICKER_MANIFEST_PATH, hexPackId), 1024 * 1024, null);
  } catch (MissingConfigurationException e) {
    throw new AssertionError(e);
  }

  return output.toByteArray();
}
 
Example #13
Source File: RemoteAttestationCipher.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static void verifyIasSignature(KeyStore trustStore, String certificates, String signatureBody, String signature, Quote quote)
    throws SignatureException
{
  if (certificates == null || certificates.isEmpty()) {
    throw new SignatureException("No certificates.");
  }

  try {
    SigningCertificate signingCertificate = new SigningCertificate(certificates, trustStore);
    signingCertificate.verifySignature(signatureBody, signature);

    SignatureBodyEntity signatureBodyEntity = JsonUtil.fromJson(signatureBody, SignatureBodyEntity.class);

    if (signatureBodyEntity.getVersion() != SIGNATURE_BODY_VERSION) {
      throw new SignatureException("Unexpected signed quote version " + signatureBodyEntity.getVersion());
    }

    if (!MessageDigest.isEqual(ByteUtil.trim(signatureBodyEntity.getIsvEnclaveQuoteBody(), 432), ByteUtil.trim(quote.getQuoteBytes(), 432))) {
      throw new SignatureException("Signed quote is not the same as RA quote: " + Hex.toStringCondensed(signatureBodyEntity.getIsvEnclaveQuoteBody()) + " vs " + Hex.toStringCondensed(quote.getQuoteBytes()));
    }

    if (!"OK".equals(signatureBodyEntity.getIsvEnclaveQuoteStatus())) {
      throw new SignatureException("Quote status is: " + signatureBodyEntity.getIsvEnclaveQuoteStatus());
    }

    if (Instant.from(ZonedDateTime.of(LocalDateTime.from(DateTimeFormatter.ofPattern("yyy-MM-dd'T'HH:mm:ss.SSSSSS").parse(signatureBodyEntity.getTimestamp())), ZoneId.of("UTC")))
               .plus(Period.ofDays(1))
               .isBefore(Instant.now()))
    {
      throw new SignatureException("Signature is expired");
    }

  } catch (CertificateException | CertPathValidatorException | IOException e) {
    throw new SignatureException(e);
  }
}
 
Example #14
Source File: SignalServiceEnvelope.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void verifyMac(byte[] ciphertext, SecretKeySpec macKey) throws IOException {
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(macKey);

    if (ciphertext.length < MAC_SIZE + 1)
      throw new IOException("Invalid MAC!");

    mac.update(ciphertext, 0, ciphertext.length - MAC_SIZE);

    byte[] ourMacFull  = mac.doFinal();
    byte[] ourMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ourMacFull, 0, ourMacBytes, 0, ourMacBytes.length);

    byte[] theirMacBytes = new byte[MAC_SIZE];
    System.arraycopy(ciphertext, ciphertext.length-MAC_SIZE, theirMacBytes, 0, theirMacBytes.length);

    Log.w(TAG, "Our MAC: " + Hex.toString(ourMacBytes));
    Log.w(TAG, "Thr MAC: " + Hex.toString(theirMacBytes));

    if (!Arrays.equals(ourMacBytes, theirMacBytes)) {
      throw new IOException("Invalid MAC compare!");
    }
  } catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example #15
Source File: MasterKey.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String deriveRegistrationLock() {
  return Hex.toStringCondensed(derive("Registration Lock"));
}
 
Example #16
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public void retrieveSticker(File destination, byte[] packId, int stickerId)
    throws NonSuccessfulResponseCodeException, PushNetworkException, MissingConfigurationException {
  String hexPackId = Hex.toStringCondensed(packId);
  downloadFromCdn(destination, 0, String.format(Locale.US, STICKER_PATH, hexPackId, stickerId), 1024 * 1024, null);
}
 
Example #17
Source File: KeyBackupRequest.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{ type:" + type + ", requestId: " + Hex.toString(requestId) + ", iv: " + Hex.toString(iv) + ", data: " + Hex.toString(data) + ", mac: " + Hex.toString(mac) + "}";
}
 
Example #18
Source File: DiscoveryRequest.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{ addressCount: " + addressCount + ", ticket: " + Hex.toString(requestId) + ", iv: " + Hex.toString(iv) + ", data: " + Hex.toString(data) + ", mac: " + Hex.toString(mac) + "}";
}
 
Example #19
Source File: DiscoveryResponse.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{iv: " + (iv == null ? null : Hex.toString(iv)) + ", data: " + (data == null ? null: Hex.toString(data)) + ", mac: " + (mac == null ? null : Hex.toString(mac)) + "}";
}
 
Example #20
Source File: DiscoveryRequest.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{ addressCount: " + addressCount + ", ticket: " + Hex.toString(requestId) + ", iv: " + Hex.toString(iv) + ", data: " + Hex.toString(data) + ", mac: " + Hex.toString(mac) + "}";
}
 
Example #21
Source File: DiscoveryResponse.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{iv: " + (iv == null ? null : Hex.toString(iv)) + ", data: " + (data == null ? null: Hex.toString(data)) + ", mac: " + (mac == null ? null : Hex.toString(mac)) + "}";
}
 
Example #22
Source File: KeyBackupResponse.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public String toString() {
  return "{iv: " + (iv == null ? null : Hex.toString(iv)) + ", data: " + (data == null ? null: Hex.toString(data)) + ", mac: " + (mac == null ? null : Hex.toString(mac)) + "}";
}
 
Example #23
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public void retrieveSticker(File destination, byte[] packId, int stickerId)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String hexPackId = Hex.toStringCondensed(packId);
  downloadFromCdn(destination, String.format(Locale.US, STICKER_PATH, hexPackId, stickerId), 1024 * 1024, null);
}
 
Example #24
Source File: KeyBackupService.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private KbsPinData restorePin(HashedPin hashedPin, TokenResponse token)
  throws UnauthenticatedResponseException, IOException, TokenException, KeyBackupSystemNoDataException
{
  try {
    final int               remainingTries    = token.getTries();
    final RemoteAttestation remoteAttestation = getAndVerifyRemoteAttestation();
    final KeyBackupRequest  request           = KeyBackupCipher.createKeyRestoreRequest(hashedPin.getKbsAccessKey(), token, remoteAttestation, Hex.fromStringCondensed(enclaveName));
    final KeyBackupResponse response          = pushServiceSocket.putKbsData(authorization, request, remoteAttestation.getCookies(), enclaveName);
    final RestoreResponse   status            = KeyBackupCipher.getKeyRestoreResponse(response, remoteAttestation);

    TokenResponse nextToken = status.hasToken()
                              ? new TokenResponse(token.getBackupId(), status.getToken().toByteArray(), status.getTries())
                              : token;

    Log.i(TAG, "Restore " + status.getStatus());
    switch (status.getStatus()) {
      case OK:
        KbsData kbsData = hashedPin.decryptKbsDataIVCipherText(status.getData().toByteArray());
        MasterKey masterKey = kbsData.getMasterKey();
        return new KbsPinData(masterKey, nextToken);
      case PIN_MISMATCH:
        Log.i(TAG, "Restore PIN_MISMATCH");
        throw new KeyBackupServicePinException(nextToken);
      case TOKEN_MISMATCH:
        Log.i(TAG, "Restore TOKEN_MISMATCH");
        // if the number of tries has not fallen, the pin is correct we're just using an out of date token
        boolean canRetry = remainingTries == status.getTries();
        Log.i(TAG, String.format(Locale.US, "Token MISMATCH %d %d", remainingTries, status.getTries()));
        throw new TokenException(nextToken, canRetry);
      case MISSING:
        Log.i(TAG, "Restore OK! No data though");
        throw new KeyBackupSystemNoDataException();
      case NOT_YET_VALID:
        throw new UnauthenticatedResponseException("Key is not valid yet, clock mismatch");
      default:
        throw new AssertionError("Unexpected case");
    }
  } catch (InvalidCiphertextException e) {
    throw new UnauthenticatedResponseException(e);
  }
}
 
Example #25
Source File: GroupsV2AuthorizationString.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
GroupsV2AuthorizationString(GroupSecretParams groupSecretParams, AuthCredentialPresentation authCredentialPresentation) {
  String username = Hex.toStringCondensed(groupSecretParams.getPublicParams().serialize());
  String password = Hex.toStringCondensed(authCredentialPresentation.serialize());

  authString = Credentials.basic(username, password);
}