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

The following examples show how to use org.whispersystems.libsignal.ecc.Curve#decodePoint() . 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: SignedPreKeyDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public @Nullable SignedPreKeyRecord getSignedPreKey(int keyId) {
  SQLiteDatabase database = databaseHelper.getReadableDatabase();

  try (Cursor cursor = database.query(TABLE_NAME, null, KEY_ID + " = ?",
                                      new String[] {String.valueOf(keyId)},
                                      null, null, null))
  {
    if (cursor != null && cursor.moveToFirst()) {
      try {
        ECPublicKey  publicKey  = Curve.decodePoint(Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(PUBLIC_KEY))), 0);
        ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(PRIVATE_KEY))));
        byte[]       signature  = Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(SIGNATURE)));
        long         timestamp  = cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP));

        return new SignedPreKeyRecord(keyId, timestamp, new ECKeyPair(publicKey, privateKey), signature);
      } catch (InvalidKeyException | IOException e) {
        Log.w(TAG, e);
      }
    }
  }

  return null;
}
 
Example 2
Source File: SignedPreKeyDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public @NonNull List<SignedPreKeyRecord> getAllSignedPreKeys() {
  SQLiteDatabase           database = databaseHelper.getReadableDatabase();
  List<SignedPreKeyRecord> results  = new LinkedList<>();

  try (Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null)) {
    while (cursor != null && cursor.moveToNext()) {
      try {
        int          keyId      = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
        ECPublicKey  publicKey  = Curve.decodePoint(Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(PUBLIC_KEY))), 0);
        ECPrivateKey privateKey = Curve.decodePrivatePoint(Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(PRIVATE_KEY))));
        byte[]       signature  = Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(SIGNATURE)));
        long         timestamp  = cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP));

        results.add(new SignedPreKeyRecord(keyId, timestamp, new ECKeyPair(publicKey, privateKey), signature));
      } catch (InvalidKeyException | IOException e) {
        Log.w(TAG, e);
      }
    }
  }

  return results;
}
 
Example 3
Source File: MasterSecretUtil.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public static AsymmetricMasterSecret getAsymmetricMasterSecret(@NonNull AccountContext accountContext,
                                                               @Nullable MasterSecret masterSecret) {
    try {
        byte[] djbPublicBytes = retrieve(accountContext, ASYMMETRIC_LOCAL_PUBLIC_DJB);
        byte[] djbPrivateBytes = retrieve(accountContext, ASYMMETRIC_LOCAL_PRIVATE_DJB);

        ECPublicKey djbPublicKey = null;
        ECPrivateKey djbPrivateKey = null;

        if (djbPublicBytes != null) {
            djbPublicKey = Curve.decodePoint(djbPublicBytes, 0);
        }

        if (masterSecret != null) {
            MasterCipher masterCipher = new MasterCipher(masterSecret);

            if (djbPrivateBytes != null) {
                djbPrivateKey = masterCipher.decryptKey(djbPrivateBytes);
            }
        }

        return new AsymmetricMasterSecret(djbPublicKey, djbPrivateKey);
    } catch (InvalidKeyException | IOException ike) {
        throw new AssertionError(ike);
    }
}
 
Example 4
Source File: PublicKey.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public PublicKey(byte[] bytes, int offset) throws InvalidKeyException {
  Log.w("PublicKey", "PublicKey Length: " + (bytes.length - offset));

  if ((bytes.length - offset) < KEY_SIZE)
    throw new InvalidKeyException("Provided bytes are too short.");

  this.id        = Conversions.byteArrayToMedium(bytes, offset);
  this.publicKey = Curve.decodePoint(bytes, offset + 3);
}
 
Example 5
Source File: PreKeyEntity.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ECPublicKey deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  try {
    return Curve.decodePoint(Base64.decodeWithoutPadding(p.getValueAsString()), 0);
  } catch (InvalidKeyException e) {
    throw new IOException(e);
  }
}
 
