Java Code Examples for org.whispersystems.libsignal.util.KeyHelper

The following examples show how to use org.whispersystems.libsignal.util.KeyHelper. 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
Source Project: Silence   Source File: SessionBuilder.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initiate a new session by sending an initial KeyExchangeMessage to the recipient.
 *
 * @return the KeyExchangeMessage to deliver.
 */
public KeyExchangeMessage process() {
  synchronized (SessionCipher.SESSION_LOCK) {
    try {
      int             sequence         = KeyHelper.getRandomSequence(65534) + 1;
      int             flags            = KeyExchangeMessage.INITIATE_FLAG;
      ECKeyPair       baseKey          = Curve.generateKeyPair();
      ECKeyPair       ratchetKey       = Curve.generateKeyPair();
      IdentityKeyPair identityKey      = identityKeyStore.getIdentityKeyPair();
      byte[]          baseKeySignature = Curve.calculateSignature(identityKey.getPrivateKey(), baseKey.getPublicKey().serialize());
      SessionRecord   sessionRecord    = sessionStore.loadSession(remoteAddress);

      sessionRecord.getSessionState().setPendingKeyExchange(sequence, baseKey, ratchetKey, identityKey);
      sessionStore.storeSession(remoteAddress, sessionRecord);

      return new KeyExchangeMessage(CiphertextMessage.CURRENT_VERSION,
                                    sequence, flags, baseKey.getPublicKey(), baseKeySignature,
                                    ratchetKey.getPublicKey(), identityKey.getPublicKey());
    } catch (InvalidKeyException e) {
      throw new AssertionError(e);
    }
  }
}
 
Example 2
/**
 * Construct a group session for sending messages.
 *
 * @param senderKeyName The (groupId, senderId, deviceId) tuple.  In this case, 'senderId' should be the caller.
 * @return A SenderKeyDistributionMessage that is individually distributed to each member of the group.
 */
public SenderKeyDistributionMessage create(SenderKeyName senderKeyName) {
  synchronized (GroupCipher.LOCK) {
    try {
      SenderKeyRecord senderKeyRecord = senderKeyStore.loadSenderKey(senderKeyName);

      if (senderKeyRecord.isEmpty()) {
        senderKeyRecord.setSenderKeyState(KeyHelper.generateSenderKeyId(),
                                          0,
                                          KeyHelper.generateSenderKey(),
                                          KeyHelper.generateSenderSigningKey());
        senderKeyStore.storeSenderKey(senderKeyName, senderKeyRecord);
      }

      SenderKeyState state = senderKeyRecord.getSenderKeyState();

      return new SenderKeyDistributionMessage(state.getKeyId(),
                                              state.getSenderChainKey().getIteration(),
                                              state.getSenderChainKey().getSeed(),
                                              state.getSigningKeyPublic());

    } catch (InvalidKeyIdException | InvalidKeyException e) {
      throw new AssertionError(e);
    }
  }
}
 
Example 3
Source Project: signal-bot   Source File: SignalBot.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void verify(String verificationCode) throws IOException {
    String username = prefs.get("LOCAL_USERNAME", null);
    String password = prefs.get("LOCAL_PASSWORD", null);
    logger.info("Verifying user " + username + " with code " + verificationCode + "...");
    String code = verificationCode.replace("-", "");
    int registrationId = KeyHelper.generateRegistrationId(false);
    prefs.putInt("REGISTRATION_ID", registrationId);
    byte[] profileKey = Util.getSecretBytes(32);
    byte[] unidentifiedAccessKey = UnidentifiedAccess.deriveAccessKeyFrom(profileKey);
    accountManager = new SignalServiceAccountManager(config, username, password, USER_AGENT);
    accountManager.verifyAccountWithCode(code, null, registrationId, true, null, unidentifiedAccessKey, false);
}
 
