From 2a8202e74846d191a321cca1202175af9db6107d Mon Sep 17 00:00:00 2001 From: dec05eba Date: Thu, 5 Nov 2020 01:45:06 +0100 Subject: Convert to sibs project --- .../java/org/matrix/olm/CommonSerializeUtils.java | 83 ---- .../src/main/java/org/matrix/olm/OlmAccount.java | 420 ------------------- .../src/main/java/org/matrix/olm/OlmException.java | 108 ----- .../org/matrix/olm/OlmInboundGroupSession.java | 372 ----------------- .../src/main/java/org/matrix/olm/OlmManager.java | 73 ---- .../src/main/java/org/matrix/olm/OlmMessage.java | 36 -- .../org/matrix/olm/OlmOutboundGroupSession.java | 296 -------------- .../main/java/org/matrix/olm/OlmPkDecryption.java | 109 ----- .../main/java/org/matrix/olm/OlmPkEncryption.java | 97 ----- .../src/main/java/org/matrix/olm/OlmPkMessage.java | 23 -- .../src/main/java/org/matrix/olm/OlmPkSigning.java | 100 ----- .../src/main/java/org/matrix/olm/OlmSAS.java | 155 ------- .../src/main/java/org/matrix/olm/OlmSession.java | 452 --------------------- .../src/main/java/org/matrix/olm/OlmUtility.java | 240 ----------- 14 files changed, 2564 deletions(-) delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/CommonSerializeUtils.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmAccount.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmException.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmInboundGroupSession.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmManager.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmMessage.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmOutboundGroupSession.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmPkDecryption.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmPkEncryption.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmPkMessage.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmPkSigning.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmSAS.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmSession.java delete mode 100644 android/olm-sdk/src/main/java/org/matrix/olm/OlmUtility.java (limited to 'android/olm-sdk/src/main/java/org/matrix') diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/CommonSerializeUtils.java b/android/olm-sdk/src/main/java/org/matrix/olm/CommonSerializeUtils.java deleted file mode 100644 index 229963f..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/CommonSerializeUtils.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2016 OpenMarket Ltd - * Copyright 2016 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.util.Log; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -/** - * Helper class dedicated to serialization mechanism (template method pattern). - */ -abstract class CommonSerializeUtils { - private static final String LOG_TAG = "CommonSerializeUtils"; - - /** - * Kick off the serialization mechanism. - * @param aOutStream output stream for serializing - * @throws IOException exception - */ - protected void serialize(ObjectOutputStream aOutStream) throws IOException { - aOutStream.defaultWriteObject(); - - // generate serialization key - byte[] key = OlmUtility.getRandomKey(); - - // compute pickle string - StringBuffer errorMsg = new StringBuffer(); - byte[] pickledData = serialize(key, errorMsg); - - if(null == pickledData) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_SERIALIZATION, String.valueOf(errorMsg)); - } else { - aOutStream.writeObject(new String(key, "UTF-8")); - aOutStream.writeObject(new String(pickledData, "UTF-8")); - } - } - - /** - * Kick off the deserialization mechanism. - * @param aInStream input stream - * @throws Exception the exception - */ - protected void deserialize(ObjectInputStream aInStream) throws Exception { - aInStream.defaultReadObject(); - - String keyAsString = (String)aInStream.readObject(); - String pickledDataAsString = (String)aInStream.readObject(); - - byte[] key; - byte[] pickledData; - - try { - key = keyAsString.getBytes("UTF-8"); - pickledData = pickledDataAsString.getBytes("UTF-8"); - - deserialize(pickledData, key); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_DESERIALIZATION, e.getMessage()); - } - - Log.d(LOG_TAG,"## deserializeObject(): success"); - } - - protected abstract byte[] serialize(byte[] aKey, StringBuffer aErrorMsg); - protected abstract void deserialize(byte[] aSerializedData, byte[] aKey) throws Exception; -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmAccount.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmAccount.java deleted file mode 100644 index 98a3c5b..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmAccount.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright 2017 OpenMarket Ltd - * Copyright 2017 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.text.TextUtils; -import android.util.Log; - -import org.json.JSONObject; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Map; - -/** - * Account class used to create Olm sessions in conjunction with {@link OlmSession} class.
- * OlmAccount provides APIs to retrieve the Olm keys. - *

Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmAccount extends CommonSerializeUtils implements Serializable { - private static final long serialVersionUID = 3497486121598434824L; - private static final String LOG_TAG = "OlmAccount"; - - // JSON keys used in the JSON objects returned by JNI - /** As well as the identity key, each device creates a number of Curve25519 key pairs which are - also used to establish Olm sessions, but can only be used once. Once again, the private part - remains on the device. but the public part is published to the Matrix network **/ - public static final String JSON_KEY_ONE_TIME_KEY = "curve25519"; - - /** Curve25519 identity key is a public-key cryptographic system which can be used to establish a shared - secret.
In Matrix, each device has a long-lived Curve25519 identity key which is used to establish - Olm sessions with that device. The private key should never leave the device, but the - public part is signed with the Ed25519 fingerprint key ({@link #JSON_KEY_FINGER_PRINT_KEY}) and published to the network. **/ - public static final String JSON_KEY_IDENTITY_KEY = "curve25519"; - - /** Ed25519 finger print is a public-key cryptographic system for signing messages.
In Matrix, each device has - an Ed25519 key pair which serves to identify that device. The private the key should - never leave the device, but the public part is published to the Matrix network. **/ - public static final String JSON_KEY_FINGER_PRINT_KEY = "ed25519"; - - /** Account Id returned by JNI. - * This value identifies uniquely the native account instance. - */ - private transient long mNativeId; - - public OlmAccount() throws OlmException { - try { - mNativeId = createNewAccountJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_INIT_ACCOUNT_CREATION, e.getMessage()); - } - } - - /** - * Create a new account and return it to JAVA side.
- * Since a C prt is returned as a jlong, special care will be taken - * to make the cast (OlmAccount* to jlong) platform independent. - * @return the initialized OlmAccount* instance or throw an exception if fails - **/ - private native long createNewAccountJni(); - - /** - * Getter on the account ID. - * @return native account ID - */ - long getOlmAccountId(){ - return mNativeId; - } - - /** - * Release native account and invalid its JAVA reference counter part.
- * Public API for {@link #releaseAccountJni()}. - */ - public void releaseAccount() { - if (0 != mNativeId) { - releaseAccountJni(); - } - mNativeId = 0; - } - - /** - * Destroy the corresponding OLM account native object.
- * This method must ALWAYS be called when this JAVA instance - * is destroyed (ie. garbage collected) to prevent memory leak in native side. - * See {@link #createNewAccountJni()}. - */ - private native void releaseAccountJni(); - - /** - * Return true the object resources have been released.
- * @return true the object resources have been released - */ - public boolean isReleased() { - return (0 == mNativeId); - } - - /** - * Return the identity keys (identity and fingerprint keys) in a dictionary.
- * Public API for {@link #identityKeysJni()}.
- * Ex: - * { - * "curve25519":"Vam++zZPMqDQM6ANKpO/uAl5ViJSHxV9hd+b0/fwRAg", - * "ed25519":"+v8SOlOASFTMrX3MCKBM4iVnYoZ+JIjpNt1fi8Z9O2I" - * } - * @return identity keys dictionary if operation succeeds, null otherwise - * @exception OlmException the failure reason - */ - public Map identityKeys() throws OlmException { - JSONObject identityKeysJsonObj = null; - - byte[] identityKeysBuffer; - - try { - identityKeysBuffer = identityKeysJni(); - } catch (Exception e) { - Log.e(LOG_TAG, "## identityKeys(): Failure - " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_IDENTITY_KEYS, e.getMessage()); - } - - if (null != identityKeysBuffer) { - try { - identityKeysJsonObj = new JSONObject(new String(identityKeysBuffer, "UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## identityKeys(): Exception - Msg=" + e.getMessage()); - } - } else { - Log.e(LOG_TAG, "## identityKeys(): Failure - identityKeysJni()=null"); - } - - return OlmUtility.toStringMap(identityKeysJsonObj); - } - - /** - * Get the public identity keys (Ed25519 fingerprint key and Curve25519 identity key).
- * Keys are Base64 encoded. - * These keys must be published on the server. - * @return the identity keys or throw an exception if it fails - */ - private native byte[] identityKeysJni(); - - /** - * Return the largest number of "one time keys" this account can store. - * @return the max number of "one time keys", -1 otherwise - */ - public long maxOneTimeKeys() { - return maxOneTimeKeysJni(); - } - - /** - * Return the largest number of "one time keys" this account can store. - * @return the max number of "one time keys", -1 otherwise - */ - private native long maxOneTimeKeysJni(); - - /** - * Generate a number of new one time keys.
If total number of keys stored - * by this account exceeds {@link #maxOneTimeKeys()}, the old keys are discarded.
- * The corresponding keys are retrieved by {@link #oneTimeKeys()}. - * @param aNumberOfKeys number of keys to generate - * @exception OlmException the failure reason - */ - public void generateOneTimeKeys(int aNumberOfKeys) throws OlmException { - try { - generateOneTimeKeysJni(aNumberOfKeys); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_GENERATE_ONE_TIME_KEYS, e.getMessage()); - } - } - - /** - * Generate a number of new one time keys.
If total number of keys stored - * by this account exceeds {@link #maxOneTimeKeys()}, the old keys are discarded. - * An exception is thrown if the operation fails.
- * @param aNumberOfKeys number of keys to generate - */ - private native void generateOneTimeKeysJni(int aNumberOfKeys); - - /** - * Return the "one time keys" in a dictionary.
- * The number of "one time keys", is specified by {@link #generateOneTimeKeys(int)}
- * Ex: - * { "curve25519": - * { - * "AAAABQ":"qefVZd8qvjOpsFzoKSAdfUnJVkIreyxWFlipCHjSQQg", - * "AAAABA":"/X8szMU+p+lsTnr56wKjaLgjTMQQkCk8EIWEAilZtQ8", - * "AAAAAw":"qxNxxFHzevFntaaPdT0fhhO7tc7pco4+xB/5VRG81hA", - * } - * }
- * Public API for {@link #oneTimeKeysJni()}.
- * Note: these keys are to be published on the server. - * @return one time keys in string dictionary. - * @exception OlmException the failure reason - */ - public Map> oneTimeKeys() throws OlmException { - JSONObject oneTimeKeysJsonObj = null; - byte[] oneTimeKeysBuffer; - - try { - oneTimeKeysBuffer = oneTimeKeysJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_ONE_TIME_KEYS, e.getMessage()); - } - - if( null != oneTimeKeysBuffer) { - try { - oneTimeKeysJsonObj = new JSONObject(new String(oneTimeKeysBuffer, "UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## oneTimeKeys(): Exception - Msg=" + e.getMessage()); - } - } else { - Log.e(LOG_TAG, "## oneTimeKeys(): Failure - identityKeysJni()=null"); - } - - return OlmUtility.toStringMapMap(oneTimeKeysJsonObj); - } - - /** - * Get the public parts of the unpublished "one time keys" for the account.
- * The returned data is a JSON-formatted object with the single property - * curve25519, which is itself an object mapping key id to - * base64-encoded Curve25519 key.
- * @return byte array containing the one time keys or throw an exception if it fails - */ - private native byte[] oneTimeKeysJni(); - - /** - * Remove the "one time keys" that the session used from the account. - * @param aSession session instance - * @throws OlmException the failure reason - */ - public void removeOneTimeKeys(OlmSession aSession) throws OlmException { - if (null != aSession) { - try { - removeOneTimeKeysJni(aSession.getOlmSessionId()); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_REMOVE_ONE_TIME_KEYS, e.getMessage()); - } - } - } - - /** - * Remove the "one time keys" that the session used from the account. - * An exception is thrown if the operation fails. - * @param aNativeOlmSessionId native session instance identifier - */ - private native void removeOneTimeKeysJni(long aNativeOlmSessionId); - - /** - * Marks the current set of "one time keys" as being published. - * @exception OlmException the failure reason - */ - public void markOneTimeKeysAsPublished() throws OlmException { - try { - markOneTimeKeysAsPublishedJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_MARK_ONE_KEYS_AS_PUBLISHED, e.getMessage()); - } - } - - /** - * Marks the current set of "one time keys" as being published. - * An exception is thrown if the operation fails. - */ - private native void markOneTimeKeysAsPublishedJni(); - - /** - * Sign a message with the ed25519 fingerprint key for this account.
- * The signed message is returned by the method. - * @param aMessage message to sign - * @return the signed message - * @exception OlmException the failure reason - */ - public String signMessage(String aMessage) throws OlmException { - String result = null; - - if (null != aMessage) { - byte[] utf8String = null; - try { - utf8String = aMessage.getBytes("UTF-8"); - if (null != utf8String) { - byte[] signedMessage = signMessageJni(utf8String); - - if (null != signedMessage) { - result = new String(signedMessage, "UTF-8"); - } - } - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_SIGN_MESSAGE, e.getMessage()); - } finally { - if (null != utf8String) { - Arrays.fill(utf8String, (byte) 0); - } - } - } - - return result; - } - - /** - * Sign a message with the ed25519 fingerprint key for this account.
- * The signed message is returned by the method. - * @param aMessage message to sign - * @return the signed message - */ - private native byte[] signMessageJni(byte[] aMessage); - - //============================================================================================================== - // Serialization management - //============================================================================================================== - - /** - * Kick off the serialization mechanism. - * @param aOutStream output stream for serializing - * @throws IOException exception - */ - private void writeObject(ObjectOutputStream aOutStream) throws IOException { - serialize(aOutStream); - } - - /** - * Kick off the deserialization mechanism. - * @param aInStream input stream - * @throws Exception exception - */ - private void readObject(ObjectInputStream aInStream) throws Exception { - deserialize(aInStream); - } - - /** - * Return an account as a bytes buffer.
- * The account is serialized and encrypted with aKey. - * In case of failure, an error human readable - * description is provide in aErrorMsg. - * @param aKey encryption key - * @param aErrorMsg error message description - * @return the account as bytes buffer - */ - @Override - protected byte[] serialize(byte[] aKey, StringBuffer aErrorMsg) { - byte[] pickleRetValue = null; - - // sanity check - if(null == aErrorMsg) { - Log.e(LOG_TAG,"## serialize(): invalid parameter - aErrorMsg=null"); - } else if (null == aKey) { - aErrorMsg.append("Invalid input parameters in serializeDataWithKey()"); - } else { - aErrorMsg.setLength(0); - try { - pickleRetValue = serializeJni(aKey); - } catch (Exception e) { - Log.e(LOG_TAG, "## serialize() failed " + e.getMessage()); - aErrorMsg.append(e.getMessage()); - } - } - - return pickleRetValue; - } - - /** - * Serialize and encrypt account instance.
- * @param aKeyBuffer key used to encrypt the serialized account data - * @return the serialised account as bytes buffer. - **/ - private native byte[] serializeJni(byte[] aKeyBuffer); - - /** - * Loads an account from a pickled bytes buffer.
- * See {@link #serialize(byte[], StringBuffer)} - * @param aSerializedData bytes buffer - * @param aKey key used to encrypted - * @exception Exception the exception - */ - @Override - protected void deserialize(byte[] aSerializedData, byte[] aKey) throws Exception { - String errorMsg = null; - - try { - if ((null == aSerializedData) || (null == aKey)) { - Log.e(LOG_TAG, "## deserialize(): invalid input parameters"); - errorMsg = "invalid input parameters"; - } else { - mNativeId = deserializeJni(aSerializedData, aKey); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## deserialize() failed " + e.getMessage()); - errorMsg = e.getMessage(); - } - - if (!TextUtils.isEmpty(errorMsg)) { - releaseAccount(); - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_DESERIALIZATION, errorMsg); - } - } - - /** - * Allocate a new account and initialize it with the serialisation data.
- * @param aSerializedDataBuffer the account serialisation buffer - * @param aKeyBuffer the key used to encrypt the serialized account data - * @return the deserialized account - **/ - private native long deserializeJni(byte[] aSerializedDataBuffer, byte[] aKeyBuffer); -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmException.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmException.java deleted file mode 100644 index 5b4a85a..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2017 OpenMarket Ltd - * Copyright 2017-2019 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import java.io.IOException; - -/** - * Exception class to identify specific Olm SDK exceptions. - */ -public class OlmException extends IOException { - // exception codes - - public static final int EXCEPTION_CODE_INIT_ACCOUNT_CREATION = 10; - - public static final int EXCEPTION_CODE_ACCOUNT_SERIALIZATION = 100; - public static final int EXCEPTION_CODE_ACCOUNT_DESERIALIZATION = 101; - public static final int EXCEPTION_CODE_ACCOUNT_IDENTITY_KEYS = 102; - public static final int EXCEPTION_CODE_ACCOUNT_GENERATE_ONE_TIME_KEYS = 103; - public static final int EXCEPTION_CODE_ACCOUNT_ONE_TIME_KEYS = 104; - public static final int EXCEPTION_CODE_ACCOUNT_REMOVE_ONE_TIME_KEYS = 105; - public static final int EXCEPTION_CODE_ACCOUNT_MARK_ONE_KEYS_AS_PUBLISHED = 106; - public static final int EXCEPTION_CODE_ACCOUNT_SIGN_MESSAGE = 107; - - public static final int EXCEPTION_CODE_CREATE_INBOUND_GROUP_SESSION = 200; - public static final int EXCEPTION_CODE_INIT_INBOUND_GROUP_SESSION = 201; - public static final int EXCEPTION_CODE_INBOUND_GROUP_SESSION_IDENTIFIER = 202; - public static final int EXCEPTION_CODE_INBOUND_GROUP_SESSION_DECRYPT_SESSION = 203; - public static final int EXCEPTION_CODE_INBOUND_GROUP_SESSION_FIRST_KNOWN_INDEX = 204; - public static final int EXCEPTION_CODE_INBOUND_GROUP_SESSION_IS_VERIFIED = 205; - public static final int EXCEPTION_CODE_INBOUND_GROUP_SESSION_EXPORT = 206; - - public static final int EXCEPTION_CODE_CREATE_OUTBOUND_GROUP_SESSION = 300; - public static final int EXCEPTION_CODE_INIT_OUTBOUND_GROUP_SESSION = 301; - public static final int EXCEPTION_CODE_OUTBOUND_GROUP_SESSION_IDENTIFIER = 302; - public static final int EXCEPTION_CODE_OUTBOUND_GROUP_SESSION_KEY = 303; - public static final int EXCEPTION_CODE_OUTBOUND_GROUP_ENCRYPT_MESSAGE = 304; - - public static final int EXCEPTION_CODE_INIT_SESSION_CREATION = 400; - public static final int EXCEPTION_CODE_SESSION_INIT_OUTBOUND_SESSION = 401; - public static final int EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION = 402; - public static final int EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION_FROM = 403; - public static final int EXCEPTION_CODE_SESSION_ENCRYPT_MESSAGE = 404; - public static final int EXCEPTION_CODE_SESSION_DECRYPT_MESSAGE = 405; - public static final int EXCEPTION_CODE_SESSION_SESSION_IDENTIFIER = 406; - - public static final int EXCEPTION_CODE_UTILITY_CREATION = 500; - public static final int EXCEPTION_CODE_UTILITY_VERIFY_SIGNATURE = 501; - - public static final int EXCEPTION_CODE_PK_ENCRYPTION_CREATION = 600; - public static final int EXCEPTION_CODE_PK_ENCRYPTION_SET_RECIPIENT_KEY = 601; - public static final int EXCEPTION_CODE_PK_ENCRYPTION_ENCRYPT = 602; - - public static final int EXCEPTION_CODE_PK_DECRYPTION_CREATION = 700; - public static final int EXCEPTION_CODE_PK_DECRYPTION_GENERATE_KEY = 701; - public static final int EXCEPTION_CODE_PK_DECRYPTION_DECRYPT = 702; - public static final int EXCEPTION_CODE_PK_DECRYPTION_SET_PRIVATE_KEY = 703; - public static final int EXCEPTION_CODE_PK_DECRYPTION_PRIVATE_KEY = 704; - - public static final int EXCEPTION_CODE_PK_SIGNING_CREATION = 800; - public static final int EXCEPTION_CODE_PK_SIGNING_GENERATE_SEED = 801; - public static final int EXCEPTION_CODE_PK_SIGNING_INIT_WITH_SEED = 802; - public static final int EXCEPTION_CODE_PK_SIGNING_SIGN = 803; - - public static final int EXCEPTION_CODE_SAS_CREATION = 900; - public static final int EXCEPTION_CODE_SAS_ERROR = 901; - public static final int EXCEPTION_CODE_SAS_MISSING_THEIR_PKEY = 902; - public static final int EXCEPTION_CODE_SAS_GENERATE_SHORT_CODE = 903; - - // exception human readable messages - public static final String EXCEPTION_MSG_INVALID_PARAMS_DESERIALIZATION = "invalid de-serialized parameters"; - - /** exception code to be taken from: {@link #EXCEPTION_CODE_CREATE_OUTBOUND_GROUP_SESSION}, {@link #EXCEPTION_CODE_CREATE_INBOUND_GROUP_SESSION}, - * {@link #EXCEPTION_CODE_INIT_OUTBOUND_GROUP_SESSION}, {@link #EXCEPTION_CODE_INIT_INBOUND_GROUP_SESSION}..**/ - private final int mCode; - - /** Human readable message description **/ - private final String mMessage; - - public OlmException(int aExceptionCode, String aExceptionMessage) { - super(); - mCode = aExceptionCode; - mMessage = aExceptionMessage; - } - - public int getExceptionCode() { - return mCode; - } - - @Override - public String getMessage() { - return mMessage; - } -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmInboundGroupSession.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmInboundGroupSession.java deleted file mode 100644 index 2fc81ef..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmInboundGroupSession.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright 2017 OpenMarket Ltd - * Copyright 2017 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.text.TextUtils; -import android.util.Log; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import java.util.Arrays; - -/** - * Class used to create an inbound Megolm session.
- * Counter part of the outbound group session {@link OlmOutboundGroupSession}, this class decrypts the messages sent by the outbound side. - * - *

Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmInboundGroupSession extends CommonSerializeUtils implements Serializable { - private static final long serialVersionUID = -772028491251653253L; - private static final String LOG_TAG = "OlmInboundGroupSession"; - - /** Session Id returned by JNI.
- * This value uniquely identifies the native inbound group session instance. - */ - private transient long mNativeId; - - /** - * Result in {@link #decryptMessage(String)} - */ - public static class DecryptMessageResult { - /** decrypt message **/ - public String mDecryptedMessage; - - /** decrypt index **/ - public long mIndex; - } - - /** - * Constructor.
- * Create and save a new native session instance ID and start a new inbound group session. - * The session key parameter is retrieved from an outbound group session. - * @param aSessionKey session key - * @throws OlmException constructor failure - */ - public OlmInboundGroupSession(String aSessionKey) throws OlmException { - this(aSessionKey, false); - } - - /** - * Constructor.
- * Create and save a new native session instance ID and start a new inbound group session. - * The session key parameter is retrieved from an outbound group session. - * @param aSessionKey session key - * @param isImported true when the session key has been retrieved from a backup - * @throws OlmException constructor failure - */ - private OlmInboundGroupSession(String aSessionKey, boolean isImported) throws OlmException { - if (TextUtils.isEmpty(aSessionKey)) { - Log.e(LOG_TAG, "## initInboundGroupSession(): invalid session key"); - throw new OlmException(OlmException.EXCEPTION_CODE_INIT_INBOUND_GROUP_SESSION, "invalid session key"); - } else { - byte[] sessionBuffer = null; - try { - sessionBuffer = aSessionKey.getBytes("UTF-8"); - mNativeId = createNewSessionJni(aSessionKey.getBytes("UTF-8"), isImported); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_INIT_INBOUND_GROUP_SESSION, e.getMessage()); - } finally { - if (null != sessionBuffer) { - Arrays.fill(sessionBuffer, (byte) 0); - } - } - } - } - - /** - * Initialize a new inbound group session and return it to JAVA side.
- * Since a C prt is returned as a jlong, special care will be taken - * to make the cast (OlmInboundGroupSession* to jlong) platform independent. - * @param aSessionKeyBuffer session key from an outbound session - * @param isImported true when the session key has been retrieved from a backup - * @return the initialized OlmInboundGroupSession* instance or throw an exception it fails. - **/ - private native long createNewSessionJni(byte[] aSessionKeyBuffer, boolean isImported); - - /** - * Create an OlmInboundGroupSession from its exported session data. - * @param exported the exported data - * @return the created OlmException - * @throws OlmException the failure reason - */ - public static OlmInboundGroupSession importSession(String exported) throws OlmException { - return new OlmInboundGroupSession(exported, true); - } - - /** - * Release native session and invalid its JAVA reference counter part.
- * Public API for {@link #releaseSessionJni()}. - */ - public void releaseSession(){ - if (0 != mNativeId) { - releaseSessionJni(); - } - mNativeId = 0; - } - - /** - * Destroy the corresponding OLM inbound group session native object.
- * This method must ALWAYS be called when this JAVA instance - * is destroyed (ie. garbage collected) to prevent memory leak in native side. - * See {@link #createNewSessionJni(byte[], boolean)}. - */ - private native void releaseSessionJni(); - - /** - * Return true the object resources have been released.
- * @return true the object resources have been released - */ - public boolean isReleased() { - return (0 == mNativeId); - } - - /** - * Retrieve the base64-encoded identifier for this inbound group session. - * @return the session ID - * @throws OlmException the failure reason - */ - public String sessionIdentifier() throws OlmException { - try { - return new String(sessionIdentifierJni(), "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionIdentifier() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_INBOUND_GROUP_SESSION_IDENTIFIER, e.getMessage()); - } - } - - /** - * Get a base64-encoded identifier for this inbound group session. - * An exception is thrown if the operation fails. - * @return the base64-encoded identifier - */ - private native byte[] sessionIdentifierJni(); - - /** - * Provides the first known index. - * @return the first known index. - * @throws OlmException the failure reason - */ - public long getFirstKnownIndex() throws OlmException { - long index = 0; - - try { - index = firstKnownIndexJni(); - } catch (Exception e) { - Log.e(LOG_TAG, "## getFirstKnownIndex() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_INBOUND_GROUP_SESSION_FIRST_KNOWN_INDEX, e.getMessage()); - } - - return index; - } - - /** - * Provides the first known index. - * An exception is thrown if the operation fails. - * @return the first known index. - */ - private native long firstKnownIndexJni(); - - /** - * Tells if the session is verified. - * @return true if the session is verified - * @throws OlmException the failure reason - */ - public boolean isVerified() throws OlmException { - boolean isVerified; - - try { - isVerified = isVerifiedJni(); - } catch (Exception e) { - Log.e(LOG_TAG, "## isVerified() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_INBOUND_GROUP_SESSION_IS_VERIFIED, e.getMessage()); - } - - return isVerified; - } - - /** - * Tells if the session is verified. - * @return true if the session is verified - */ - private native boolean isVerifiedJni(); - - /** - * Export the session from a message index as String. - * @param messageIndex the message index - * @return the session as String - * @throws OlmException the failure reason - */ - public String export(long messageIndex) throws OlmException { - String result = null; - - try { - byte[] bytesBuffer = exportJni(messageIndex); - - if (null != bytesBuffer) { - result = new String(bytesBuffer, "UTF-8"); - Arrays.fill(bytesBuffer, (byte) 0); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## export() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_INBOUND_GROUP_SESSION_EXPORT, e.getMessage()); - } - - return result; - } - - /** - * Exports the session as byte array from a message index - * An exception is thrown if the operation fails. - * @param messageIndex key used to encrypt the serialized session data - * @return the session saved as bytes array - */ - private native byte[] exportJni(long messageIndex); - - /** - * Decrypt the message passed in parameter.
- * In case of error, null is returned and an error message description is provided in aErrorMsg. - * @param aEncryptedMsg the message to be decrypted - * @return the decrypted message information - * @exception OlmException the failure reason - */ - public DecryptMessageResult decryptMessage(String aEncryptedMsg) throws OlmException { - DecryptMessageResult result = new DecryptMessageResult(); - - try { - byte[] decryptedMessageBuffer = decryptMessageJni(aEncryptedMsg.getBytes("UTF-8"), result); - - if (null != decryptedMessageBuffer) { - result.mDecryptedMessage = new String(decryptedMessageBuffer, "UTF-8"); - Arrays.fill(decryptedMessageBuffer, (byte) 0); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## decryptMessage() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_INBOUND_GROUP_SESSION_DECRYPT_SESSION, e.getMessage()); - } - - return result; - } - - /** - * Decrypt a message. - * An exception is thrown if the operation fails. - * @param aEncryptedMsg the encrypted message - * @param aDecryptMessageResult the decryptMessage information - * @return the decrypted message - */ - private native byte[] decryptMessageJni(byte[] aEncryptedMsg, DecryptMessageResult aDecryptMessageResult); - - //============================================================================================================== - // Serialization management - //============================================================================================================== - - /** - * Kick off the serialization mechanism. - * @param aOutStream output stream for serializing - * @throws IOException exception - */ - private void writeObject(ObjectOutputStream aOutStream) throws IOException { - serialize(aOutStream); - } - - /** - * Kick off the deserialization mechanism. - * @param aInStream input stream - * @throws Exception exception - */ - private void readObject(ObjectInputStream aInStream) throws Exception { - deserialize(aInStream); - } - - /** - * Return the current inbound group session as a bytes buffer.
- * The session is serialized and encrypted with aKey. - * In case of failure, an error human readable - * description is provide in aErrorMsg. - * @param aKey encryption key - * @param aErrorMsg error message description - * @return pickled bytes buffer if operation succeed, null otherwise - */ - @Override - protected byte[] serialize(byte[] aKey, StringBuffer aErrorMsg) { - byte[] pickleRetValue = null; - - // sanity check - if(null == aErrorMsg) { - Log.e(LOG_TAG,"## serialize(): invalid parameter - aErrorMsg=null"); - } else if (null == aKey) { - aErrorMsg.append("Invalid input parameters in serialize()"); - } else { - aErrorMsg.setLength(0); - try { - pickleRetValue = serializeJni(aKey); - } catch (Exception e) { - Log.e(LOG_TAG, "## serialize() failed " + e.getMessage()); - aErrorMsg.append(e.getMessage()); - } - } - - return pickleRetValue; - } - /** - * JNI counter part of {@link #serialize(byte[], StringBuffer)}. - * @param aKey encryption key - * @return the serialized session - */ - private native byte[] serializeJni(byte[] aKey); - - /** - * Loads an account from a pickled base64 string.
- * See {@link #serialize(byte[], StringBuffer)} - * @param aSerializedData pickled account in a bytes buffer - * @param aKey key used to encrypted - */ - @Override - protected void deserialize(byte[] aSerializedData, byte[] aKey) throws Exception { - String errorMsg = null; - - try { - if ((null == aSerializedData) || (null == aKey)) { - Log.e(LOG_TAG, "## deserialize(): invalid input parameters"); - errorMsg = "invalid input parameters"; - } else { - mNativeId = deserializeJni(aSerializedData, aKey); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## deserialize() failed " + e.getMessage()); - errorMsg = e.getMessage(); - } - - if (!TextUtils.isEmpty(errorMsg)) { - releaseSession(); - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_DESERIALIZATION, errorMsg); - } - } - - /** - * Allocate a new session and initialize it with the serialisation data.
- * An exception is thrown if the operation fails. - * @param aSerializedData the session serialisation buffer - * @param aKey the key used to encrypt the serialized account data - * @return the deserialized session - **/ - private native long deserializeJni(byte[] aSerializedData, byte[] aKey); -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmManager.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmManager.java deleted file mode 100644 index cd33a5a..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2016 OpenMarket Ltd - * Copyright 2016 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.content.Context; -import android.util.Log; - -/** - * Olm SDK entry point class.
An OlmManager instance must be created at first to enable native library load. - *

Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmManager { - private static final String LOG_TAG = "OlmManager"; - - /** - * Constructor. - */ - public OlmManager() { - } - - static { - try { - java.lang.System.loadLibrary("olm"); - } catch(UnsatisfiedLinkError e) { - Log.e(LOG_TAG,"Exception loadLibrary() - Msg="+e.getMessage()); - } - } - - /** - * Provide the android library version - * @return the library version - */ - public String getVersion() { - return BuildConfig.VERSION_NAME; - } - - /** - * Provide a detailed version. - * It contains the android and the native libraries versions. - * @param context the context - * @return the detailed version - */ - public String getDetailedVersion(Context context) { - String gitVersion = context.getResources().getString(R.string.git_olm_revision); - String date = context.getResources().getString(R.string.git_olm_revision_date); - return getVersion() + " - olm version (" + getOlmLibVersion() + ") - " + gitVersion + "-" + date; - } - - /** - * Provide the native OLM lib version. - * @return the lib version as a string - */ - public String getOlmLibVersion(){ - return getOlmLibVersionJni(); - } - public native String getOlmLibVersionJni(); -} - diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmMessage.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmMessage.java deleted file mode 100644 index 08db993..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmMessage.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2016 OpenMarket Ltd - * Copyright 2016 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -/** - * Message class used in Olm sessions to contain the encrypted data.
- * See {@link OlmSession#decryptMessage(OlmMessage)} and {@link OlmSession#encryptMessage(String)}. - *
Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmMessage { - /** PRE KEY message type (used to establish new Olm session) **/ - public final static int MESSAGE_TYPE_PRE_KEY = 0; - /** normal message type **/ - public final static int MESSAGE_TYPE_MESSAGE = 1; - - /** the encrypted message **/ - public String mCipherText; - - /** defined by {@link #MESSAGE_TYPE_MESSAGE} or {@link #MESSAGE_TYPE_PRE_KEY}**/ - public long mType; -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmOutboundGroupSession.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmOutboundGroupSession.java deleted file mode 100644 index 55732fe..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmOutboundGroupSession.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Copyright 2017 OpenMarket Ltd - * Copyright 2017 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - - -import android.text.TextUtils; -import android.util.Log; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import java.util.Arrays; - -/** - * Class used to create an outbound a Megolm session.
- * To send a first message in an encrypted room, the client should start a new outbound Megolm session. - * The session ID and the session key must be shared with each device in the room within. - * - *

Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmOutboundGroupSession extends CommonSerializeUtils implements Serializable { - private static final long serialVersionUID = -3133097431283604416L; - private static final String LOG_TAG = "OlmOutboundGroupSession"; - - /** Session Id returned by JNI.
- * This value uniquely identifies the native outbound group session instance. - */ - private transient long mNativeId; - - /** - * Constructor.
- * Create and save a new session native instance ID and - * initialise a new outbound group session.
- * @throws OlmException constructor failure - */ - public OlmOutboundGroupSession() throws OlmException { - try { - mNativeId = createNewSessionJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_CREATE_OUTBOUND_GROUP_SESSION, e.getMessage()); - } - } - - /** - * Create the corresponding OLM outbound group session in native side.
- * An exception is thrown if the operation fails. - * Do not forget to call {@link #releaseSession()} when JAVA side is done. - * @return native session instance identifier (see {@link #mNativeId}) - */ - private native long createNewSessionJni(); - - /** - * Release native session and invalid its JAVA reference counter part.
- * Public API for {@link #releaseSessionJni()}. - */ - public void releaseSession() { - if (0 != mNativeId) { - releaseSessionJni(); - } - mNativeId = 0; - } - - /** - * Destroy the corresponding OLM outbound group session native object.
- * This method must ALWAYS be called when this JAVA instance - * is destroyed (ie. garbage collected) to prevent memory leak in native side. - * See {@link #createNewSessionJni()}. - */ - private native void releaseSessionJni(); - - /** - * Return true the object resources have been released.
- * @return true the object resources have been released - */ - public boolean isReleased() { - return (0 == mNativeId); - } - - /** - * Get a base64-encoded identifier for this session. - * @return session identifier - * @throws OlmException the failure reason - */ - public String sessionIdentifier() throws OlmException { - try { - return new String(sessionIdentifierJni(), "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionIdentifier() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_OUTBOUND_GROUP_SESSION_IDENTIFIER, e.getMessage()); - } - } - - /** - * Return the session identifier. - * An exception is thrown if the operation fails. - * @return the session identifier - */ - private native byte[] sessionIdentifierJni(); - - /** - * Get the current message index for this session.
- * Each message is sent with an increasing index, this - * method returns the index for the next message. - * @return current session index - */ - public int messageIndex() { - return messageIndexJni(); - } - - /** - * Get the current message index for this session.
- * Each message is sent with an increasing index, this - * method returns the index for the next message. - * An exception is thrown if the operation fails. - * @return current session index - */ - private native int messageIndexJni(); - - /** - * Get the base64-encoded current ratchet key for this session.
- * Each message is sent with a different ratchet key. This method returns the - * ratchet key that will be used for the next message. - * @return outbound session key - * @exception OlmException the failure reason - */ - public String sessionKey() throws OlmException { - try { - byte[] sessionKeyBuffer = sessionKeyJni(); - String ret = new String(sessionKeyBuffer, "UTF-8"); - Arrays.fill(sessionKeyBuffer, (byte) 0); - return ret; - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionKey() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_OUTBOUND_GROUP_SESSION_KEY, e.getMessage()); - } - } - - /** - * Return the session key. - * An exception is thrown if the operation fails. - * @return the session key - */ - private native byte[] sessionKeyJni(); - - /** - * Encrypt some plain-text message.
- * The message given as parameter is encrypted and returned as the return value. - * @param aClearMsg message to be encrypted - * @return the encrypted message - * @exception OlmException the encryption failure reason - */ - public String encryptMessage(String aClearMsg) throws OlmException { - String retValue = null; - - if (!TextUtils.isEmpty(aClearMsg)) { - try { - byte[] clearMsgBuffer = aClearMsg.getBytes("UTF-8"); - byte[] encryptedBuffer = encryptMessageJni(clearMsgBuffer); - Arrays.fill(clearMsgBuffer, (byte) 0); - - if (null != encryptedBuffer) { - retValue = new String(encryptedBuffer , "UTF-8"); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## encryptMessage() failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_OUTBOUND_GROUP_ENCRYPT_MESSAGE, e.getMessage()); - } - } - - return retValue; - } - - /** - * Encrypt a bytes buffer messages. - * An exception is thrown if the operation fails. - * @param aClearMsgBuffer the message to encode - * @return the encoded message - */ - private native byte[] encryptMessageJni(byte[] aClearMsgBuffer); - - //============================================================================================================== - // Serialization management - //============================================================================================================== - - /** - * Kick off the serialization mechanism. - * @param aOutStream output stream for serializing - * @throws IOException exception - */ - private void writeObject(ObjectOutputStream aOutStream) throws IOException { - serialize(aOutStream); - } - - /** - * Kick off the deserialization mechanism. - * @param aInStream input stream - * @throws Exception exception - */ - private void readObject(ObjectInputStream aInStream) throws Exception { - deserialize(aInStream); - } - - /** - * Return the current outbound group session as a base64 byte buffers.
- * The session is serialized and encrypted with aKey. - * In case of failure, an error human readable - * description is provide in aErrorMsg. - * @param aKey encryption key - * @param aErrorMsg error message description - * @return pickled base64 bytes buffer if operation succeed, null otherwise - */ - @Override - protected byte[] serialize(byte[] aKey, StringBuffer aErrorMsg) { - byte[] pickleRetValue = null; - - // sanity check - if(null == aErrorMsg) { - Log.e(LOG_TAG,"## serialize(): invalid parameter - aErrorMsg=null"); - } else if (null == aKey) { - aErrorMsg.append("Invalid input parameters in serialize()"); - } else { - try { - pickleRetValue = serializeJni(aKey); - } catch (Exception e) { - Log.e(LOG_TAG,"## serialize(): failed " + e.getMessage()); - aErrorMsg.append(e.getMessage()); - } - } - - return pickleRetValue; - } - - /** - * JNI counter part of {@link #serialize(byte[], StringBuffer)}. - * An exception is thrown if the operation fails. - * @param aKey encryption key - * @return the serialized session - */ - private native byte[] serializeJni(byte[] aKey); - - /** - * Loads an account from a pickled base64 string.
- * See {@link #serialize(byte[], StringBuffer)} - * @param aSerializedData pickled account in a base64 bytes buffer - * @param aKey key used to encrypted - * @exception Exception the exception - */ - @Override - protected void deserialize(byte[] aSerializedData, byte[] aKey) throws Exception { - String errorMsg = null; - - try { - if ((null == aSerializedData) || (null == aKey)) { - Log.e(LOG_TAG, "## deserialize(): invalid input parameters"); - errorMsg = "invalid input parameters"; - } else { - mNativeId = deserializeJni(aSerializedData, aKey); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## deserialize() failed " + e.getMessage()); - errorMsg = e.getMessage(); - } - - if (!TextUtils.isEmpty(errorMsg)) { - releaseSession(); - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_DESERIALIZATION, errorMsg); - } - } - - /** - * Allocate a new session and initialize it with the serialisation data.
- * An exception is thrown if the operation fails. - * @param aSerializedData the session serialisation buffer - * @param aKey the key used to encrypt the serialized account data - * @return the deserialized session - **/ - private native long deserializeJni(byte[] aSerializedData, byte[] aKey); - -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkDecryption.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkDecryption.java deleted file mode 100644 index 6a6a22b..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkDecryption.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2018 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.util.Log; - -import java.util.Arrays; - -public class OlmPkDecryption { - private static final String LOG_TAG = "OlmPkDecryption"; - - /** Session Id returned by JNI. - * This value uniquely identifies the native session instance. - **/ - private transient long mNativeId; - - public OlmPkDecryption() throws OlmException { - try { - mNativeId = createNewPkDecryptionJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_PK_DECRYPTION_CREATION, e.getMessage()); - } - } - - private native long createNewPkDecryptionJni(); - - private native void releasePkDecryptionJni(); - - public void releaseDecryption() { - if (0 != mNativeId) { - releasePkDecryptionJni(); - } - mNativeId = 0; - } - - public boolean isReleased() { - return (0 == mNativeId); - } - - public static native int privateKeyLength(); - - public String setPrivateKey(byte[] privateKey) throws OlmException { - try { - byte[] key = setPrivateKeyJni(privateKey); - return new String(key, "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## setPrivateKey(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_DECRYPTION_SET_PRIVATE_KEY, e.getMessage()); - } - } - - private native byte[] setPrivateKeyJni(byte[] privateKey); - - public String generateKey() throws OlmException { - try { - byte[] key = generateKeyJni(); - return new String(key, "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## setRecipientKey(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_DECRYPTION_GENERATE_KEY, e.getMessage()); - } - } - - private native byte[] generateKeyJni(); - - public byte[] privateKey() throws OlmException { - try { - return privateKeyJni(); - } catch (Exception e) { - Log.e(LOG_TAG, "## privateKey(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_DECRYPTION_PRIVATE_KEY, e.getMessage()); - } - } - - private native byte[] privateKeyJni(); - - public String decrypt(OlmPkMessage aMessage) throws OlmException { - if (null == aMessage) { - return null; - } - - byte[] plaintextBuffer = decryptJni(aMessage); - try { - String plaintext = new String(plaintextBuffer, "UTF-8"); - return plaintext; - } catch (Exception e) { - Log.e(LOG_TAG, "## pkDecrypt(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_DECRYPTION_DECRYPT, e.getMessage()); - } finally { - Arrays.fill(plaintextBuffer, (byte) 0); - } - } - - private native byte[] decryptJni(OlmPkMessage aMessage); -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkEncryption.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkEncryption.java deleted file mode 100644 index 01666fd..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkEncryption.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2018 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.util.Log; - -import java.util.Arrays; - -public class OlmPkEncryption { - private static final String LOG_TAG = "OlmPkEncryption"; - - /** Session Id returned by JNI. - * This value uniquely identifies the native session instance. - **/ - private transient long mNativeId; - - public OlmPkEncryption() throws OlmException { - try { - mNativeId = createNewPkEncryptionJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_PK_ENCRYPTION_CREATION, e.getMessage()); - } - } - - private native long createNewPkEncryptionJni(); - - private native void releasePkEncryptionJni(); - - public void releaseEncryption() { - if (0 != mNativeId) { - releasePkEncryptionJni(); - } - mNativeId = 0; - } - - public boolean isReleased() { - return (0 == mNativeId); - } - - public void setRecipientKey(String aKey) throws OlmException { - if (null == aKey) { - return; - } - - try { - setRecipientKeyJni(aKey.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## setRecipientKey(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_ENCRYPTION_SET_RECIPIENT_KEY, e.getMessage()); - } - } - - private native void setRecipientKeyJni(byte[] aKey); - - public OlmPkMessage encrypt(String aPlaintext) throws OlmException { - if (null == aPlaintext) { - return null; - } - - OlmPkMessage encryptedMsgRetValue = new OlmPkMessage(); - - byte[] plaintextBuffer = null; - try { - plaintextBuffer = aPlaintext.getBytes("UTF-8"); - byte[] ciphertextBuffer = encryptJni(plaintextBuffer, encryptedMsgRetValue); - - if (null != ciphertextBuffer) { - encryptedMsgRetValue.mCipherText = new String(ciphertextBuffer, "UTF-8"); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## pkEncrypt(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_ENCRYPTION_ENCRYPT, e.getMessage()); - } finally { - if (null != plaintextBuffer) { - Arrays.fill(plaintextBuffer, (byte) 0); - } - } - - return encryptedMsgRetValue; - } - - private native byte[] encryptJni(byte[] plaintext, OlmPkMessage aMessage); -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkMessage.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkMessage.java deleted file mode 100644 index f8a065a..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkMessage.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2018 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -public class OlmPkMessage { - public String mCipherText; - public String mMac; - public String mEphemeralKey; -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkSigning.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkSigning.java deleted file mode 100644 index 89cb556..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmPkSigning.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2019 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.util.Log; - -import java.util.Arrays; - -public class OlmPkSigning { - private static final String LOG_TAG = "OlmPkSigning"; - - /** PK Signing Id returned by JNI. - * This value uniquely identifies the native PK signing instance. - **/ - private transient long mNativeId; - - public OlmPkSigning() throws OlmException { - try { - mNativeId = createNewPkSigningJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_PK_SIGNING_CREATION, e.getMessage()); - } - } - - private native long createNewPkSigningJni(); - - private native void releasePkSigningJni(); - - public void releaseSigning() { - if (0 != mNativeId) { - releasePkSigningJni(); - } - mNativeId = 0; - } - - public boolean isReleased() { - return (0 == mNativeId); - } - - public static native int seedLength(); - - public static byte[] generateSeed() throws OlmException { - try { - return generateSeedJni(); - } catch (Exception e) { - Log.e(LOG_TAG, "## generateSeed(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_SIGNING_GENERATE_SEED, e.getMessage()); - } - } - - public static native byte[] generateSeedJni(); - - public String initWithSeed(byte[] seed) throws OlmException { - try { - byte[] pubKey = setKeyFromSeedJni(seed); - return new String(pubKey, "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## initWithSeed(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_SIGNING_INIT_WITH_SEED, e.getMessage()); - } - } - - public native byte[] setKeyFromSeedJni(byte[] seed); - - public String sign(String aMessage) throws OlmException { - if (null == aMessage) { - return null; - } - - byte[] messageBuffer = null; - try { - messageBuffer = aMessage.getBytes("UTF-8"); - byte[] signature = pkSignJni(messageBuffer); - return new String(signature, "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## pkSign(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_PK_SIGNING_SIGN, e.getMessage()); - } finally { - if (null != messageBuffer) { - Arrays.fill(messageBuffer, (byte) 0); - } - } - } - - private native byte[] pkSignJni(byte[] message); -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmSAS.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmSAS.java deleted file mode 100644 index a0589e9..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmSAS.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2019 New Vector Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.matrix.olm; - -import android.util.Log; - -import java.io.UnsupportedEncodingException; - -public class OlmSAS { - - private static final String LOG_TAG = OlmSAS.class.getName(); - /** - * Session Id returned by JNI. - * This value uniquely identifies the native SAS instance. - **/ - private transient long mNativeId; - - private String theirPublicKey = null; - - public OlmSAS() throws OlmException { - try { - mNativeId = createNewSASJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_CREATION, e.getMessage()); - } - } - - /** - * Gets the Public Key encoded in Base64 with no padding - * @return The public key - * @throws OlmException the failure reason - */ - public String getPublicKey() throws OlmException { - try { - byte[] buffer = getPubKeyJni(); - - if (null != buffer) { - return new String(buffer, "UTF-8"); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionIdentifier(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_ERROR, e.getMessage()); - } - - return null; - } - - /** - * Sets the public key of other user. - * - * @param otherPkey other user public key (base64 encoded with no padding) - * @throws OlmException the failure reason - */ - public void setTheirPublicKey(String otherPkey) throws OlmException { - try { - setTheirPubKey(otherPkey.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_ERROR, e.getMessage()); - } - this.theirPublicKey = otherPkey; - } - - - /** - * Generate bytes to use for the short authentication string. - * - * @param info info extra information to mix in when generating the bytes, as - * per the Matrix spec. - * @param byteNumber The size of the short code to generate - * @return The generated shortcode - * @throws OlmException the failure reason - */ - public byte[] generateShortCode(String info, int byteNumber) throws OlmException { - if (theirPublicKey == null || theirPublicKey.isEmpty()) { - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_MISSING_THEIR_PKEY, "call setTheirPublicKey first"); - } - try { - return generateShortCodeJni(info.getBytes("UTF-8"), byteNumber); - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionIdentifier(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_GENERATE_SHORT_CODE, e.getMessage()); - } - } - - - public String calculateMac(String message, String info) throws OlmException { - try { - byte[] bytes = calculateMacJni(message.getBytes("UTF-8"), info.getBytes("UTF-8")); - if (bytes != null) return new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_ERROR, e.getMessage()); - } - return null; - } - - public String calculateMacLongKdf(String message, String info) throws OlmException { - try { - byte[] bytes = calculateMacLongKdfJni(message.getBytes("UTF-8"), info.getBytes("UTF-8")); - if (bytes != null) return new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new OlmException(OlmException.EXCEPTION_CODE_SAS_ERROR, e.getMessage()); - } - return null; - } - - /** - * Create an OLM session in native side.
- * Do not forget to call {@link #releaseSASJni()} when JAVA side is done. - * - * @return native account instance identifier or throw an exception. - */ - private native long createNewSASJni(); - - /** - * Destroy the corresponding OLM session native object.
- * This method must ALWAYS be called when this JAVA instance - * is destroyed (ie. garbage collected) to prevent memory leak in native side. - * See {@link #createNewSASJni()}. - */ - private native void releaseSASJni(); - - private native byte[] getPubKeyJni(); - - private native void setTheirPubKey(byte[] pubKey); - - private native byte[] generateShortCodeJni(byte[] info, int byteNumber); - - private native byte[] calculateMacJni(byte[] message, byte[] info); - - private native byte[] calculateMacLongKdfJni(byte[] message, byte[] info); - - /** - * Release native session and invalid its JAVA reference counter part.
- * Public API for {@link #releaseSASJni()}. - */ - public void releaseSas() { - if (0 != mNativeId) { - releaseSASJni(); - } - mNativeId = 0; - } -} diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmSession.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmSession.java deleted file mode 100644 index 3c5ce49..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmSession.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Copyright 2016 OpenMarket Ltd - * Copyright 2016 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.text.TextUtils; -import android.util.Log; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import java.util.Arrays; - -/** - * Session class used to create Olm sessions in conjunction with {@link OlmAccount} class.
- * Olm session is used to encrypt data between devices, especially to create Olm group sessions (see {@link OlmOutboundGroupSession} and {@link OlmInboundGroupSession}).
- * To establish an Olm session with Bob, Alice calls {@link #initOutboundSession(OlmAccount, String, String)} with Bob's identity and onetime keys. Then Alice generates an encrypted PRE_KEY message ({@link #encryptMessage(String)}) - * used by Bob to open the Olm session in his side with {@link #initOutboundSession(OlmAccount, String, String)}. - * From this step on, messages can be exchanged by using {@link #encryptMessage(String)} and {@link #decryptMessage(OlmMessage)}. - *

Detailed implementation guide is available at Implementing End-to-End Encryption in Matrix clients. - */ -public class OlmSession extends CommonSerializeUtils implements Serializable { - private static final long serialVersionUID = -8975488639186976419L; - private static final String LOG_TAG = "OlmSession"; - - /** Session Id returned by JNI. - * This value uniquely identifies the native session instance. - **/ - private transient long mNativeId; - - public OlmSession() throws OlmException { - try { - mNativeId = createNewSessionJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_INIT_SESSION_CREATION, e.getMessage()); - } - } - - /** - * Create an OLM session in native side.
- * Do not forget to call {@link #releaseSession()} when JAVA side is done. - * @return native account instance identifier or throw an exception. - */ - private native long createNewSessionJni(); - - /** - * Getter on the session ID. - * @return native session ID - */ - long getOlmSessionId(){ - return mNativeId; - } - - /** - * Destroy the corresponding OLM session native object.
- * This method must ALWAYS be called when this JAVA instance - * is destroyed (ie. garbage collected) to prevent memory leak in native side. - * See {@link #createNewSessionJni()}. - */ - private native void releaseSessionJni(); - - /** - * Release native session and invalid its JAVA reference counter part.
- * Public API for {@link #releaseSessionJni()}. - */ - public void releaseSession() { - if (0 != mNativeId) { - releaseSessionJni(); - } - mNativeId = 0; - } - - /** - * Return true the object resources have been released.
- * @return true the object resources have been released - */ - public boolean isReleased() { - return (0 == mNativeId); - } - - /** - * Creates a new out-bound session for sending messages to a recipient - * identified by an identity key and a one time key.
- * @param aAccount the account to associate with this session - * @param aTheirIdentityKey the identity key of the recipient - * @param aTheirOneTimeKey the one time key of the recipient - * @exception OlmException the failure reason - */ - public void initOutboundSession(OlmAccount aAccount, String aTheirIdentityKey, String aTheirOneTimeKey) throws OlmException { - if ((null == aAccount) || TextUtils.isEmpty(aTheirIdentityKey) || TextUtils.isEmpty(aTheirOneTimeKey)) { - Log.e(LOG_TAG, "## initOutboundSession(): invalid input parameters"); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_OUTBOUND_SESSION, "invalid input parameters"); - } else { - try { - initOutboundSessionJni(aAccount.getOlmAccountId(), aTheirIdentityKey.getBytes("UTF-8"), aTheirOneTimeKey.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## initOutboundSession(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_OUTBOUND_SESSION, e.getMessage()); - } - } - } - - /** - * Create a new in-bound session for sending/receiving messages from an - * incoming PRE_KEY message.
The recipient is defined as the entity - * with whom the session is established. - * An exception is thrown if the operation fails. - * @param aOlmAccountId account instance - * @param aTheirIdentityKey the identity key of the recipient - * @param aTheirOneTimeKey the one time key of the recipient - **/ - private native void initOutboundSessionJni(long aOlmAccountId, byte[] aTheirIdentityKey, byte[] aTheirOneTimeKey); - - /** - * Create a new in-bound session for sending/receiving messages from an - * incoming PRE_KEY message ({@link OlmMessage#MESSAGE_TYPE_PRE_KEY}).
- * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * @param aAccount the account to associate with this session - * @param aPreKeyMsg PRE KEY message - * @exception OlmException the failure reason - */ - public void initInboundSession(OlmAccount aAccount, String aPreKeyMsg) throws OlmException { - if ((null == aAccount) || TextUtils.isEmpty(aPreKeyMsg)){ - Log.e(LOG_TAG, "## initInboundSession(): invalid input parameters"); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION, "invalid input parameters"); - } else { - try { - initInboundSessionJni(aAccount.getOlmAccountId(), aPreKeyMsg.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## initInboundSession(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION, e.getMessage()); - } - } - } - - /** - * Create a new in-bound session for sending/receiving messages from an - * incoming PRE_KEY message.
- * An exception is thrown if the operation fails. - * @param aOlmAccountId account instance - * @param aOneTimeKeyMsg PRE_KEY message - */ - private native void initInboundSessionJni(long aOlmAccountId, byte[] aOneTimeKeyMsg); - - /** - * Create a new in-bound session for sending/receiving messages from an - * incoming PRE_KEY({@link OlmMessage#MESSAGE_TYPE_PRE_KEY}) message based on the sender identity key.
- * Public API for {@link #initInboundSessionFromIdKeyJni(long, byte[], byte[])}. - * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * This method must only be called the first time a pre-key message is received from an inbound session. - * @param aAccount the account to associate with this session - * @param aTheirIdentityKey the sender identity key - * @param aPreKeyMsg PRE KEY message - * @exception OlmException the failure reason - */ - public void initInboundSessionFrom(OlmAccount aAccount, String aTheirIdentityKey, String aPreKeyMsg) throws OlmException { - if ( (null==aAccount) || TextUtils.isEmpty(aPreKeyMsg)){ - Log.e(LOG_TAG, "## initInboundSessionFrom(): invalid input parameters"); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION_FROM, "invalid input parameters"); - } else { - try { - initInboundSessionFromIdKeyJni(aAccount.getOlmAccountId(), aTheirIdentityKey.getBytes("UTF-8"), aPreKeyMsg.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## initInboundSessionFrom(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_INIT_INBOUND_SESSION_FROM, e.getMessage()); - } - } - } - - /** - * Create a new in-bound session for sending/receiving messages from an - * incoming PRE_KEY message based on the recipient identity key.
- * An exception is thrown if the operation fails. - * @param aOlmAccountId account instance - * @param aTheirIdentityKey the identity key of the recipient - * @param aOneTimeKeyMsg encrypted message - */ - private native void initInboundSessionFromIdKeyJni(long aOlmAccountId, byte[] aTheirIdentityKey, byte[] aOneTimeKeyMsg); - - /** - * Get the session identifier.
Will be the same for both ends of the - * conversation. The session identifier is returned as a String object. - * Session Id sample: "session_id":"M4fOVwD6AABrkTKl" - * Public API for {@link #getSessionIdentifierJni()}. - * @return the session ID - * @exception OlmException the failure reason - */ - public String sessionIdentifier() throws OlmException { - try { - byte[] buffer = getSessionIdentifierJni(); - - if (null != buffer) { - return new String(buffer, "UTF-8"); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## sessionIdentifier(): " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_SESSION_IDENTIFIER, e.getMessage()); - } - - return null; - } - - /** - * Get the session identifier for this session. - * An exception is thrown if the operation fails. - * @return the session identifier - */ - private native byte[] getSessionIdentifierJni(); - - /** - * Checks if the PRE_KEY({@link OlmMessage#MESSAGE_TYPE_PRE_KEY}) message is for this in-bound session.
- * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * Public API for {@link #matchesInboundSessionJni(byte[])}. - * @param aOneTimeKeyMsg PRE KEY message - * @return true if the one time key matches. - */ - public boolean matchesInboundSession(String aOneTimeKeyMsg) { - boolean retCode = false; - - try { - retCode = matchesInboundSessionJni(aOneTimeKeyMsg.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## matchesInboundSession(): failed " + e.getMessage()); - } - - return retCode; - } - - /** - * Checks if the PRE_KEY message is for this in-bound session.
- * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * An exception is thrown if the operation fails. - * @param aOneTimeKeyMsg PRE KEY message - * @return true if the PRE_KEY message matches - */ - private native boolean matchesInboundSessionJni(byte[] aOneTimeKeyMsg); - - /** - * Checks if the PRE_KEY({@link OlmMessage#MESSAGE_TYPE_PRE_KEY}) message is for this in-bound session based on the sender identity key.
- * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * Public API for {@link #matchesInboundSessionJni(byte[])}. - * @param aTheirIdentityKey the sender identity key - * @param aOneTimeKeyMsg PRE KEY message - * @return this if operation succeed, null otherwise - */ - public boolean matchesInboundSessionFrom(String aTheirIdentityKey, String aOneTimeKeyMsg) { - boolean retCode = false; - - try { - retCode = matchesInboundSessionFromIdKeyJni(aTheirIdentityKey.getBytes("UTF-8"), aOneTimeKeyMsg.getBytes("UTF-8")); - } catch (Exception e) { - Log.e(LOG_TAG, "## matchesInboundSessionFrom(): failed " + e.getMessage()); - } - - return retCode; - } - - /** - * Checks if the PRE_KEY message is for this in-bound session based on the sender identity key.
- * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY). - * An exception is thrown if the operation fails. - * @param aTheirIdentityKey the identity key of the sender - * @param aOneTimeKeyMsg PRE KEY message - * @return true if the PRE_KEY message matches. - */ - private native boolean matchesInboundSessionFromIdKeyJni(byte[] aTheirIdentityKey, byte[] aOneTimeKeyMsg); - - /** - * Encrypt a message using the session.
- * The encrypted message is returned in a OlmMessage object. - * Public API for {@link #encryptMessageJni(byte[], OlmMessage)}. - * @param aClearMsg message to encrypted - * @return the encrypted message - * @exception OlmException the failure reason - */ - public OlmMessage encryptMessage(String aClearMsg) throws OlmException { - if (null == aClearMsg) { - return null; - } - - OlmMessage encryptedMsgRetValue = new OlmMessage(); - - try { - byte[] clearMsgBuffer = aClearMsg.getBytes("UTF-8"); - byte[] encryptedMessageBuffer = encryptMessageJni(clearMsgBuffer, encryptedMsgRetValue); - Arrays.fill(clearMsgBuffer, (byte) 0); - - if (null != encryptedMessageBuffer) { - encryptedMsgRetValue.mCipherText = new String(encryptedMessageBuffer, "UTF-8"); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## encryptMessage(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_ENCRYPT_MESSAGE, e.getMessage()); - } - - return encryptedMsgRetValue; - } - - /** - * Encrypt a message using the session.
- * An exception is thrown if the operation fails. - * @param aClearMsg clear text message - * @param aEncryptedMsg ciphered message - * @return the encrypted message - */ - private native byte[] encryptMessageJni(byte[] aClearMsg, OlmMessage aEncryptedMsg); - - /** - * Decrypt a message using the session.
- * The encrypted message is given as a OlmMessage object. - * @param aEncryptedMsg message to decrypt - * @return the decrypted message - * @exception OlmException the failure reason - */ - public String decryptMessage(OlmMessage aEncryptedMsg) throws OlmException { - if (null == aEncryptedMsg) { - return null; - } - - try { - byte[] plaintextBuffer = decryptMessageJni(aEncryptedMsg); - String plaintext = new String(plaintextBuffer, "UTF-8"); - Arrays.fill(plaintextBuffer, (byte) 0); - return plaintext; - } catch (Exception e) { - Log.e(LOG_TAG, "## decryptMessage(): failed " + e.getMessage()); - throw new OlmException(OlmException.EXCEPTION_CODE_SESSION_DECRYPT_MESSAGE, e.getMessage()); - } - } - /** - * Decrypt a message using the session.
- * An exception is thrown if the operation fails. - * @param aEncryptedMsg message to decrypt - * @return the decrypted message - */ - private native byte[] decryptMessageJni(OlmMessage aEncryptedMsg); - - //============================================================================================================== - // Serialization management - //============================================================================================================== - - /** - * Kick off the serialization mechanism. - * @param aOutStream output stream for serializing - * @throws IOException exception - */ - private void writeObject(ObjectOutputStream aOutStream) throws IOException { - serialize(aOutStream); - } - - /** - * Kick off the deserialization mechanism. - * @param aInStream input stream - * @throws IOException exception - * @throws ClassNotFoundException exception - */ - private void readObject(ObjectInputStream aInStream) throws Exception { - deserialize(aInStream); - } - - /** - * Return a session as a bytes buffer.
- * The account is serialized and encrypted with aKey. - * In case of failure, an error human readable - * description is provide in aErrorMsg. - * @param aKey encryption key - * @param aErrorMsg error message description - * @return session as a bytes buffer - */ - @Override - protected byte[] serialize(byte[] aKey, StringBuffer aErrorMsg) { - byte[] pickleRetValue = null; - - // sanity check - if(null == aErrorMsg) { - Log.e(LOG_TAG,"## serializeDataWithKey(): invalid parameter - aErrorMsg=null"); - } else if (null == aKey) { - aErrorMsg.append("Invalid input parameters in serializeDataWithKey()"); - } else { - aErrorMsg.setLength(0); - try { - pickleRetValue = serializeJni(aKey); - } catch (Exception e) { - Log.e(LOG_TAG,"## serializeDataWithKey(): failed " + e.getMessage()); - aErrorMsg.append(e.getMessage()); - } - } - - return pickleRetValue; - } - - /** - * Serialize and encrypt session instance.
- * An exception is thrown if the operation fails. - * @param aKeyBuffer key used to encrypt the serialized account data - * @return the serialised account as bytes buffer. - **/ - private native byte[] serializeJni(byte[] aKeyBuffer); - - /** - * Loads an account from a pickled base64 string.
- * See {@link #serialize(byte[], StringBuffer)} - * @param aSerializedData pickled account in a base64 string format - * @param aKey key used to encrypted - */ - @Override - protected void deserialize(byte[] aSerializedData, byte[] aKey) throws Exception { - String errorMsg = null; - - try { - if ((null == aSerializedData) || (null == aKey)) { - Log.e(LOG_TAG, "## deserialize(): invalid input parameters"); - errorMsg = "invalid input parameters"; - } else { - mNativeId = deserializeJni(aSerializedData, aKey); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## deserialize() failed " + e.getMessage()); - errorMsg = e.getMessage(); - } - - if (!TextUtils.isEmpty(errorMsg)) { - releaseSession(); - throw new OlmException(OlmException.EXCEPTION_CODE_ACCOUNT_DESERIALIZATION, errorMsg); - } - } - /** - * Allocate a new session and initialize it with the serialisation data.
- * An exception is thrown if the operation fails. - * @param aSerializedData the session serialisation buffer - * @param aKey the key used to encrypt the serialized account data - * @return the deserialized session - **/ - private native long deserializeJni(byte[] aSerializedData, byte[] aKey); -} - diff --git a/android/olm-sdk/src/main/java/org/matrix/olm/OlmUtility.java b/android/olm-sdk/src/main/java/org/matrix/olm/OlmUtility.java deleted file mode 100644 index 250cfb1..0000000 --- a/android/olm-sdk/src/main/java/org/matrix/olm/OlmUtility.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright 2017 OpenMarket Ltd - * Copyright 2017 Vector Creations Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.matrix.olm; - -import android.text.TextUtils; -import android.util.Log; - -import org.json.JSONObject; - -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * Olm SDK helper class. - */ -public class OlmUtility { - private static final String LOG_TAG = "OlmUtility"; - - public static final int RANDOM_KEY_SIZE = 32; - - /** Instance Id returned by JNI. - * This value uniquely identifies this utility instance. - **/ - private long mNativeId; - - public OlmUtility() throws OlmException { - initUtility(); - } - - /** - * Create a native utility instance. - * To be called before any other API call. - * @exception OlmException the exception - */ - private void initUtility() throws OlmException { - try { - mNativeId = createUtilityJni(); - } catch (Exception e) { - throw new OlmException(OlmException.EXCEPTION_CODE_UTILITY_CREATION, e.getMessage()); - } - } - - private native long createUtilityJni(); - - /** - * Release native instance.
- * Public API for {@link #releaseUtilityJni()}. - */ - public void releaseUtility() { - if (0 != mNativeId) { - releaseUtilityJni(); - } - mNativeId = 0; - } - private native void releaseUtilityJni(); - - /** - * Verify an ed25519 signature.
- * An exception is thrown if the operation fails. - * @param aSignature the base64-encoded message signature to be checked. - * @param aFingerprintKey the ed25519 key (fingerprint key) - * @param aMessage the signed message - * @exception OlmException the failure reason - */ - public void verifyEd25519Signature(String aSignature, String aFingerprintKey, String aMessage) throws OlmException { - String errorMessage; - byte[] messageBuffer = null; - - try { - if (TextUtils.isEmpty(aSignature) || TextUtils.isEmpty(aFingerprintKey) || TextUtils.isEmpty(aMessage)) { - Log.e(LOG_TAG, "## verifyEd25519Signature(): invalid input parameters"); - errorMessage = "JAVA sanity check failure - invalid input parameters"; - } else { - messageBuffer = aMessage.getBytes("UTF-8"); - errorMessage = verifyEd25519SignatureJni(aSignature.getBytes("UTF-8"), aFingerprintKey.getBytes("UTF-8"), messageBuffer); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## verifyEd25519Signature(): failed " + e.getMessage()); - errorMessage = e.getMessage(); - } finally { - if (messageBuffer != null) { - Arrays.fill(messageBuffer, (byte) 0); - } - } - - if (!TextUtils.isEmpty(errorMessage)) { - throw new OlmException(OlmException.EXCEPTION_CODE_UTILITY_VERIFY_SIGNATURE, errorMessage); - } - } - - /** - * Verify an ed25519 signature. - * Return a human readable error message in case of verification failure. - * @param aSignature the base64-encoded message signature to be checked. - * @param aFingerprintKey the ed25519 key - * @param aMessage the signed message - * @return null if validation succeed, the error message string if operation failed - */ - private native String verifyEd25519SignatureJni(byte[] aSignature, byte[] aFingerprintKey, byte[] aMessage); - - /** - * Compute the hash(SHA-256) value of the string given in parameter(aMessageToHash).
- * The hash value is the returned by the method. - * @param aMessageToHash message to be hashed - * @return hash value if operation succeed, null otherwise - */ - public String sha256(String aMessageToHash) { - String hashRetValue = null; - - if (null != aMessageToHash) { - byte[] messageBuffer = null; - try { - messageBuffer = aMessageToHash.getBytes("UTF-8"); - hashRetValue = new String(sha256Jni(messageBuffer), "UTF-8"); - } catch (Exception e) { - Log.e(LOG_TAG, "## sha256(): failed " + e.getMessage()); - } finally { - if (null != messageBuffer) { - Arrays.fill(messageBuffer, (byte) 0); - } - } - } - - return hashRetValue; - } - - /** - * Compute the digest (SHA 256) for the message passed in parameter.
- * The digest value is the function return value. - * An exception is thrown if the operation fails. - * @param aMessage the message - * @return digest of the message. - **/ - private native byte[] sha256Jni(byte[] aMessage); - - /** - * Helper method to compute a string based on random integers. - * @return bytes buffer containing randoms integer values - */ - public static byte[] getRandomKey() { - SecureRandom secureRandom = new SecureRandom(); - byte[] buffer = new byte[RANDOM_KEY_SIZE]; - secureRandom.nextBytes(buffer); - - // the key is saved as string - // so avoid the UTF8 marker bytes - for(int i = 0; i < RANDOM_KEY_SIZE; i++) { - buffer[i] = (byte)(buffer[i] & 0x7F); - } - return buffer; - } - - /** - * Return true the object resources have been released.
- * @return true the object resources have been released - */ - public boolean isReleased() { - return (0 == mNativeId); - } - - /** - * Build a string-string dictionary from a jsonObject.
- * @param jsonObject the object to parse - * @return the map - */ - public static Map toStringMap(JSONObject jsonObject) { - if (null != jsonObject) { - HashMap map = new HashMap<>(); - Iterator keysItr = jsonObject.keys(); - while(keysItr.hasNext()) { - String key = keysItr.next(); - try { - Object value = jsonObject.get(key); - - if (value instanceof String) { - map.put(key, (String) value); - } else { - Log.e(LOG_TAG, "## toStringMap(): unexpected type " + value.getClass()); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## toStringMap(): failed " + e.getMessage()); - } - } - - return map; - } - - return null; - } - - /** - * Build a string-string dictionary of string dictionary from a jsonObject.
- * @param jsonObject the object to parse - * @return the map - */ - public static Map> toStringMapMap(JSONObject jsonObject) { - if (null != jsonObject) { - HashMap> map = new HashMap<>(); - - Iterator keysItr = jsonObject.keys(); - while(keysItr.hasNext()) { - String key = keysItr.next(); - try { - Object value = jsonObject.get(key); - - if (value instanceof JSONObject) { - map.put(key, toStringMap((JSONObject) value)); - } else { - Log.e(LOG_TAG, "## toStringMapMap(): unexpected type " + value.getClass()); - } - } catch (Exception e) { - Log.e(LOG_TAG, "## toStringMapMap(): failed " + e.getMessage()); - } - } - - return map; - } - - return null; - } -} - -- cgit v1.2.3