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

The following examples show how to use org.whispersystems.signalservice.internal.util.Base64. 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: SignalServiceCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public OutgoingPushMessage encrypt(SignalProtocolAddress destination, byte[] unpaddedMessage, PushPurpose pushPurpose)
    throws UntrustedIdentityException
{
  SessionCipher        sessionCipher        = new SessionCipher(signalProtocolStore, destination);
  PushTransportDetails transportDetails     = new PushTransportDetails(sessionCipher.getSessionVersion());
  CiphertextMessage    message              = sessionCipher.encrypt(transportDetails.getPaddedMessageBody(unpaddedMessage));
  int                  remoteRegistrationId = sessionCipher.getRemoteRegistrationId();
  String               body                 = Base64.encodeBytes(message.serialize());

  int type;

  switch (message.getType()) {
    case CiphertextMessage.PREKEY_TYPE:  type = Type.PREKEY_BUNDLE_VALUE; break;
    case CiphertextMessage.WHISPER_TYPE: type = Type.CIPHERTEXT_VALUE;    break;
    default: throw new AssertionError("Bad type: " + message.getType());
  }

  return new OutgoingPushMessage(type, destination.getDeviceId(), remoteRegistrationId, body, pushPurpose);
}
 
Example #2
Source File: GroupStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public GroupStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    GroupStore store = new GroupStore();
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    if(!node.has("groups")) {
        return store;
    }
    for (JsonNode n : node.get("groups")) {
        logger.debug("Loading node %s", n.asText());
        GroupInfo g = jsonProcessor.treeToValue(n, GroupInfo.class);
        // Check if a legacy avatarId exists
        if (g.getAvatarId() != 0) {
            groupsWithLegacyAvatarId.add(g);
        }
        store.groups.put(Base64.encodeBytes(g.groupId), g);
    }

    return store;
}
 
Example #3
Source File: PreKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    Map<Integer, byte[]> preKeyMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode preKey : node) {
            Integer preKeyId = preKey.get("id").asInt();
            try {
                preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding prekey for: %s", preKeyId));
            }
        }
    }
    PreKeyStore keyStore = new PreKeyStore();
    keyStore.store.putAll(preKeyMap);
    return keyStore;
}
 
Example #4
Source File: SignedPreKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SignedPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    Map<Integer, byte[]> preKeyMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode preKey : node) {
            Integer preKeyId = preKey.get("id").asInt();
            try {
                preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding prekey for: %s", preKeyId));
            }
        }
    }
    SignedPreKeyStore keyStore = new SignedPreKeyStore();
    keyStore.store.putAll(preKeyMap);
    return keyStore;
}
 
Example #5
Source File: IdentityKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void serialize(IdentityKeyStore jsonIdentityKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
    json.writeStartObject();
    json.writeNumberField("registrationId", jsonIdentityKeyStore.getLocalRegistrationId());
    json.writeStringField("identityKey", org.whispersystems.signalservice.internal.util.Base64.encodeBytes(jsonIdentityKeyStore.getIdentityKeyPair().serialize()));
    json.writeArrayFieldStart("trustedKeys");
    for (Map.Entry<String, List<IdentityKeyStore.Identity>> trustedKey : jsonIdentityKeyStore.trustedKeys.entrySet()) {
        for (IdentityKeyStore.Identity id : trustedKey.getValue()) {
            json.writeStartObject();
            json.writeStringField("name", trustedKey.getKey());
            json.writeStringField("identityKey", Base64.encodeBytes(id.identityKey.serialize()));
            json.writeNumberField("trustLevel", id.trustLevel.ordinal());
            json.writeNumberField("addedTimestamp", id.added.getTime());
            json.writeEndObject();
        }
    }
    json.writeEndArray();
    json.writeEndObject();
}
 
Example #6
Source File: SessionStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SessionStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    Map<SignalProtocolAddress, byte[]> sessionMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode session : node) {
            String sessionName = session.get("name").asText();
            try {
                sessionMap.put(new SignalProtocolAddress(sessionName, session.get("deviceId").asInt()), org.whispersystems.signalservice.internal.util.Base64.decode(session.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding session for: %s", sessionName));
            }
        }
    }
    SessionStore sessionStore = new SessionStore();
    sessionStore.sessions.putAll(sessionMap);
    return sessionStore;
}
 