Example 6
Source File: PreKeySignalMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public PreKeySignalMessage(byte[] serialized)
    throws InvalidMessageException, InvalidVersionException
{
  try {
    this.version = ByteUtil.highBitsToInt(serialized[0]);

    if (this.version > CiphertextMessage.CURRENT_VERSION) {
      throw new InvalidVersionException("Unknown version: " + this.version);
    }

    if (this.version < CiphertextMessage.CURRENT_VERSION) {
      throw new LegacyMessageException("Legacy version: " + this.version);
    }

    SignalProtos.PreKeySignalMessage preKeyWhisperMessage
        = SignalProtos.PreKeySignalMessage.parseFrom(ByteString.copyFrom(serialized, 1,
                                                                         serialized.length-1));

    if (!preKeyWhisperMessage.hasSignedPreKeyId()  ||
        !preKeyWhisperMessage.hasBaseKey()         ||
        !preKeyWhisperMessage.hasIdentityKey()     ||
        !preKeyWhisperMessage.hasMessage())
    {
      throw new InvalidMessageException("Incomplete message.");
    }

    this.serialized     = serialized;
    this.registrationId = preKeyWhisperMessage.getRegistrationId();
    this.preKeyId       = preKeyWhisperMessage.hasPreKeyId() ? Optional.of(preKeyWhisperMessage.getPreKeyId()) : Optional.<Integer>absent();
    this.signedPreKeyId = preKeyWhisperMessage.hasSignedPreKeyId() ? preKeyWhisperMessage.getSignedPreKeyId() : -1;
    this.baseKey        = Curve.decodePoint(preKeyWhisperMessage.getBaseKey().toByteArray(), 0);
    this.identityKey    = new IdentityKey(Curve.decodePoint(preKeyWhisperMessage.getIdentityKey().toByteArray(), 0));
    this.message        = new SignalMessage(preKeyWhisperMessage.getMessage().toByteArray());
  } catch (InvalidProtocolBufferException | InvalidKeyException | LegacyMessageException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 7
Source File: KeyExchangeMessage.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public KeyExchangeMessage(byte[] serialized)
    throws InvalidMessageException, InvalidVersionException, LegacyMessageException
{
  try {
    byte[][] parts        = ByteUtil.split(serialized, 1, serialized.length - 1);
    this.version          = ByteUtil.highBitsToInt(parts[0][0]);
    this.supportedVersion = ByteUtil.lowBitsToInt(parts[0][0]);

    if (this.version < CiphertextMessage.CURRENT_VERSION) {
      throw new LegacyMessageException("Unsupported legacy version: " + this.version);
    }

    if (this.version > CiphertextMessage.CURRENT_VERSION) {
      throw new InvalidVersionException("Unknown version: " + this.version);
    }

    SignalProtos.KeyExchangeMessage message = SignalProtos.KeyExchangeMessage.parseFrom(parts[1]);

    if (!message.hasId()           || !message.hasBaseKey()     ||
        !message.hasRatchetKey()   || !message.hasIdentityKey() ||
        !message.hasBaseKeySignature())
    {
      throw new InvalidMessageException("Some required fields missing!");
    }

    this.sequence         = message.getId() >> 5;
    this.flags            = message.getId() & 0x1f;
    this.serialized       = serialized;
    this.baseKey          = Curve.decodePoint(message.getBaseKey().toByteArray(), 0);
    this.baseKeySignature = message.getBaseKeySignature().toByteArray();
    this.ratchetKey       = Curve.decodePoint(message.getRatchetKey().toByteArray(), 0);
    this.identityKey      = new IdentityKey(message.getIdentityKey().toByteArray(), 0);
  } catch (InvalidKeyException | IOException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 8
Source File: Utils.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
static DeviceLinkInfo parseDeviceLinkUri(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);

    return new DeviceLinkInfo(deviceIdentifier, deviceKey);
}
 
Example 9
Source File: Utils.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
static CertificateValidator getCertificateValidator() {
    try {
        ECPublicKey unidentifiedSenderTrustRoot = Curve.decodePoint(Base64.decode(ServiceConfig.UNIDENTIFIED_SENDER_TRUST_ROOT), 0);
        return new CertificateValidator(unidentifiedSenderTrustRoot);
    } catch (InvalidKeyException | IOException e) {
        throw new AssertionError(e);
    }
}
 
Example 10
Source File: SignalMessage.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public SignalMessage(byte[] serialized) throws InvalidMessageException, LegacyMessageException {
  try {
    byte[][] messageParts = ByteUtil.split(serialized, 1, serialized.length - 1 - MAC_LENGTH, MAC_LENGTH);
    byte     version      = messageParts[0][0];
    byte[]   message      = messageParts[1];
    byte[]   mac          = messageParts[2];

    if (ByteUtil.highBitsToInt(version) < CURRENT_VERSION) {
      throw new LegacyMessageException("Legacy message: " + ByteUtil.highBitsToInt(version));
    }

    if (ByteUtil.highBitsToInt(version) > CURRENT_VERSION) {
      throw new InvalidMessageException("Unknown version: " + ByteUtil.highBitsToInt(version));
    }

    SignalProtos.SignalMessage whisperMessage = SignalProtos.SignalMessage.parseFrom(message);

    if (!whisperMessage.hasCiphertext() ||
        !whisperMessage.hasCounter() ||
        !whisperMessage.hasRatchetKey())
    {
      throw new InvalidMessageException("Incomplete message.");
    }

    this.serialized       = serialized;
    this.senderRatchetKey = Curve.decodePoint(whisperMessage.getRatchetKey().toByteArray(), 0);
    this.messageVersion   = ByteUtil.highBitsToInt(version);
    this.counter          = whisperMessage.getCounter();
    this.previousCounter  = whisperMessage.getPreviousCounter();
    this.ciphertext       = whisperMessage.getCiphertext().toByteArray();
  } catch (InvalidProtocolBufferException | InvalidKeyException | ParseException e) {
    throw new InvalidMessageException(e);
  }
}
 
Example 11
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 12
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 13
Source File: SessionState.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public ECKeyPair getPendingKeyExchangeBaseKey() throws InvalidKeyException {
  ECPublicKey publicKey   = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
                                                              .getLocalBaseKey().toByteArray(), 0);

  ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getPendingKeyExchange()
                                                                     .getLocalBaseKeyPrivate()
                                                                     .toByteArray());

  return new ECKeyPair(publicKey, privateKey);
}
 
Example 14
Source File: GroupMessageEntity.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public String getFinalSource(GroupInfo groupInfo) throws DecryptSourceException {
    if (TextUtils.isEmpty(sourceExtra)) {
        return fromUid;
    }
    try {
        String sourceExtraDecoded = new String(Base64.decode(sourceExtra), StandardCharsets.UTF_8);
        JSONObject json = new JSONObject(sourceExtraDecoded);
        ALog.d("GroupMessageEntity", "getFinalSource source_extra: " + sourceExtraDecoded);
        String encryptSource = json.optString("source");
        String ephemeralPubKey = json.optString("ephemeralPubkey");
        String groupMsgPubKey = json.optString("groupMsgPubkey");
        String iv = json.optString("iv");
        int version = json.optInt("version");
        if (groupInfo == null) {
            throw new Exception("groupInfo is null");
        }
        if (!TextUtils.equals(Base64.encodeBytes(groupInfo.getChannelPublicKey()), groupMsgPubKey)) {
            throw new Exception("groupMsgPubKey is wrong");
        }
        DjbECPublicKey djbECPublicKey = (DjbECPublicKey) Curve.decodePoint(Base64.decode(ephemeralPubKey), 0);
        byte[] ecdh = Curve25519.getInstance(Curve25519.BEST).calculateAgreement(djbECPublicKey.getPublicKey(), groupInfo.getChannelPrivateKey());
        return new String(EncryptUtils.decryptAES(Base64.decode(encryptSource),
                EncryptUtils.computeSHA256(ecdh), EncryptUtils.MODE_AES, Base64.decode(iv)), StandardCharsets.UTF_8);


    }catch (Exception ex) {
        ALog.e("GroupMessageEntity", "getFinalSource error", ex);
        throw new DecryptSourceException(ex.getCause());
    }
}
 
Example 15
Source File: SignalOmemoKeyUtil.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public ECPublicKey ellipticCurvePublicKeyFromBytes(byte[] data) throws CorruptedOmemoKeyException {
    if (data == null) return null;
    try {
        return Curve.decodePoint(data, 0);
    } catch (InvalidKeyException e) {
        throw new CorruptedOmemoKeyException(e);
    }
}
 
Example 16
Source File: MasterCipher.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public ECPublicKey decryptPublicKey(byte[] key) throws InvalidKeyException {
  try {
    return Curve.decodePoint(decrypt(key, "ECPublicKey".getBytes()), 0);
  } catch (GeneralSecurityException ge) {
    throw new InvalidKeyException(ge);
  }
}
 
Example 17
Source File: PreKeyRecord.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public ECKeyPair getKeyPair() {
  try {
    ECPublicKey publicKey = Curve.decodePoint(this.structure.getPublicKey().toByteArray(), 0);
    ECPrivateKey privateKey = Curve.decodePrivatePoint(this.structure.getPrivateKey().toByteArray());

    return new ECKeyPair(publicKey, privateKey);
  } catch (InvalidKeyException e) {
    throw new AssertionError(e);
  }
}
 
Example 18
Source File: SessionState.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public ECKeyPair getPendingKeyExchangeRatchetKey() throws InvalidKeyException {
  ECPublicKey publicKey   = Curve.decodePoint(sessionStructure.getPendingKeyExchange()
                                                              .getLocalRatchetKey().toByteArray(), 0);

  ECPrivateKey privateKey = Curve.decodePrivatePoint(sessionStructure.getPendingKeyExchange()
                                                                     .getLocalRatchetKeyPrivate()
                                                                     .toByteArray());

  return new ECKeyPair(publicKey, privateKey);
}
 
Example 19
Source File: RootKeyTest.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public void testRootKeyDerivationV2() throws NoSuchAlgorithmException, InvalidKeyException {
  byte[] rootKeySeed  = {(byte) 0x7b, (byte) 0xa6, (byte) 0xde, (byte) 0xbc, (byte) 0x2b,
                         (byte) 0xc1, (byte) 0xbb, (byte) 0xf9, (byte) 0x1a, (byte) 0xbb,
                         (byte) 0xc1, (byte) 0x36, (byte) 0x74, (byte) 0x04, (byte) 0x17,
                         (byte) 0x6c, (byte) 0xa6, (byte) 0x23, (byte) 0x09, (byte) 0x5b,
                         (byte) 0x7e, (byte) 0xc6, (byte) 0x6b, (byte) 0x45, (byte) 0xf6,
                         (byte) 0x02, (byte) 0xd9, (byte) 0x35, (byte) 0x38, (byte) 0x94,
                         (byte) 0x2d, (byte) 0xcc};

  byte[] alicePublic  = {(byte) 0x05, (byte) 0xee, (byte) 0x4f, (byte) 0xa6, (byte) 0xcd,
                         (byte) 0xc0, (byte) 0x30, (byte) 0xdf, (byte) 0x49, (byte) 0xec,
                         (byte) 0xd0, (byte) 0xba, (byte) 0x6c, (byte) 0xfc, (byte) 0xff,
                         (byte) 0xb2, (byte) 0x33, (byte) 0xd3, (byte) 0x65, (byte) 0xa2,
                         (byte) 0x7f, (byte) 0xad, (byte) 0xbe, (byte) 0xff, (byte) 0x77,
                         (byte) 0xe9, (byte) 0x63, (byte) 0xfc, (byte) 0xb1, (byte) 0x62,
                         (byte) 0x22, (byte) 0xe1, (byte) 0x3a};

  byte[] alicePrivate = {(byte) 0x21, (byte) 0x68, (byte) 0x22, (byte) 0xec, (byte) 0x67,
                         (byte) 0xeb, (byte) 0x38, (byte) 0x04, (byte) 0x9e, (byte) 0xba,
                         (byte) 0xe7, (byte) 0xb9, (byte) 0x39, (byte) 0xba, (byte) 0xea,
                         (byte) 0xeb, (byte) 0xb1, (byte) 0x51, (byte) 0xbb, (byte) 0xb3,
                         (byte) 0x2d, (byte) 0xb8, (byte) 0x0f, (byte) 0xd3, (byte) 0x89,
                         (byte) 0x24, (byte) 0x5a, (byte) 0xc3, (byte) 0x7a, (byte) 0x94,
                         (byte) 0x8e, (byte) 0x50};

  byte[] bobPublic    = {(byte) 0x05, (byte) 0xab, (byte) 0xb8, (byte) 0xeb, (byte) 0x29,
                         (byte) 0xcc, (byte) 0x80, (byte) 0xb4, (byte) 0x71, (byte) 0x09,
                         (byte) 0xa2, (byte) 0x26, (byte) 0x5a, (byte) 0xbe, (byte) 0x97,
                         (byte) 0x98, (byte) 0x48, (byte) 0x54, (byte) 0x06, (byte) 0xe3,
                         (byte) 0x2d, (byte) 0xa2, (byte) 0x68, (byte) 0x93, (byte) 0x4a,
                         (byte) 0x95, (byte) 0x55, (byte) 0xe8, (byte) 0x47, (byte) 0x57,
                         (byte) 0x70, (byte) 0x8a, (byte) 0x30};

  byte[] nextRoot     = {(byte) 0xb1, (byte) 0x14, (byte) 0xf5, (byte) 0xde, (byte) 0x28,
                         (byte) 0x01, (byte) 0x19, (byte) 0x85, (byte) 0xe6, (byte) 0xeb,
                         (byte) 0xa2, (byte) 0x5d, (byte) 0x50, (byte) 0xe7, (byte) 0xec,
                         (byte) 0x41, (byte) 0xa9, (byte) 0xb0, (byte) 0x2f, (byte) 0x56,
                         (byte) 0x93, (byte) 0xc5, (byte) 0xc7, (byte) 0x88, (byte) 0xa6,
                         (byte) 0x3a, (byte) 0x06, (byte) 0xd2, (byte) 0x12, (byte) 0xa2,
                         (byte) 0xf7, (byte) 0x31};

  byte[] nextChain    = {(byte) 0x9d, (byte) 0x7d, (byte) 0x24, (byte) 0x69, (byte) 0xbc,
                         (byte) 0x9a, (byte) 0xe5, (byte) 0x3e, (byte) 0xe9, (byte) 0x80,
                         (byte) 0x5a, (byte) 0xa3, (byte) 0x26, (byte) 0x4d, (byte) 0x24,
                         (byte) 0x99, (byte) 0xa3, (byte) 0xac, (byte) 0xe8, (byte) 0x0f,
                         (byte) 0x4c, (byte) 0xca, (byte) 0xe2, (byte) 0xda, (byte) 0x13,
                         (byte) 0x43, (byte) 0x0c, (byte) 0x5c, (byte) 0x55, (byte) 0xb5,
                         (byte) 0xca, (byte) 0x5f};

  ECPublicKey  alicePublicKey  = Curve.decodePoint(alicePublic, 0);
  ECPrivateKey alicePrivateKey = Curve.decodePrivatePoint(alicePrivate);
  ECKeyPair    aliceKeyPair    = new ECKeyPair(alicePublicKey, alicePrivateKey);

  ECPublicKey bobPublicKey = Curve.decodePoint(bobPublic, 0);
  RootKey     rootKey      = new RootKey(HKDF.createFor(2), rootKeySeed);

  Pair<RootKey, ChainKey> rootKeyChainKeyPair = rootKey.createChain(bobPublicKey, aliceKeyPair);
  RootKey                 nextRootKey         = rootKeyChainKeyPair.first();
  ChainKey                nextChainKey        = rootKeyChainKeyPair.second();

  assertTrue(Arrays.equals(rootKey.getKeyBytes(), rootKeySeed));
  assertTrue(Arrays.equals(nextRootKey.getKeyBytes(), nextRoot));
  assertTrue(Arrays.equals(nextChainKey.getKey(), nextChain));
}
 
Example 20
Source File: SenderKeyState.java    From libsignal-protocol-java with GNU General Public License v3.0 4 votes vote down vote up
public ECPublicKey getSigningKeyPublic() throws InvalidKeyException {
  return Curve.decodePoint(senderKeyStateStructure.getSenderSigningKey()
                                                  .getPublic()
                                                  .toByteArray(), 0);
}