Java Code Examples for org.whispersystems.libsignal.ecc.Curve#generateKeyPair()

The following examples show how to use org.whispersystems.libsignal.ecc.Curve#generateKeyPair() . 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: 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 2
Source File: SessionBuilderTest.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
public void testBasicPreKeyV2()
    throws InvalidKeyException, InvalidVersionException, InvalidMessageException, InvalidKeyIdException, DuplicateMessageException, LegacyMessageException, UntrustedIdentityException, NoSessionException {
  SignalProtocolStore aliceStore          = new TestInMemorySignalProtocolStore();
  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);

  SignalProtocolStore bobStore      = new TestInMemorySignalProtocolStore();
  ECKeyPair    bobPreKeyPair = Curve.generateKeyPair();
  PreKeyBundle bobPreKey     = new PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                                31337, bobPreKeyPair.getPublicKey(),
                                                0, null, null,
                                                bobStore.getIdentityKeyPair().getPublicKey());

  try {
    aliceSessionBuilder.process(bobPreKey);
    throw new AssertionError("Should fail with missing unsigned prekey!");
  } catch (InvalidKeyException e) {
    // Good!
    return;
  }
}
 
Example 3
Source File: SimultaneousInitiateTests.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
private PreKeyBundle createBobPreKeyBundle(SignalProtocolStore bobStore) throws InvalidKeyException {
  ECKeyPair bobUnsignedPreKey   = Curve.generateKeyPair();
  int       bobUnsignedPreKeyId = new Random().nextInt(Medium.MAX_VALUE);
  byte[]    bobSignature        = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                           bobSignedPreKey.getPublicKey().serialize());

  PreKeyBundle bobPreKeyBundle = new PreKeyBundle(1, 1,
                                                  bobUnsignedPreKeyId, bobUnsignedPreKey.getPublicKey(),
                                                  bobSignedPreKeyId, bobSignedPreKey.getPublicKey(),
                                                  bobSignature, bobStore.getIdentityKeyPair().getPublicKey());

  bobStore.storeSignedPreKey(bobSignedPreKeyId, new SignedPreKeyRecord(bobSignedPreKeyId, System.currentTimeMillis(), bobSignedPreKey, bobSignature));
  bobStore.storePreKey(bobUnsignedPreKeyId, new PreKeyRecord(bobUnsignedPreKeyId, bobUnsignedPreKey));

  return bobPreKeyBundle;
}
 
Example 4
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 5
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
private List<PreKeyRecord> generatePreKeys() {
    List<PreKeyRecord> records = new ArrayList<>(ServiceConfig.PREKEY_BATCH_SIZE);

    final int offset = account.getPreKeyIdOffset();
    for (int i = 0; i < ServiceConfig.PREKEY_BATCH_SIZE; i++) {
        int preKeyId = (offset + i) % Medium.MAX_VALUE;
        ECKeyPair keyPair = Curve.generateKeyPair();
        PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);

        records.add(record);
    }

    account.addPreKeys(records);
    account.save();

    return records;
}
 