Example #7
Source File: JsonGroupInfo.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
JsonGroupInfo(SignalServiceGroup groupInfo, String username) throws IOException, NoSuchAccountException {
    Manager manager = Manager.get(username);
    this.groupId = Base64.encodeBytes(groupInfo.getGroupId());
    if (groupInfo.getMembers().isPresent()) {
        this.members = groupInfo.getMembers().get();
    }
    if (groupInfo.getName().isPresent()) {
        this.name = groupInfo.getName().get();
    } else {
        GroupInfo group = manager.getGroup(groupInfo.getGroupId());
        if(group != null) {
            this.name = group.name;
        }
    }

    this.type = groupInfo.getType().toString();
}
 
Example #8
Source File: JsonPreKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);


    Map<Integer, byte[]> preKeyMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode preKey : node) {
            Integer preKeyId = preKey.get("id").asInt();
            try {
                preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding prekey for: %s", preKeyId));
            }
        }
    }

    JsonPreKeyStore keyStore = new JsonPreKeyStore();
    keyStore.addPreKeys(preKeyMap);

    return keyStore;

}
 
Example #9
Source File: JsonSignedPreKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonSignedPreKeyStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);


    Map<Integer, byte[]> preKeyMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode preKey : node) {
            Integer preKeyId = preKey.get("id").asInt();
            try {
                preKeyMap.put(preKeyId, Base64.decode(preKey.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding prekey for: %s", preKeyId));
            }
        }
    }

    JsonSignedPreKeyStore keyStore = new JsonSignedPreKeyStore();
    keyStore.addSignedPreKeys(preKeyMap);

    return keyStore;

}
 
Example #10
Source File: JsonIdentityKeyStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void serialize(JsonIdentityKeyStore jsonIdentityKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
    json.writeStartObject();
    json.writeNumberField("registrationId", jsonIdentityKeyStore.getLocalRegistrationId());
    json.writeStringField("identityKey", Base64.encodeBytes(jsonIdentityKeyStore.getIdentityKeyPair().serialize()));
    json.writeArrayFieldStart("trustedKeys");
    for (Map.Entry<String, List<Identity>> trustedKey : jsonIdentityKeyStore.trustedKeys.entrySet()) {
        for (Identity id : trustedKey.getValue()) {
            json.writeStartObject();
            json.writeStringField("name", trustedKey.getKey());
            json.writeStringField("identityKey", Base64.encodeBytes(id.identityKey.serialize()));
            json.writeNumberField("trustLevel", id.trustLevel.ordinal());
            json.writeNumberField("addedTimestamp", id.added.getTime());
            json.writeEndObject();
        }
    }
    json.writeEndArray();
    json.writeEndObject();
}
 
Example #11
Source File: JsonSessionStore.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonSessionStore deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    Map<SignalProtocolAddress, byte[]> sessionMap = new HashMap<>();
    if (node.isArray()) {
        for (JsonNode session : node) {
            String sessionName = session.get("name").asText();
            try {
                sessionMap.put(new SignalProtocolAddress(sessionName, session.get("deviceId").asInt()), Base64.decode(session.get("record").asText()));
            } catch (IOException e) {
                System.out.println(String.format("Error while decoding session for: %s", sessionName));
            }
        }
    }

    JsonSessionStore sessionStore = new JsonSessionStore();
    sessionStore.addSessions(sessionMap);

    return sessionStore;

}
 
Example #12
Source File: JsonGroupStore.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, GroupInfo> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    Map<String, GroupInfo> groups = new HashMap<>();
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    for (JsonNode n : node) {
        GroupInfo g = jsonProcessor.treeToValue(n, GroupInfo.class);
        // Check if a legacy avatarId exists
        if (g.getAvatarId() != 0) {
            groupsWithLegacyAvatarId.add(g);
        }
        groups.put(Base64.encodeBytes(g.groupId), g);
    }

    return groups;
}
 
Example #13
Source File: PreKeyStore.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(PreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
    json.writeStartArray();
    for (Map.Entry<Integer, byte[]> preKey : jsonPreKeyStore.store.entrySet()) {
        json.writeStartObject();
        json.writeNumberField("id", preKey.getKey());
        json.writeStringField("record", Base64.encodeBytes(preKey.getValue()));
        json.writeEndObject();
    }
    json.writeEndArray();
}
 
Example #14
Source File: IdentityKeyAdapter.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IdentityKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
  if (null == json) {
    return null;
  }

  try {
    String jsonString = json.getAsString();
    return new IdentityKey(Base64.decodeWithoutPadding(jsonString), 0);
  } catch (Throwable e) {
    throw new JsonParseException(e);
  }
}
 