Example 4
Source Project: signal-bot   Source File: SignalBot.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void listen() throws IOException, InvalidKeyException {
    String username = prefs.get("LOCAL_USERNAME", null);
    String password = prefs.get("LOCAL_PASSWORD", null);
    logger.info("Generating keys for " + username + "...");
    IdentityKeyPair identityKeyPair = KeyHelper.generateIdentityKeyPair();
    int registrationId = prefs.getInt("REGISTRATION_ID", -1);
    this.protocolStore = new InMemorySignalProtocolStore(identityKeyPair, registrationId);
    accountManager = new SignalServiceAccountManager(config, username, password, USER_AGENT);
    refreshPreKeys(identityKeyPair);
    logger.info("Starting message listener...");
    messageRetrieverThread.start();
    // TODO refresh keys job
}
 
Example 5
Source Project: signal-bot   Source File: SignalBot.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void refreshPreKeys(IdentityKeyPair identityKeyPair) throws IOException, InvalidKeyException {
    int initialPreKeyId = new SecureRandom().nextInt(Medium.MAX_VALUE);
    List<PreKeyRecord> records = KeyHelper.generatePreKeys(initialPreKeyId, BATCH_SIZE);
    records.forEach((v) -> this.protocolStore.storePreKey(v.getId(), v));
    int signedPreKeyId = new SecureRandom().nextInt(Medium.MAX_VALUE);
    SignedPreKeyRecord signedPreKey = KeyHelper.generateSignedPreKey(identityKeyPair, signedPreKeyId);
    this.protocolStore.storeSignedPreKey(signedPreKey.getId(), signedPreKey);
    this.accountManager.setPreKeys(identityKeyPair.getPublicKey(), signedPreKey, records);
}
 
Example 6
Source Project: signald   Source File: Manager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void createNewIdentity() {
    IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
    int registrationId = KeyHelper.generateRegistrationId(false);
    accountData.axolotlStore = new SignalProtocolStore(identityKey, registrationId);
    accountData.registered = false;
    accountData.init();
}
 
Example 7
public ProvisioningManager(String settingsPath, SignalServiceConfiguration serviceConfiguration, String userAgent) {
    this.pathConfig = PathConfig.createDefault(settingsPath);
    this.serviceConfiguration = serviceConfiguration;
    this.userAgent = userAgent;

    identityKey = KeyHelper.generateIdentityKeyPair();
    registrationId = KeyHelper.generateRegistrationId(false);
    password = KeyUtils.createPassword();
    final SleepTimer timer = new UptimeSleepTimer();
    accountManager = new SignalServiceAccountManager(serviceConfiguration, null, null, password, SignalServiceAddress.DEFAULT_DEVICE_ID, userAgent, timer);
}
 
Example 8
Source Project: Smack   Source File: SignalOmemoKeyUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TreeMap<Integer, PreKeyRecord> generateOmemoPreKeys(int currentPreKeyId, int count) {
    List<PreKeyRecord> preKeyRecords = KeyHelper.generatePreKeys(currentPreKeyId, count);
    TreeMap<Integer, PreKeyRecord> map = new TreeMap<>();
    for (PreKeyRecord p : preKeyRecords) {
        map.put(p.getId(), p);
    }
    return map;
}
 
Example 9
Source Project: Smack   Source File: SignalOmemoKeyUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SignedPreKeyRecord generateOmemoSignedPreKey(IdentityKeyPair identityKeyPair, int currentPreKeyId)
        throws CorruptedOmemoKeyException {
    try {
        return KeyHelper.generateSignedPreKey(identityKeyPair, currentPreKeyId);
    } catch (InvalidKeyException e) {
        throw new CorruptedOmemoKeyException(e);
    }
}
 