Example 6
Source File: SessionCipher.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
private ChainKey getOrCreateChainKey(SessionState sessionState, ECPublicKey theirEphemeral)
    throws InvalidMessageException
{
  try {
    if (sessionState.hasReceiverChain(theirEphemeral)) {
      return sessionState.getReceiverChainKey(theirEphemeral);
    } else {
      RootKey                 rootKey         = sessionState.getRootKey();
      ECKeyPair               ourEphemeral    = sessionState.getSenderRatchetKeyPair();
      Pair<RootKey, ChainKey> receiverChain   = rootKey.createChain(theirEphemeral, ourEphemeral);
      ECKeyPair               ourNewEphemeral = Curve.generateKeyPair();
      Pair<RootKey, ChainKey> senderChain     = receiverChain.first().createChain(theirEphemeral, ourNewEphemeral);

      sessionState.setRootKey(senderChain.first());
      sessionState.addReceiverChain(theirEphemeral, receiverChain.second());
      sessionState.setPreviousCounter(Math.max(sessionState.getSenderChainKey().getIndex()-1, 0));
      sessionState.setSenderChain(ourNewEphemeral, senderChain.second());

      return receiverChain.second();
    }
  } catch (InvalidKeyException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 7
Source File: PreKeyUtil.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public static SignedPreKeyRecord generateSignedPreKey(Context context, AccountContext accountContext, IdentityKeyPair identityKeyPair, boolean active) {
    try {
        SignedPreKeyStore signedPreKeyStore = new TextSecurePreKeyStore(context, accountContext);
        int signedPreKeyId = getNextSignedPreKeyId(context, accountContext);
        ECKeyPair keyPair = Curve.generateKeyPair();
        byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
        SignedPreKeyRecord record = new SignedPreKeyRecord(signedPreKeyId, System.currentTimeMillis(), keyPair, signature);

        signedPreKeyStore.storeSignedPreKey(signedPreKeyId, record);
        setNextSignedPreKeyId(context, accountContext,(signedPreKeyId + 1) % Medium.MAX_VALUE);

        if (active) {
            setActiveSignedPreKeyId(context, accountContext, signedPreKeyId);
        }

        return record;
    } catch (InvalidKeyException e) {
        throw new AssertionError(e);
    }
}
 
Example 8
Source File: AsymmetricMasterCipher.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encryptBytes(byte[] body) {
  try {
    ECPublicKey  theirPublic        = asymmetricMasterSecret.getDjbPublicKey();
    ECKeyPair    ourKeyPair         = Curve.generateKeyPair();
    byte[]       secret             = Curve.calculateAgreement(theirPublic, ourKeyPair.getPrivateKey());
    MasterCipher masterCipher       = getMasterCipherForSecret(secret);
    byte[]       encryptedBodyBytes = masterCipher.encryptBytes(body);

    PublicKey    ourPublicKey       = new PublicKey(31337, ourKeyPair.getPublicKey());
    byte[]       publicKeyBytes     = ourPublicKey.serialize();

    return Util.combine(publicKeyBytes, encryptedBodyBytes);
  } catch (InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 9
Source File: Manager.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
private List<PreKeyRecord> generatePreKeys() throws IOException {
    List<PreKeyRecord> records = new LinkedList<>();

    for (int i = 0; i < PREKEY_BATCH_SIZE; i++) {
        int preKeyId = (accountData.preKeyIdOffset + i) % Medium.MAX_VALUE;
        ECKeyPair keyPair = Curve.generateKeyPair();
        PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);

        accountData.axolotlStore.preKeys.storePreKey(preKeyId, record);
        records.add(record);
    }

    accountData.preKeyIdOffset = (accountData.preKeyIdOffset + PREKEY_BATCH_SIZE + 1) % Medium.MAX_VALUE;
    accountData.save();

    return records;
}
 
Example 10
Source File: NumericFingerprintGeneratorTest.java    From libsignal-protocol-java with GNU General Public License v3.0 6 votes vote down vote up
public void testMismatchingFingerprints() throws FingerprintVersionMismatchException, FingerprintIdentifierMismatchException, FingerprintParsingException {
  ECKeyPair aliceKeyPair = Curve.generateKeyPair();
  ECKeyPair bobKeyPair   = Curve.generateKeyPair();
  ECKeyPair mitmKeyPair  = Curve.generateKeyPair();

  IdentityKey aliceIdentityKey = new IdentityKey(aliceKeyPair.getPublicKey());
  IdentityKey bobIdentityKey   = new IdentityKey(bobKeyPair.getPublicKey());
  IdentityKey mitmIdentityKey  = new IdentityKey(mitmKeyPair.getPublicKey());

  NumericFingerprintGenerator generator        = new NumericFingerprintGenerator(1024);
  Fingerprint                 aliceFingerprint = generator.createFor(VERSION_1,
                                                                     "+14152222222".getBytes(), aliceIdentityKey,
                                                                     "+14153333333".getBytes(), mitmIdentityKey);

  Fingerprint bobFingerprint = generator.createFor(VERSION_1,
                                                   "+14153333333".getBytes(), bobIdentityKey,
                                                   "+14152222222".getBytes(), aliceIdentityKey);

  assertFalse(aliceFingerprint.getDisplayableFingerprint().getDisplayText().equals(
              bobFingerprint.getDisplayableFingerprint().getDisplayText()));

  assertFalse(aliceFingerprint.getScannableFingerprint().compareTo(bobFingerprint.getScannableFingerprint().getSerialized()));
  assertFalse(bobFingerprint.getScannableFingerprint().compareTo(aliceFingerprint.getScannableFingerprint().getSerialized()));
}
 
Example 11
Source File: IdentityKeyUtil.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public static void generateIdentityKeys(Context context, MasterSecret masterSecret, int subscriptionId, boolean displayNotification) {
  Log.w(TAG, "Generating identity keys for subscription ID " + subscriptionId);
  ECKeyPair    djbKeyPair     = Curve.generateKeyPair();

  MasterCipher masterCipher   = new MasterCipher(masterSecret);
  IdentityKey  djbIdentityKey = new IdentityKey(djbKeyPair.getPublicKey());
  byte[]       djbPrivateKey  = masterCipher.encryptKey(djbKeyPair.getPrivateKey());

  save(context, getIdentityPublicKeyDjbPref(subscriptionId), Base64.encodeBytes(djbIdentityKey.serialize()));
  save(context, getIdentityPrivateKeyDjbPref(subscriptionId), Base64.encodeBytes(djbPrivateKey));

  if (displayNotification) DualSimUtil.displayNotification(context);
}
 
Example 12
Source File: CurveTest.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public void testLargeSignatures() throws InvalidKeyException {
  ECKeyPair keys      = Curve.generateKeyPair();
  byte[]    message   = new byte[1024 * 1024];
  byte[]    signature = Curve.calculateSignature(keys.getPrivateKey(), message);

  assertTrue(Curve.verifySignature(keys.getPublicKey(), message, signature));

  message[0] ^= 0x01;

  assertFalse(Curve.verifySignature(keys.getPublicKey(), message, signature));
}
 
Example 13
Source File: RatchetingSession.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public static void initializeSession(SessionState sessionState, AliceSignalProtocolParameters parameters)
    throws InvalidKeyException
{
  try {
    sessionState.setSessionVersion(CiphertextMessage.CURRENT_VERSION);
    sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey());
    sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey());

    ECKeyPair             sendingRatchetKey = Curve.generateKeyPair();
    ByteArrayOutputStream secrets           = new ByteArrayOutputStream();

    secrets.write(getDiscontinuityBytes());

    secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
                                           parameters.getOurIdentityKey().getPrivateKey()));
    secrets.write(Curve.calculateAgreement(parameters.getTheirIdentityKey().getPublicKey(),
                                           parameters.getOurBaseKey().getPrivateKey()));
    secrets.write(Curve.calculateAgreement(parameters.getTheirSignedPreKey(),
                                           parameters.getOurBaseKey().getPrivateKey()));

    if (parameters.getTheirOneTimePreKey().isPresent()) {
      secrets.write(Curve.calculateAgreement(parameters.getTheirOneTimePreKey().get(),
                                             parameters.getOurBaseKey().getPrivateKey()));
    }

    DerivedKeys             derivedKeys  = calculateDerivedKeys(secrets.toByteArray());
    Pair<RootKey, ChainKey> sendingChain = derivedKeys.getRootKey().createChain(parameters.getTheirRatchetKey(), sendingRatchetKey);

    sessionState.addReceiverChain(parameters.getTheirRatchetKey(), derivedKeys.getChainKey());
    sessionState.setSenderChain(sendingRatchetKey, sendingChain.second());
    sessionState.setRootKey(sendingChain.first());
  } catch (IOException e) {
    throw new AssertionError(e);
  }
}
 