Example #15
Source File: SignedPreKeyStore.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(SignedPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
    json.writeStartArray();
    for (Map.Entry<Integer, byte[]> signedPreKey : jsonPreKeyStore.store.entrySet()) {
        json.writeStartObject();
        json.writeNumberField("id", signedPreKey.getKey());
        json.writeStringField("record", Base64.encodeBytes(signedPreKey.getValue()));
        json.writeEndObject();
    }
    json.writeEndArray();
}
 
Example #16
Source File: IdentityKeyAdapter.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(IdentityKey src, Type typeOfSrc, JsonSerializationContext context) {
  if (null == src) {
    return null;
  }
  return new JsonPrimitive(Base64.encodeBytesWithoutPadding(src.serialize()));
}
 
Example #17
Source File: PreKeyEntity.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ECPublicKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (null != json) {
        try {
            String publicSting = json.getAsString();
            return Curve.decodePoint(Base64.decodeWithoutPadding(publicSting), 0);
        } catch (Throwable e) {
            throw new JsonParseException("unknown public key", e);
        }
    }
    return null;
}
 
Example #18
Source File: SessionStore.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(SessionStore jsonSessionStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException {
    json.writeStartArray();
    for (Map.Entry<SignalProtocolAddress, byte[]> preKey : jsonSessionStore.sessions.entrySet()) {
        json.writeStartObject();
        json.writeStringField("name", preKey.getKey().getName());
        json.writeNumberField("deviceId", preKey.getKey().getDeviceId());
        json.writeStringField("record", Base64.encodeBytes(preKey.getValue()));
        json.writeEndObject();
    }
    json.writeEndArray();
}
 
Example #19
Source File: SocketHandler.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private void getProfile(JsonRequest request) throws IOException, InvalidCiphertextException, NoSuchAccountException {
    Manager m = Manager.get(request.username);
    ContactInfo contact = m.getContact(request.recipientNumber);
    if(contact == null || contact.profileKey == null) {
        this.reply("profile_not_available", null, request.id);
        return;
    }
    this.reply("profile", new JsonProfile(m.getProfile(request.recipientNumber), Base64.decode(contact.profileKey)), request.id);
}
 
Example #20
Source File: SocketHandler.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private void setExpiration(JsonRequest request) throws IOException, GroupNotFoundException, NotAGroupMemberException, AttachmentInvalidException, UntrustedIdentityException, EncapsulatedExceptions, NoSuchAccountException {
  Manager m = Manager.get(request.username);

  if(request.recipientGroupId != null) {
    byte[] groupId = Base64.decode(request.recipientGroupId);
    m.setExpiration(groupId, request.expiresInSeconds);
  } else {
    m.setExpiration(request.recipientNumber, request.expiresInSeconds);
  }

  this.reply("expiration_updated", null, request.id);
}
 
Example #21
Source File: SocketHandler.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private void updateGroup(JsonRequest request) throws IOException, EncapsulatedExceptions, UntrustedIdentityException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, NoSuchAccountException {
  Manager m = Manager.get(request.username);

  byte[] groupId = null;
  if(request.recipientGroupId != null) {
    groupId = Base64.decode(request.recipientGroupId);
  }
  if (groupId == null) {
      groupId = new byte[0];
  }

  String groupName = request.groupName;
  if(groupName == null) {
      groupName = "";
  }

  List<String> groupMembers = request.members;
  if (groupMembers == null) {
      groupMembers = new ArrayList<>();
  }

  String groupAvatar = request.avatar;
  if (groupAvatar == null) {
      groupAvatar = "";
  }

  byte[] newGroupId = m.updateGroup(groupId, groupName, groupMembers, groupAvatar);

  if (groupId.length != newGroupId.length) {
      this.reply("group_created", new JsonStatusMessage(5, "Created new group " + groupName + "."), request.id);
  } else {
      this.reply("group_updated", new JsonStatusMessage(6, "Updated group"), request.id);
  }
}
 
Example #22
Source File: JsonTypingMessage.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
JsonTypingMessage(SignalServiceTypingMessage typingMessage) {
    action = typingMessage.getAction().name();
    timestamp = typingMessage.getTimestamp();
    if(typingMessage.getGroupId().isPresent()) {
      groupId = Base64.encodeBytes(typingMessage.getGroupId().get());
    }
}
 
Example #23
Source File: JsonAttachment.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
JsonAttachment(SignalServiceAttachment attachment, String username) throws IOException, NoSuchAccountException {
    this.contentType = attachment.getContentType();
    final SignalServiceAttachmentPointer pointer = attachment.asPointer();
    if (attachment.isPointer()) {
        this.id = pointer.getId();
        this.key = Base64.encodeBytes(pointer.getKey());

        if (pointer.getSize().isPresent()) {
            this.size = pointer.getSize().get();
        }

        if(pointer.getPreview().isPresent()) {
            this.preview = Base64.encodeBytes(pointer.getPreview().get());
        }

        if(pointer.getDigest().isPresent()) {
            this.digest = Base64.encodeBytes(pointer.getDigest().get());
        }

        this.voiceNote = pointer.getVoiceNote();

        this.width = pointer.getWidth();
        this.height = pointer.getHeight();

        if(pointer.getCaption().isPresent()) {
            this.caption = pointer.getCaption().get();
        }

        if(pointer.getBlurHash().isPresent()) {
            this.blurhash = pointer.getBlurHash().get();
        }

        File file = Manager.get(username).getAttachmentFile(pointer.getId());
        if(file.exists()) {
            this.storedFilename = file.toString();
        }
    }
}
 
Example #24
Source File: BcmHash.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static String hashPhone(String phone, Boolean urlSafe) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] token = Util.trim(digest.digest(phone.getBytes()), 10);
        String encoded = Base64.encodeBytesWithoutPadding(token);

        if (urlSafe) {
            return encoded.replace('+', '-').replace('/', '_');
        } else {
            return encoded;
        }
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}
 