Example 10
private static void verifyAccount(@NonNull Context context,
                                  @NonNull Credentials credentials,
                                  @NonNull String code,
                                  @Nullable String pin,
                                  @Nullable TokenResponse kbsTokenResponse,
                                  @Nullable String kbsStorageCredentials,
                                  @Nullable String fcmToken)
  throws IOException, KeyBackupSystemWrongPinException, KeyBackupSystemNoDataException
{
  boolean    isV2RegistrationLock        = kbsTokenResponse != null;
  int        registrationId              = KeyHelper.generateRegistrationId(false);
  boolean    universalUnidentifiedAccess = TextSecurePreferences.isUniversalUnidentifiedAccess(context);
  ProfileKey profileKey                  = findExistingProfileKey(context, credentials.getE164number());

  if (profileKey == null) {
    profileKey = ProfileKeyUtil.createNew();
    Log.i(TAG, "No profile key found, created a new one");
  }

  byte[] unidentifiedAccessKey = UnidentifiedAccess.deriveAccessKeyFrom(profileKey);

  TextSecurePreferences.setLocalRegistrationId(context, registrationId);
  SessionUtil.archiveAllSessions(context);

  SignalServiceAccountManager accountManager     = AccountManagerFactory.createUnauthenticated(context, credentials.getE164number(), credentials.getPassword());
  KbsPinData                  kbsData            = isV2RegistrationLock ? PinState.restoreMasterKey(pin, kbsStorageCredentials, kbsTokenResponse) : null;
  String                      registrationLockV2 = kbsData != null ? kbsData.getMasterKey().deriveRegistrationLock() : null;
  String                      registrationLockV1 = isV2RegistrationLock ? null : pin;
  boolean                     hasFcm             = fcmToken != null;

  Log.i(TAG, "Calling verifyAccountWithCode(): reglockV1? " + !TextUtils.isEmpty(registrationLockV1) + ", reglockV2? " + !TextUtils.isEmpty(registrationLockV2));

  VerifyAccountResponse response = accountManager.verifyAccountWithCode(code,
                                                                        null,
                                                                        registrationId,
                                                                        !hasFcm,
                                                                        registrationLockV1,
                                                                        registrationLockV2,
                                                                        unidentifiedAccessKey,
                                                                        universalUnidentifiedAccess,
                                                                        AppCapabilities.getCapabilities(true));

  UUID    uuid   = UuidUtil.parseOrThrow(response.getUuid());
  boolean hasPin = response.isStorageCapable();

  IdentityKeyPair    identityKey  = IdentityKeyUtil.getIdentityKeyPair(context);
  List<PreKeyRecord> records      = PreKeyUtil.generatePreKeys(context);
  SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(context, identityKey, true);

  accountManager = AccountManagerFactory.createAuthenticated(context, uuid, credentials.getE164number(), credentials.getPassword());
  accountManager.setPreKeys(identityKey.getPublicKey(), signedPreKey, records);

  if (hasFcm) {
    accountManager.setGcmId(Optional.fromNullable(fcmToken));
  }

  RecipientDatabase recipientDatabase = DatabaseFactory.getRecipientDatabase(context);
  RecipientId       selfId            = recipientDatabase.getOrInsertFromE164(credentials.getE164number());

  recipientDatabase.setProfileSharing(selfId, true);
  recipientDatabase.markRegistered(selfId, uuid);

  TextSecurePreferences.setLocalNumber(context, credentials.getE164number());
  TextSecurePreferences.setLocalUuid(context, uuid);
  recipientDatabase.setProfileKey(selfId, profileKey);
  ApplicationDependencies.getRecipientCache().clearSelf();

  TextSecurePreferences.setFcmToken(context, fcmToken);
  TextSecurePreferences.setFcmDisabled(context, !hasFcm);
  TextSecurePreferences.setWebsocketRegistered(context, true);

  DatabaseFactory.getIdentityDatabase(context)
                 .saveIdentity(selfId,
                               identityKey.getPublicKey(), IdentityDatabase.VerifiedStatus.VERIFIED,
                               true, System.currentTimeMillis(), true);

  TextSecurePreferences.setVerifying(context, false);
  TextSecurePreferences.setPushRegistered(context, true);
  TextSecurePreferences.setPushServerPassword(context, credentials.getPassword());
  TextSecurePreferences.setSignedPreKeyRegistered(context, true);
  TextSecurePreferences.setPromptedPushRegistration(context, true);
  TextSecurePreferences.setUnauthorizedReceived(context, false);

  PinState.onRegistration(context, kbsData, pin, hasPin);
}
 