Example 14
Source File: IdentityKeyUtil.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public static void generateCurve25519IdentityKeys(Context context, MasterSecret masterSecret, int subscriptionId) {
  MasterCipher masterCipher    = new MasterCipher(masterSecret);
  ECKeyPair    djbKeyPair      = Curve.generateKeyPair();
  IdentityKey  djbIdentityKey  = new IdentityKey(djbKeyPair.getPublicKey());
  byte[]       djbPrivateKey   = masterCipher.encryptKey(djbKeyPair.getPrivateKey());

  save(context, getIdentityPublicKeyDjbPref(subscriptionId), Base64.encodeBytes(djbIdentityKey.serialize()));
  save(context, getIdentityPrivateKeyDjbPref(subscriptionId), Base64.encodeBytes(djbPrivateKey));
}
 
Example 15
Source File: MasterSecretUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static AsymmetricMasterSecret generateAsymmetricMasterSecret(Context context,
                                                                    MasterSecret masterSecret)
{
  MasterCipher masterCipher = new MasterCipher(masterSecret);
  ECKeyPair    keyPair      = Curve.generateKeyPair();

  if (!context.getSharedPreferences(PREFERENCES_NAME, 0).edit()
      .putString(ASYMMETRIC_LOCAL_PUBLIC_DJB, Base64.encodeBytes(masterCipher.encryptPublicKey(keyPair.getPublicKey())))
      .putString(ASYMMETRIC_LOCAL_PRIVATE_DJB, Base64.encodeBytes(masterCipher.encryptPrivateKey(keyPair.getPrivateKey())))
      .commit()) {
    throw new AssertionError("failed to save preferences in MasterSecretUtil");
  }

  return new AsymmetricMasterSecret(keyPair.getPublicKey(), keyPair.getPrivateKey());
}
 