Example #25
Source File: Manager.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private static CertificateValidator getCertificateValidator() {
    try {
        ECPublicKey unidentifiedSenderTrustRoot = Curve.decodePoint(Base64.decode(BuildConfig.UNIDENTIFIED_SENDER_TRUST_ROOT), 0);
        return new CertificateValidator(unidentifiedSenderTrustRoot);
    } catch (InvalidKeyException | IOException e) {
        throw new AssertionError(e);
    }
}
 
Example #26
Source File: Manager.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
    Map<String, String> query = getQueryMap(linkUri.getRawQuery());
    String deviceIdentifier = query.get("uuid");
    String publicKeyEncoded = query.get("pub_key");

    if (isEmpty(deviceIdentifier) || isEmpty(publicKeyEncoded)) {
        throw new RuntimeException("Invalid device link uri");
    }

    ECPublicKey deviceKey = Curve.decodePoint(Base64.decode(publicKeyEncoded), 0);

    addDevice(deviceIdentifier, deviceKey);
}
 
Example #27
Source File: Manager.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
public URI getDeviceLinkUri() throws TimeoutException, IOException {
    accountData.password = Util.getSecret(18);

    accountManager = new SignalServiceAccountManager(serviceConfiguration, accountData.username, accountData.password, USER_AGENT, sleepTimer);
    String uuid = accountManager.getNewDeviceUuid();

    accountData.registered = false;
    try {
        return new URI("tsdevice:/?uuid=" + URLEncoder.encode(uuid, "utf-8") + "&pub_key=" + URLEncoder.encode(Base64.encodeBytesWithoutPadding(accountData.axolotlStore.identityKeyStore.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
    } catch (URISyntaxException e) {
        // Shouldn't happen
        return null;
    }
}
 
Example #28
Source File: JsonProfile.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
JsonProfile(SignalServiceProfile p, byte[] profileKey) throws IOException, InvalidCiphertextException {
    ProfileCipher profileCipher = new ProfileCipher(profileKey);
    name = new String(profileCipher.decryptName(Base64.decode(p.getName())));
    identity_key = p.getIdentityKey();
    avatar = p.getAvatar();
    unidentified_access = p.getUnidentifiedAccess();
    if (p.isUnrestrictedUnidentifiedAccess()) {
        unrestricted_unidentified_access = true;
    }

}
 
Example #29
Source File: JsonPreKeyStore.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(JsonPreKeyStore jsonPreKeyStore, JsonGenerator json, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    json.writeStartArray();
    for (Map.Entry<Integer, byte[]> preKey : jsonPreKeyStore.store.entrySet()) {
        json.writeStartObject();
        json.writeNumberField("id", preKey.getKey());
        json.writeStringField("record", Base64.encodeBytes(preKey.getValue()));
        json.writeEndObject();
    }
    json.writeEndArray();
}
 
Example #30
Source File: SignalBot.java    From signal-bot with GNU General Public License v3.0 5 votes vote down vote up
public void register(String username) throws IOException, BackingStoreException {
    logger.info("Sending verification SMS to " + username + ".");
    prefs.clear();
    String password = Base64.encodeBytes(Util.getSecretBytes(18));
    prefs.put("LOCAL_USERNAME", username);
    prefs.put("LOCAL_PASSWORD", password);
    accountManager = new SignalServiceAccountManager(config, username, password, USER_AGENT);
    accountManager.requestSmsVerificationCode(false);
}