Example 11
private static int generateRegistrationId() {
    Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl registration ID...");
    return KeyHelper.generateRegistrationId(true);
}
 
Example 12
private static int generateRegistrationId() {
  return KeyHelper.generateRegistrationId(false);
}
 
Example 13
private static int generateRegistrationId() {
  return KeyHelper.generateRegistrationId(false);
}
 
Example 14
public void testDeviceConsistency() throws InvalidMessageException {
  final IdentityKeyPair deviceOne   = KeyHelper.generateIdentityKeyPair();
  final IdentityKeyPair deviceTwo   = KeyHelper.generateIdentityKeyPair();
  final IdentityKeyPair deviceThree = KeyHelper.generateIdentityKeyPair();

  List<IdentityKey> keyList = new LinkedList<IdentityKey>() {{
    add(deviceOne.getPublicKey());
    add(deviceTwo.getPublicKey());
    add(deviceThree.getPublicKey());
  }};

  Collections.shuffle(keyList);
  DeviceConsistencyCommitment deviceOneCommitment = new DeviceConsistencyCommitment(1, keyList);

  Collections.shuffle(keyList);
  DeviceConsistencyCommitment deviceTwoCommitment = new DeviceConsistencyCommitment(1, keyList);

  Collections.shuffle(keyList);
  DeviceConsistencyCommitment deviceThreeCommitment = new DeviceConsistencyCommitment(1, keyList);

  assertTrue(Arrays.equals(deviceOneCommitment.toByteArray(), deviceTwoCommitment.toByteArray()));
  assertTrue(Arrays.equals(deviceTwoCommitment.toByteArray(), deviceThreeCommitment.toByteArray()));

  DeviceConsistencyMessage deviceOneMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceOne);
  DeviceConsistencyMessage deviceTwoMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceTwo);
  DeviceConsistencyMessage deviceThreeMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceThree);

  DeviceConsistencyMessage receivedDeviceOneMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceOneMessage.getSerialized(), deviceOne.getPublicKey());
  DeviceConsistencyMessage receivedDeviceTwoMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceTwoMessage.getSerialized(), deviceTwo.getPublicKey());
  DeviceConsistencyMessage receivedDeviceThreeMessage = new DeviceConsistencyMessage(deviceOneCommitment, deviceThreeMessage.getSerialized(), deviceThree.getPublicKey());

  assertTrue(Arrays.equals(deviceOneMessage.getSignature().getVrfOutput(), receivedDeviceOneMessage.getSignature().getVrfOutput()));
  assertTrue(Arrays.equals(deviceTwoMessage.getSignature().getVrfOutput(), receivedDeviceTwoMessage.getSignature().getVrfOutput()));
  assertTrue(Arrays.equals(deviceThreeMessage.getSignature().getVrfOutput(), receivedDeviceThreeMessage.getSignature().getVrfOutput()));

  String codeOne = generateCode(deviceOneCommitment, deviceOneMessage, receivedDeviceTwoMessage, receivedDeviceThreeMessage);
  String codeTwo = generateCode(deviceTwoCommitment, deviceTwoMessage, receivedDeviceThreeMessage, receivedDeviceOneMessage);
  String codeThree = generateCode(deviceThreeCommitment, deviceThreeMessage, receivedDeviceTwoMessage, receivedDeviceOneMessage);

  assertEquals(codeOne, codeTwo);
  assertEquals(codeTwo, codeThree);
}
 
Example 15
Source Project: Smack   Source File: SignalOmemoKeyUtil.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public IdentityKeyPair generateOmemoIdentityKeyPair() {
    return KeyHelper.generateIdentityKeyPair();
}
 
Example 16
private static int generateRegistrationId() {
	Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl registration ID...");
	return KeyHelper.generateRegistrationId(true);
}