Example 16
Source File: SQLiteAxolotlStore.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
private static IdentityKeyPair generateIdentityKeyPair() {
	Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + "Generating axolotl IdentityKeyPair...");
	ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
	return new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
			identityKeyPairKeys.getPrivateKey());
}
 
Example 17
Source File: TestInMemoryIdentityKeyStore.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
private static IdentityKeyPair generateIdentityKeyPair() {
  ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();

  return new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
                             identityKeyPairKeys.getPrivateKey());
}
 
Example 18
Source File: SessionBuilderTest.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testBadMessageBundle() throws InvalidKeyException, UntrustedIdentityException, InvalidVersionException, InvalidMessageException, DuplicateMessageException, LegacyMessageException, InvalidKeyIdException {
  SignalProtocolStore aliceStore          = new TestInMemorySignalProtocolStore();
  SessionBuilder aliceSessionBuilder = new SessionBuilder(aliceStore, BOB_ADDRESS);

  SignalProtocolStore bobStore = new TestInMemorySignalProtocolStore();

  ECKeyPair bobPreKeyPair            = Curve.generateKeyPair();
  ECKeyPair bobSignedPreKeyPair      = Curve.generateKeyPair();
  byte[]    bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                                bobSignedPreKeyPair.getPublicKey().serialize());

  PreKeyBundle bobPreKey = new PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                            31337, bobPreKeyPair.getPublicKey(),
                                            22, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                            bobStore.getIdentityKeyPair().getPublicKey());

  bobStore.storePreKey(31337, new PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair));
  bobStore.storeSignedPreKey(22, new SignedPreKeyRecord(22, System.currentTimeMillis(), bobSignedPreKeyPair, bobSignedPreKeySignature));

  aliceSessionBuilder.process(bobPreKey);

  String            originalMessage    = "L'homme est condamné à être libre";
  SessionCipher     aliceSessionCipher = new SessionCipher(aliceStore, BOB_ADDRESS);
  CiphertextMessage outgoingMessageOne = aliceSessionCipher.encrypt(originalMessage.getBytes());

  assertTrue(outgoingMessageOne.getType() == CiphertextMessage.PREKEY_TYPE);

  byte[] goodMessage = outgoingMessageOne.serialize();
  byte[] badMessage  = new byte[goodMessage.length];
  System.arraycopy(goodMessage, 0, badMessage, 0, badMessage.length);

  badMessage[badMessage.length-10] ^= 0x01;

  PreKeySignalMessage incomingMessage  = new PreKeySignalMessage(badMessage);
  SessionCipher        bobSessionCipher = new SessionCipher(bobStore, ALICE_ADDRESS);

  byte[] plaintext = new byte[0];

  try {
    plaintext = bobSessionCipher.decrypt(incomingMessage);
    throw new AssertionError("Decrypt should have failed!");
  } catch (InvalidMessageException e) {
    // good.
  }

  assertTrue(bobStore.containsPreKey(31337));

  plaintext = bobSessionCipher.decrypt(new PreKeySignalMessage(goodMessage));

  assertTrue(originalMessage.equals(new String(plaintext)));
  assertTrue(!bobStore.containsPreKey(31337));
}
 
Example 19
Source File: KeyHelper.java    From libsignal-protocol-java with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Generate a signed PreKey
 *
 * @param identityKeyPair The local client's identity key pair.
 * @param signedPreKeyId The PreKey id to assign the generated signed PreKey
 *
 * @return the generated signed PreKey
 * @throws InvalidKeyException when the provided identity key is invalid
 */
public static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair, int signedPreKeyId)
    throws InvalidKeyException
{
  ECKeyPair keyPair   = Curve.generateKeyPair();
  byte[]    signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());

  return new SignedPreKeyRecord(signedPreKeyId, System.currentTimeMillis(), keyPair, signature);
}
 
Example 20
Source File: KeyHelper.java    From libsignal-protocol-java with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Generate an identity key pair.  Clients should only do this once,
 * at install time.
 *
 * @return the generated IdentityKeyPair.
 */
public static IdentityKeyPair generateIdentityKeyPair() {
  ECKeyPair   keyPair   = Curve.generateKeyPair();
  IdentityKey publicKey = new IdentityKey(keyPair.getPublicKey());
  return new IdentityKeyPair(publicKey, keyPair.getPrivateKey());
}