aboutsummaryrefslogtreecommitdiff
path: root/android/olm-sdk/src/main/jni
diff options
context:
space:
mode:
Diffstat (limited to 'android/olm-sdk/src/main/jni')
-rw-r--r--android/olm-sdk/src/main/jni/Android.mk59
-rw-r--r--android/olm-sdk/src/main/jni/Application.mk3
-rw-r--r--android/olm-sdk/src/main/jni/olm_account.cpp687
-rw-r--r--android/olm-sdk/src/main/jni/olm_account.h56
-rw-r--r--android/olm-sdk/src/main/jni/olm_inbound_group_session.cpp507
-rw-r--r--android/olm-sdk/src/main/jni/olm_inbound_group_session.h46
-rw-r--r--android/olm-sdk/src/main/jni/olm_jni.h78
-rw-r--r--android/olm-sdk/src/main/jni/olm_jni_helper.cpp214
-rw-r--r--android/olm-sdk/src/main/jni/olm_jni_helper.h28
-rw-r--r--android/olm-sdk/src/main/jni/olm_manager.cpp35
-rw-r--r--android/olm-sdk/src/main/jni/olm_manager.h36
-rw-r--r--android/olm-sdk/src/main/jni/olm_outbound_group_session.cpp550
-rw-r--r--android/olm-sdk/src/main/jni/olm_outbound_group_session.h49
-rw-r--r--android/olm-sdk/src/main/jni/olm_session.cpp961
-rw-r--r--android/olm-sdk/src/main/jni/olm_session.h59
-rw-r--r--android/olm-sdk/src/main/jni/olm_utility.cpp228
-rw-r--r--android/olm-sdk/src/main/jni/olm_utility.h40
17 files changed, 3636 insertions, 0 deletions
diff --git a/android/olm-sdk/src/main/jni/Android.mk b/android/olm-sdk/src/main/jni/Android.mk
new file mode 100644
index 0000000..97d747c
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/Android.mk
@@ -0,0 +1,59 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := olm
+MAJOR := 2
+MINOR := 0
+PATCH := 0
+OLM_VERSION := $(MAJOR).$(MINOR).$(PATCH)
+SRC_ROOT_DIR := ../../../../..
+
+$(info LOCAL_PATH=$(LOCAL_PATH))
+$(info SRC_ROOT_DIR=$(SRC_ROOT_DIR))
+$(info OLM_VERSION=$(OLM_VERSION))
+
+LOCAL_CPPFLAGS+= -std=c++11 -Wall
+LOCAL_CONLYFLAGS+= -std=c99
+LOCAL_CFLAGS+= -DOLMLIB_VERSION_MAJOR=$(MAJOR) \
+-DOLMLIB_VERSION_MINOR=$(MINOR) \
+-DOLMLIB_VERSION_PATCH=$(PATCH)
+
+#LOCAL_CFLAGS+= -DNDK_DEBUG
+
+LOCAL_C_INCLUDES+= $(LOCAL_PATH)/$(SRC_ROOT_DIR)/include/ \
+$(LOCAL_PATH)/$(SRC_ROOT_DIR)/lib
+
+$(info LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES))
+
+LOCAL_SRC_FILES := $(SRC_ROOT_DIR)/src/account.cpp \
+$(SRC_ROOT_DIR)/src/base64.cpp \
+$(SRC_ROOT_DIR)/src/cipher.cpp \
+$(SRC_ROOT_DIR)/src/crypto.cpp \
+$(SRC_ROOT_DIR)/src/memory.cpp \
+$(SRC_ROOT_DIR)/src/message.cpp \
+$(SRC_ROOT_DIR)/src/olm.cpp \
+$(SRC_ROOT_DIR)/src/pickle.cpp \
+$(SRC_ROOT_DIR)/src/ratchet.cpp \
+$(SRC_ROOT_DIR)/src/session.cpp \
+$(SRC_ROOT_DIR)/src/utility.cpp \
+$(SRC_ROOT_DIR)/src/ed25519.c \
+$(SRC_ROOT_DIR)/src/error.c \
+$(SRC_ROOT_DIR)/src/inbound_group_session.c \
+$(SRC_ROOT_DIR)/src/megolm.c \
+$(SRC_ROOT_DIR)/src/outbound_group_session.c \
+$(SRC_ROOT_DIR)/src/pickle_encoding.c \
+$(SRC_ROOT_DIR)/lib/crypto-algorithms/sha256.c \
+$(SRC_ROOT_DIR)/lib/crypto-algorithms/aes.c \
+$(SRC_ROOT_DIR)/lib/curve25519-donna/curve25519-donna.c \
+olm_account.cpp \
+olm_session.cpp \
+olm_jni_helper.cpp \
+olm_inbound_group_session.cpp \
+olm_outbound_group_session.cpp \
+olm_utility.cpp \
+olm_manager.cpp
+
+LOCAL_LDLIBS := -llog
+
+include $(BUILD_SHARED_LIBRARY)
+
diff --git a/android/olm-sdk/src/main/jni/Application.mk b/android/olm-sdk/src/main/jni/Application.mk
new file mode 100644
index 0000000..6516f5e
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/Application.mk
@@ -0,0 +1,3 @@
+APP_PLATFORM := android-16
+APP_ABI := arm64-v8a armeabi-v7a armeabi x86_64 x86
+APP_STL := gnustl_static \ No newline at end of file
diff --git a/android/olm-sdk/src/main/jni/olm_account.cpp b/android/olm-sdk/src/main/jni/olm_account.cpp
new file mode 100644
index 0000000..40081ac
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_account.cpp
@@ -0,0 +1,687 @@
+/*
+ * 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.
+ */
+
+#include "olm_account.h"
+
+using namespace AndroidOlmSdk;
+
+/**
+ * Init memory allocation for account creation.
+ * @return valid memory allocation, NULL otherwise
+ **/
+OlmAccount* initializeAccountMemory()
+{
+ size_t accountSize = olm_account_size();
+ OlmAccount* accountPtr = (OlmAccount*)malloc(accountSize);
+
+ if (accountPtr)
+ {
+ // init account object
+ accountPtr = olm_account(accountPtr);
+ LOGD("## initializeAccountMemory(): success - OLM account size=%lu",static_cast<long unsigned int>(accountSize));
+ }
+ else
+ {
+ LOGE("## initializeAccountMemory(): failure - OOM");
+ }
+
+ return accountPtr;
+}
+
+/**
+ * Create a new account and return it to JAVA side.<br>
+ * Since a C prt is returned as a jlong, special care will be taken
+ * to make the cast (OlmAccount* => jlong) platform independent.
+ * @return the initialized OlmAccount* instance or throw an exception if fails
+ **/
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(createNewAccountJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ OlmAccount *accountPtr = initializeAccountMemory();
+
+ // init account memory allocation
+ if (!accountPtr)
+ {
+ LOGE("## initNewAccount(): failure - init account OOM");
+ errorMessage = "init account OOM";
+ }
+ else
+ {
+ // get random buffer size
+ size_t randomSize = olm_create_account_random_length(accountPtr);
+
+ LOGD("## initNewAccount(): randomSize=%lu", static_cast<long unsigned int>(randomSize));
+
+ uint8_t *randomBuffPtr = NULL;
+ size_t accountRetCode;
+
+ // allocate random buffer
+ if ((0 != randomSize) && !setRandomInBuffer(env, &randomBuffPtr, randomSize))
+ {
+ LOGE("## initNewAccount(): failure - random buffer init");
+ errorMessage = "random buffer init";
+ }
+ else
+ {
+ // create account
+ accountRetCode = olm_create_account(accountPtr, (void*)randomBuffPtr, randomSize);
+
+ if (accountRetCode == olm_error())
+ {
+ LOGE("## initNewAccount(): failure - account creation failed Msg=%s", olm_account_last_error(accountPtr));
+ errorMessage = olm_account_last_error(accountPtr);
+ }
+
+ LOGD("## initNewAccount(): success - OLM account created");
+ LOGD("## initNewAccount(): success - accountPtr=%p (jlong)(intptr_t)accountPtr=%lld",accountPtr,(jlong)(intptr_t)accountPtr);
+ }
+
+ if (randomBuffPtr)
+ {
+ memset(randomBuffPtr, 0, randomSize);
+ free(randomBuffPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ // release the allocated data
+ if (accountPtr)
+ {
+ olm_clear_account(accountPtr);
+ free(accountPtr);
+ }
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)accountPtr;
+}
+/**
+ * Release the account allocation made by initializeAccountMemory().<br>
+ * This method MUST be called when java counter part account instance is done.
+ */
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(releaseAccountJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## releaseAccountJni(): IN");
+
+ OlmAccount* accountPtr = getAccountInstanceId(env, thiz);
+
+ if (!accountPtr)
+ {
+ LOGE(" ## releaseAccountJni(): failure - invalid Account ptr=NULL");
+ }
+ else
+ {
+ LOGD(" ## releaseAccountJni(): accountPtr=%p",accountPtr);
+ olm_clear_account(accountPtr);
+
+ LOGD(" ## releaseAccountJni(): IN");
+ // even if free(NULL) does not crash, logs are performed for debug purpose
+ free(accountPtr);
+ LOGD(" ## releaseAccountJni(): OUT");
+ }
+}
+
+// *********************************************************************
+// ************************* IDENTITY KEYS API *************************
+// *********************************************************************
+
+/**
+ * Get identity keys: Ed25519 fingerprint key and Curve25519 identity key.<br>
+ * The keys are returned in the byte array.
+ * @return the identity keys or throw an exception if it fails
+ **/
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(identityKeysJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ jbyteArray byteArrayRetValue = NULL;
+ OlmAccount* accountPtr = getAccountInstanceId(env, thiz);
+
+ if (!accountPtr)
+ {
+ LOGE("## identityKeys(): failure - invalid Account ptr=NULL");
+ errorMessage = "invalid Account ptr";
+ }
+ else
+ {
+ LOGD("## identityKeys(): accountPtr =%p", accountPtr);
+
+ // identity keys allocation
+ size_t identityKeysLength = olm_account_identity_keys_length(accountPtr);
+ uint8_t *identityKeysBytesPtr = (uint8_t*)malloc(identityKeysLength);
+
+ if (!identityKeysBytesPtr)
+ {
+ LOGE("## identityKeys(): failure - identity keys array OOM");
+ errorMessage = "identity keys array OOM";
+ }
+ else
+ {
+ // retrieve key pairs in identityKeysBytesPtr
+ size_t keysResult = olm_account_identity_keys(accountPtr, identityKeysBytesPtr, identityKeysLength);
+
+ if (keysResult == olm_error())
+ {
+ errorMessage = (const char *)olm_account_last_error(accountPtr);
+ LOGE("## identityKeys(): failure - error getting identity keys Msg=%s", errorMessage);
+ }
+ else
+ {
+ // allocate the byte array to be returned to java
+ byteArrayRetValue = env->NewByteArray(identityKeysLength);
+
+ if (!byteArrayRetValue)
+ {
+ LOGE("## identityKeys(): failure - return byte array OOM");
+ errorMessage = "byte array OOM";
+ }
+ else
+ {
+ env->SetByteArrayRegion(byteArrayRetValue, 0/*offset*/, identityKeysLength, (const jbyte*)identityKeysBytesPtr);
+ LOGD("## identityKeys(): success - result=%lu", static_cast<long unsigned int>(keysResult));
+ }
+ }
+
+ free(identityKeysBytesPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return byteArrayRetValue;
+}
+
+// *********************************************************************
+// ************************* ONE TIME KEYS API *************************
+// *********************************************************************
+
+/**
+ * Get the public parts of the unpublished "one time keys" for the account.<br>
+ * The returned data is a JSON-formatted object with the single property
+ * <tt>curve25519</tt>, which is itself an object mapping key id to
+ * base64-encoded Curve25519 key.<br>
+ * @return byte array containing the one time keys or throw an exception if it fails
+ */
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(maxOneTimeKeysJni)(JNIEnv *env, jobject thiz)
+{
+ OlmAccount* accountPtr = getAccountInstanceId(env, thiz);
+ size_t maxKeys = -1;
+
+ if (!accountPtr)
+ {
+ LOGE("## maxOneTimeKey(): failure - invalid Account ptr=NULL");
+ }
+ else
+ {
+ maxKeys = olm_account_max_number_of_one_time_keys(accountPtr);
+ }
+
+ LOGD("## maxOneTimeKey(): Max keys=%lu", static_cast<long unsigned int>(maxKeys));
+
+ return (jlong)maxKeys;
+}
+
+/**
+ * Generate "one time keys".
+ * An exception is thrown if the operation fails.
+ * @param aNumberOfKeys number of keys to generate
+ **/
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(generateOneTimeKeysJni)(JNIEnv *env, jobject thiz, jint aNumberOfKeys)
+{
+ const char* errorMessage = NULL;
+ OlmAccount *accountPtr = getAccountInstanceId(env, thiz);
+
+ if (!accountPtr)
+ {
+ LOGE("## generateOneTimeKeysJni(): failure - invalid Account ptr");
+ errorMessage = "invalid Account ptr";
+ }
+ else
+ {
+ // keys memory allocation
+ size_t randomLength = olm_account_generate_one_time_keys_random_length(accountPtr, (size_t)aNumberOfKeys);
+ LOGD("## generateOneTimeKeysJni(): randomLength=%lu", static_cast<long unsigned int>(randomLength));
+
+ uint8_t *randomBufferPtr = NULL;
+
+ if ((0 != randomLength) && !setRandomInBuffer(env, &randomBufferPtr, randomLength))
+ {
+ LOGE("## generateOneTimeKeysJni(): failure - random buffer init");
+ errorMessage = "random buffer init";
+ }
+ else
+ {
+ LOGD("## generateOneTimeKeysJni(): accountPtr =%p aNumberOfKeys=%d",accountPtr, aNumberOfKeys);
+
+ // retrieve key pairs in keysBytesPtr
+ size_t result = olm_account_generate_one_time_keys(accountPtr, (size_t)aNumberOfKeys, (void*)randomBufferPtr, randomLength);
+
+ if (result == olm_error())
+ {
+ errorMessage = olm_account_last_error(accountPtr);
+ LOGE("## generateOneTimeKeysJni(): failure - error generating one time keys Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## generateOneTimeKeysJni(): success - result=%lu", static_cast<long unsigned int>(result));
+ }
+ }
+
+
+ if (randomBufferPtr)
+ {
+ memset(randomBufferPtr, 0, randomLength);
+ free(randomBufferPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+/**
+ * Get "one time keys".<br>
+ * Return the public parts of the unpublished "one time keys" for the account
+ * @return a valid byte array if operation succeed, null otherwise
+ **/
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(oneTimeKeysJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ jbyteArray byteArrayRetValue = NULL;
+ OlmAccount* accountPtr = getAccountInstanceId(env, thiz);
+
+ LOGD("## oneTimeKeysJni(): IN");
+
+ if (!accountPtr)
+ {
+ LOGE("## oneTimeKeysJni(): failure - invalid Account ptr");
+ errorMessage = "invalid Account ptr";
+ }
+ else
+ {
+ // keys memory allocation
+ size_t keysLength = olm_account_one_time_keys_length(accountPtr);
+ uint8_t *keysBytesPtr = (uint8_t *)malloc(keysLength*sizeof(uint8_t));
+
+ if (!keysBytesPtr)
+ {
+ LOGE("## oneTimeKeysJni(): failure - one time keys array OOM");
+ errorMessage = "one time keys array OOM";
+ }
+ else
+ {
+ // retrieve key pairs in keysBytesPtr
+ size_t keysResult = olm_account_one_time_keys(accountPtr, keysBytesPtr, keysLength);
+
+ if (keysResult == olm_error()) {
+ LOGE("## oneTimeKeysJni(): failure - error getting one time keys Msg=%s",(const char *)olm_account_last_error(accountPtr));
+ errorMessage = (const char *)olm_account_last_error(accountPtr);
+ }
+ else
+ {
+ // allocate the byte array to be returned to java
+ byteArrayRetValue = env->NewByteArray(keysLength);
+
+ if (!byteArrayRetValue)
+ {
+ LOGE("## oneTimeKeysJni(): failure - return byte array OOM");
+ errorMessage = "return byte array OOM";
+ }
+ else
+ {
+ env->SetByteArrayRegion(byteArrayRetValue, 0/*offset*/, keysLength, (const jbyte*)keysBytesPtr);
+ LOGD("## oneTimeKeysJni(): success");
+ }
+ }
+
+ free(keysBytesPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return byteArrayRetValue;
+}
+
+/**
+ * Remove the "one time keys" that the session used from the account.
+ * An exception is thrown if the operation fails.
+ * @param aNativeOlmSessionId session instance
+ **/
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(removeOneTimeKeysJni)(JNIEnv *env, jobject thiz, jlong aNativeOlmSessionId)
+{
+ const char* errorMessage = NULL;
+ OlmAccount* accountPtr = NULL;
+ OlmSession* sessionPtr = (OlmSession*)aNativeOlmSessionId;
+
+ if (!sessionPtr)
+ {
+ LOGE("## removeOneTimeKeysJni(): failure - invalid session ptr");
+ errorMessage = "invalid session ptr";
+ }
+ else if (!(accountPtr = getAccountInstanceId(env, thiz)))
+ {
+ LOGE("## removeOneTimeKeysJni(): failure - invalid account ptr");
+ errorMessage = "invalid account ptr";
+ }
+ else
+ {
+ size_t result = olm_remove_one_time_keys(accountPtr, sessionPtr);
+
+ if (result == olm_error())
+ { // the account doesn't have any matching "one time keys"..
+ LOGW("## removeOneTimeKeysJni(): failure - removing one time keys Msg=%s", olm_account_last_error(accountPtr));
+ errorMessage = (const char *)olm_account_last_error(accountPtr);
+ }
+ else
+ {
+ LOGD("## removeOneTimeKeysJni(): success");
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+/**
+ * Mark the current set of "one time keys" as being published.
+ * An exception is thrown if the operation fails.
+ **/
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(markOneTimeKeysAsPublishedJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ OlmAccount* accountPtr = getAccountInstanceId(env, thiz);
+
+ if (!accountPtr)
+ {
+ LOGE("## markOneTimeKeysAsPublishedJni(): failure - invalid account ptr");
+ errorMessage = "invalid account ptr";
+ }
+ else
+ {
+ size_t result = olm_account_mark_keys_as_published(accountPtr);
+
+ if (result == olm_error())
+ {
+ LOGW("## markOneTimeKeysAsPublishedJni(): failure - Msg=%s",(const char *)olm_account_last_error(accountPtr));
+ errorMessage = (const char *)olm_account_last_error(accountPtr);
+ }
+ else
+ {
+ LOGD("## markOneTimeKeysAsPublishedJni(): success - retCode=%lu",static_cast<long unsigned int>(result));
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+/**
+ * Sign a message with the ed25519 key (fingerprint) for this account.<br>
+ * The signed message is returned by the function.
+ * @param aMessage message to sign
+ * @return the signed message, null otherwise
+ **/
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(signMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aMessage)
+{
+ const char* errorMessage = NULL;
+ OlmAccount* accountPtr = NULL;
+ jbyteArray signedMsgRetValueBuffer = NULL;
+
+ if (!aMessage)
+ {
+ LOGE("## signMessageJni(): failure - invalid aMessage param");
+ errorMessage = "invalid aMessage param";
+ }
+ else if (!(accountPtr = getAccountInstanceId(env, thiz)))
+ {
+ LOGE("## signMessageJni(): failure - invalid account ptr");
+ errorMessage = "invalid account ptr";
+ }
+ else
+ {
+ int messageLength = env->GetArrayLength(aMessage);
+ jbyte* messageToSign = env->GetByteArrayElements(aMessage, NULL);
+
+ // signature memory allocation
+ size_t signatureLength = olm_account_signature_length(accountPtr);
+ void* signedMsgPtr = malloc(signatureLength * sizeof(uint8_t));
+
+ if (!signedMsgPtr)
+ {
+ LOGE("## signMessageJni(): failure - signature allocation OOM");
+ errorMessage = "signature allocation OOM";
+ }
+ else
+ {
+ // sign message
+ size_t resultSign = olm_account_sign(accountPtr,
+ (void*)messageToSign,
+ (size_t)messageLength,
+ signedMsgPtr,
+ signatureLength);
+
+ if (resultSign == olm_error())
+ {
+ LOGE("## signMessageJni(): failure - error signing message Msg=%s",(const char *)olm_account_last_error(accountPtr));
+ errorMessage = (const char *)olm_account_last_error(accountPtr);
+ }
+ else
+ {
+ LOGD("## signMessageJni(): success - retCode=%lu signatureLength=%lu", static_cast<long unsigned int>(resultSign), static_cast<long unsigned int>(signatureLength));
+
+ signedMsgRetValueBuffer = env->NewByteArray(signatureLength);
+ env->SetByteArrayRegion(signedMsgRetValueBuffer, 0 , signatureLength, (jbyte*)signedMsgPtr);
+ }
+
+ free(signedMsgPtr);
+ }
+
+ // release messageToSign
+ if (messageToSign)
+ {
+ env->ReleaseByteArrayElements(aMessage, messageToSign, JNI_ABORT);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return signedMsgRetValueBuffer;
+}
+
+/**
+ * Serialize and encrypt account instance.<br>
+ * @param aKeyBuffer key used to encrypt the serialized account data
+ * @return the serialised account as bytes buffer.
+ **/
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ jbyteArray pickledDataRetValue = 0;
+ jbyte* keyPtr = NULL;
+ OlmAccount* accountPtr = NULL;
+
+ LOGD("## serializeJni(): IN");
+
+ if (!aKeyBuffer)
+ {
+ LOGE(" ## serializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!(accountPtr = getAccountInstanceId(env, thiz)))
+ {
+ LOGE(" ## serializeJni(): failure - invalid account ptr");
+ errorMessage = "invalid account ptr";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, NULL)))
+ {
+ LOGE(" ## serializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = olm_pickle_account_length(accountPtr);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## serializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+
+ void* pickledPtr = malloc(pickledLength * sizeof(uint8_t));
+
+ if (!pickledPtr)
+ {
+ LOGE(" ## serializeJni(): failure - pickledPtr buffer OOM");
+ errorMessage = "pickledPtr buffer OOM";
+ }
+ else
+ {
+ size_t result = olm_pickle_account(accountPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_account_last_error(accountPtr);
+ LOGE(" ## serializeJni(): failure - olm_pickle_account() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## serializeJni(): success - result=%lu pickled=%.*s", static_cast<long unsigned int>(result), static_cast<int>(pickledLength), static_cast<char*>(pickledPtr));
+ pickledDataRetValue = env->NewByteArray(pickledLength);
+ env->SetByteArrayRegion(pickledDataRetValue, 0 , pickledLength, (jbyte*)pickledPtr);
+ }
+
+ free(pickledPtr);
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return pickledDataRetValue;
+}
+
+/**
+ * Allocate a new account and initialise it with the serialisation data.<br>
+ * @param aSerializedDataBuffer the account serialisation buffer
+ * @param aKeyBuffer the key used to encrypt the serialized account data
+ * @return the deserialised account
+ **/
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+
+ OlmAccount* accountPtr = NULL;
+
+ jbyte* keyPtr = NULL;
+ jbyte* pickledPtr = NULL;
+
+ LOGD("## deserializeJni(): IN");
+
+ if (!aKeyBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!aSerializedDataBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - invalid serialized data");
+ errorMessage = "invalid serialized data";
+ }
+ else if (!(accountPtr = initializeAccountMemory()))
+ {
+ LOGE(" ## deserializeJni(): failure - account failure OOM");
+ errorMessage = "account failure OOM";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else if (!(pickledPtr = env->GetByteArrayElements(aSerializedDataBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - pickledPtr JNI allocation OOM");
+ errorMessage = "pickledPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = (size_t)env->GetArrayLength(aSerializedDataBuffer);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## deserializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+ LOGD(" ## deserializeJni(): pickled=%.*s", static_cast<int> (pickledLength), (char const *)pickledPtr);
+
+ size_t result = olm_unpickle_account(accountPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_account_last_error(accountPtr);
+ LOGE(" ## deserializeJni(): failure - olm_unpickle_account() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## deserializeJni(): success - result=%lu ", static_cast<long unsigned int>(result));
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (pickledPtr)
+ {
+ env->ReleaseByteArrayElements(aSerializedDataBuffer, pickledPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ if (accountPtr)
+ {
+ olm_clear_account(accountPtr);
+ free(accountPtr);
+ }
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)accountPtr;
+} \ No newline at end of file
diff --git a/android/olm-sdk/src/main/jni/olm_account.h b/android/olm-sdk/src/main/jni/olm_account.h
new file mode 100644
index 0000000..42b2c2a
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_account.h
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLACCOUNT_H
+#define _OMLACCOUNT_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+
+#define OLM_ACCOUNT_FUNC_DEF(func_name) FUNC_DEF(OlmAccount,func_name)
+#define OLM_MANAGER_FUNC_DEF(func_name) FUNC_DEF(OlmManager,func_name)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// account creation/destruction
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(releaseAccountJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(createNewAccountJni)(JNIEnv *env, jobject thiz);
+
+// identity keys
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(identityKeysJni)(JNIEnv *env, jobject thiz);
+
+// one time keys
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(oneTimeKeysJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(maxOneTimeKeysJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(generateOneTimeKeysJni)(JNIEnv *env, jobject thiz, jint aNumberOfKeys);
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(removeOneTimeKeysJni)(JNIEnv *env, jobject thiz, jlong aNativeOlmSessionId);
+JNIEXPORT void OLM_ACCOUNT_FUNC_DEF(markOneTimeKeysAsPublishedJni)(JNIEnv *env, jobject thiz);
+
+// signing
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(signMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aMessage);
+
+// serialization
+JNIEXPORT jbyteArray OLM_ACCOUNT_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer);
+JNIEXPORT jlong OLM_ACCOUNT_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_inbound_group_session.cpp b/android/olm-sdk/src/main/jni/olm_inbound_group_session.cpp
new file mode 100644
index 0000000..23910bb
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_inbound_group_session.cpp
@@ -0,0 +1,507 @@
+/*
+ * 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.
+ */
+
+#include "olm_inbound_group_session.h"
+
+using namespace AndroidOlmSdk;
+
+/**
+ * Release the session allocation made by initializeInboundGroupSessionMemory().<br>
+ * This method MUST be called when java counter part account instance is done.
+ */
+JNIEXPORT void OLM_INBOUND_GROUP_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz)
+{
+ OlmInboundGroupSession* sessionPtr = getInboundGroupSessionInstanceId(env,thiz);
+
+ LOGD("## releaseSessionJni(): InBound group session IN");
+
+ if (!sessionPtr)
+ {
+ LOGE("## releaseSessionJni(): failure - invalid inbound group session instance");
+ }
+ else
+ {
+ LOGD(" ## releaseSessionJni(): sessionPtr=%p", sessionPtr);
+#ifdef ENABLE_JNI_LOG
+ size_t retCode = olm_clear_inbound_group_session(sessionPtr);
+ LOGD(" ## releaseSessionJni(): clear_inbound_group_session=%lu",static_cast<long unsigned int>(retCode));
+#else
+ olm_clear_inbound_group_session(sessionPtr);
+#endif
+
+ LOGD(" ## releaseSessionJni(): free IN");
+ free(sessionPtr);
+ LOGD(" ## releaseSessionJni(): free OUT");
+ }
+}
+
+/**
+ * Initialize a new inbound group session and return it to JAVA side.<br>
+ * Since a C prt is returned as a jlong, special care will be taken
+ * to make the cast (OlmInboundGroupSession* => jlong) platform independent.
+ * @param aSessionKeyBuffer session key from an outbound session
+ * @return the initialized OlmInboundGroupSession* instance or throw an exception it fails.
+ **/
+JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz, jbyteArray aSessionKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ OlmInboundGroupSession* sessionPtr = NULL;
+ jbyte* sessionKeyPtr = NULL;
+ size_t sessionSize = olm_inbound_group_session_size();
+
+ LOGD("## createNewSessionJni(): inbound group session IN");
+
+ if (!sessionSize)
+ {
+ LOGE(" ## createNewSessionJni(): failure - inbound group session size = 0");
+ errorMessage = "inbound group session size = 0";
+ }
+ else if (!(sessionPtr = (OlmInboundGroupSession*)malloc(sessionSize)))
+ {
+ LOGE(" ## createNewSessionJni(): failure - inbound group session OOM");
+ errorMessage = "inbound group session OOM";
+ }
+ else if (!aSessionKeyBuffer)
+ {
+ LOGE(" ## createNewSessionJni(): failure - invalid aSessionKey");
+ errorMessage = "invalid aSessionKey";
+ }
+ else if (!(sessionKeyPtr = env->GetByteArrayElements(aSessionKeyBuffer, 0)))
+ {
+ LOGE(" ## createNewSessionJni(): failure - session key JNI allocation OOM");
+ errorMessage = "Session key JNI allocation OOM";
+ }
+ else
+ {
+ sessionPtr = olm_inbound_group_session(sessionPtr);
+
+ size_t sessionKeyLength = (size_t)env->GetArrayLength(aSessionKeyBuffer);
+ LOGD(" ## createNewSessionJni(): sessionKeyLength=%lu", static_cast<long unsigned int>(sessionKeyLength));
+
+ size_t sessionResult = olm_init_inbound_group_session(sessionPtr, (const uint8_t*)sessionKeyPtr, sessionKeyLength);
+
+ if (sessionResult == olm_error())
+ {
+ errorMessage = olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## createNewSessionJni(): failure - init inbound session creation Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## createNewSessionJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
+ }
+ }
+
+ if (sessionKeyPtr)
+ {
+ env->ReleaseByteArrayElements(aSessionKeyBuffer, sessionKeyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ if (errorMessage)
+ {
+ // release the allocated session
+ if (sessionPtr)
+ {
+ olm_clear_inbound_group_session(sessionPtr);
+ free(sessionPtr);
+ }
+
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)sessionPtr;
+}
+
+/**
+ * Get a base64-encoded identifier for this inbound group session.
+ * An exception is thrown if the operation fails.
+ * @return the base64-encoded identifier
+ */
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ OlmInboundGroupSession *sessionPtr = getInboundGroupSessionInstanceId(env, thiz);
+ jbyteArray returnValue = 0;
+
+ LOGD("## sessionIdentifierJni(): inbound group session IN");
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## sessionIdentifierJni(): failure - invalid inbound group session instance");
+ errorMessage = "invalid inbound group session instance";
+ }
+ else
+ {
+ // get the size to alloc
+ size_t lengthSessionId = olm_inbound_group_session_id_length(sessionPtr);
+ LOGD(" ## sessionIdentifierJni(): inbound group session lengthSessionId=%lu",static_cast<long unsigned int>(lengthSessionId));
+
+ uint8_t *sessionIdPtr = (uint8_t*)malloc(lengthSessionId*sizeof(uint8_t));
+
+ if (!sessionIdPtr)
+ {
+ LOGE(" ## sessionIdentifierJni(): failure - inbound group session identifier allocation OOM");
+ errorMessage = "inbound group session identifier allocation OOM";
+ }
+ else
+ {
+ size_t result = olm_inbound_group_session_id(sessionPtr, sessionIdPtr, lengthSessionId);
+
+ if (result == olm_error())
+ {
+ errorMessage = (const char *)olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## sessionIdentifierJni(): failure - get inbound group session identifier failure Msg=%s",(const char *)olm_inbound_group_session_last_error(sessionPtr));
+ }
+ else
+ {
+ LOGD(" ## sessionIdentifierJni(): success - inbound group session result=%lu sessionId=%.*s",static_cast<long unsigned int>(result), static_cast<int>(result), (char*)sessionIdPtr);
+
+ returnValue = env->NewByteArray(result);
+ env->SetByteArrayRegion(returnValue, 0 , result, (jbyte*)sessionIdPtr);
+ }
+
+ free(sessionIdPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+/**
+ * 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
+ */
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aEncryptedMsgBuffer, jobject aDecryptionResult)
+{
+ jbyteArray decryptedMsgBuffer = 0;
+ const char* errorMessage = NULL;
+
+ OlmInboundGroupSession *sessionPtr = getInboundGroupSessionInstanceId(env, thiz);
+ jbyte *encryptedMsgPtr = NULL;
+ jclass indexObjJClass = 0;
+ jfieldID indexMsgFieldId;
+
+ LOGD("## decryptMessageJni(): inbound group session IN");
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## decryptMessageJni(): failure - invalid inbound group session ptr=NULL");
+ errorMessage = "invalid inbound group session ptr=NULL";
+ }
+ else if (!aEncryptedMsgBuffer)
+ {
+ LOGE(" ## decryptMessageJni(): failure - invalid encrypted message");
+ errorMessage = "invalid encrypted message";
+ }
+ else if (!aDecryptionResult)
+ {
+ LOGE(" ## decryptMessageJni(): failure - invalid index object");
+ errorMessage = "invalid index object";
+ }
+ else if (!(encryptedMsgPtr = env->GetByteArrayElements(aEncryptedMsgBuffer, 0)))
+ {
+ LOGE(" ## decryptMessageJni(): failure - encrypted message JNI allocation OOM");
+ errorMessage = "encrypted message JNI allocation OOM";
+ }
+ else if (!(indexObjJClass = env->GetObjectClass(aDecryptionResult)))
+ {
+ LOGE("## decryptMessageJni(): failure - unable to get index class");
+ errorMessage = "unable to get index class";
+ }
+ else if (!(indexMsgFieldId = env->GetFieldID(indexObjJClass,"mIndex","J")))
+ {
+ LOGE("## decryptMessageJni(): failure - unable to get index type field");
+ errorMessage = "unable to get index type field";
+ }
+ else
+ {
+ // get encrypted message length
+ size_t encryptedMsgLength = (size_t)env->GetArrayLength(aEncryptedMsgBuffer);
+ uint8_t *tempEncryptedPtr = static_cast<uint8_t*>(malloc(encryptedMsgLength*sizeof(uint8_t)));
+
+ // create a dedicated temp buffer to be used in next Olm API calls
+ if (!tempEncryptedPtr)
+ {
+ LOGE(" ## decryptMessageJni(): failure - tempEncryptedPtr allocation OOM");
+ errorMessage = "tempEncryptedPtr allocation OOM";
+ }
+ else
+ {
+ memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
+ LOGD(" ## decryptMessageJni(): encryptedMsgLength=%lu encryptedMsg=%.*s",static_cast<long unsigned int>(encryptedMsgLength), static_cast<int>(encryptedMsgLength), encryptedMsgPtr);
+
+ // get max plaintext length
+ size_t maxPlainTextLength = olm_group_decrypt_max_plaintext_length(sessionPtr,
+ tempEncryptedPtr,
+ encryptedMsgLength);
+ if (maxPlainTextLength == olm_error())
+ {
+ errorMessage = olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt_max_plaintext_length Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## decryptMessageJni(): maxPlaintextLength=%lu",static_cast<long unsigned int>(maxPlainTextLength));
+
+ uint32_t messageIndex = 0;
+
+ // allocate output decrypted message
+ uint8_t *plainTextMsgPtr = static_cast<uint8_t*>(malloc(maxPlainTextLength*sizeof(uint8_t)));
+
+ // decrypt, but before reload encrypted buffer (previous one was destroyed)
+ memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
+ size_t plaintextLength = olm_group_decrypt(sessionPtr,
+ tempEncryptedPtr,
+ encryptedMsgLength,
+ plainTextMsgPtr,
+ maxPlainTextLength,
+ &messageIndex);
+ if (plaintextLength == olm_error())
+ {
+ errorMessage = olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## decryptMessageJni(): failure - olm_group_decrypt Msg=%s", errorMessage);
+ }
+ else
+ {
+ // update index
+ env->SetLongField(aDecryptionResult, indexMsgFieldId, (jlong)messageIndex);
+
+ decryptedMsgBuffer = env->NewByteArray(plaintextLength);
+ env->SetByteArrayRegion(decryptedMsgBuffer, 0 , plaintextLength, (jbyte*)plainTextMsgPtr);
+
+ LOGD(" ## decryptMessageJni(): UTF-8 Conversion - decrypted returnedLg=%lu OK",static_cast<long unsigned int>(plaintextLength));
+ }
+
+ if (plainTextMsgPtr)
+ {
+ memset(plainTextMsgPtr, 0, maxPlainTextLength*sizeof(uint8_t));
+ free(plainTextMsgPtr);
+ }
+ }
+
+ if (tempEncryptedPtr)
+ {
+ free(tempEncryptedPtr);
+ }
+ }
+ }
+
+ // free alloc
+ if (encryptedMsgPtr)
+ {
+ env->ReleaseByteArrayElements(aEncryptedMsgBuffer, encryptedMsgPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return decryptedMsgBuffer;
+}
+
+
+/**
+ * Serialize and encrypt session instance into a base64 string.<br>
+ * An exception is thrown if the operation fails.
+ * @param aKeyBuffer key used to encrypt the serialized session data
+ * @return a base64 string if operation succeed, null otherwise
+ **/
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+
+ jbyteArray pickledDataRet = 0;
+ jbyte* keyPtr = NULL;
+ OlmInboundGroupSession* sessionPtr = getInboundGroupSessionInstanceId(env, thiz);
+
+ LOGD("## inbound group session serializeJni(): IN");
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## serializeJni(): failure - invalid session ptr");
+ errorMessage = "invalid session ptr";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## serializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## serializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = olm_pickle_inbound_group_session_length(sessionPtr);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## serializeJni(): pickledLength=%lu keyLength=%lu", static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+
+ void *pickledPtr = malloc(pickledLength*sizeof(uint8_t));
+
+ if (!pickledPtr)
+ {
+ LOGE(" ## serializeJni(): failure - pickledPtr buffer OOM");
+ errorMessage = "pickledPtr buffer OOM";
+ }
+ else
+ {
+ size_t result = olm_pickle_inbound_group_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## serializeJni(): failure - olm_pickle_outbound_group_session() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## serializeJni(): success - result=%lu pickled=%.*s", static_cast<long unsigned int>(result), static_cast<int>(pickledLength), static_cast<char*>(pickledPtr));
+
+ pickledDataRet = env->NewByteArray(pickledLength);
+ env->SetByteArrayRegion(pickledDataRet, 0 , pickledLength, (jbyte*)pickledPtr);
+ }
+
+ free(pickledPtr);
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return pickledDataRet;
+}
+
+/**
+ * Allocate a new session and initialize it with the serialisation data.<br>
+ * 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
+ **/
+JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+
+ OlmInboundGroupSession* sessionPtr = NULL;
+ size_t sessionSize = olm_inbound_group_session_size();
+ jbyte* keyPtr = NULL;
+ jbyte* pickledPtr = NULL;
+
+ LOGD("## deserializeJni(): IN");
+
+ if (!sessionSize)
+ {
+ LOGE(" ## deserializeJni(): failure - inbound group session size = 0");
+ errorMessage = "inbound group session size = 0";
+ }
+ else if (!(sessionPtr = (OlmInboundGroupSession*)malloc(sessionSize)))
+ {
+ LOGE(" ## deserializeJni(): failure - session failure OOM");
+ errorMessage = "session failure OOM";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!aSerializedDataBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - serialized data");
+ errorMessage = "serialized data";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else if (!(pickledPtr = env->GetByteArrayElements(aSerializedDataBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - pickledPtr JNI allocation OOM");
+ errorMessage = "pickledPtr JNI allocation OOM";
+ }
+ else
+ {
+ sessionPtr = olm_inbound_group_session(sessionPtr);
+
+ size_t pickledLength = (size_t)env->GetArrayLength(aSerializedDataBuffer);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## deserializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+ LOGD(" ## deserializeJni(): pickled=%.*s", static_cast<int>(pickledLength), (char const *)pickledPtr);
+
+ size_t result = olm_unpickle_inbound_group_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_inbound_group_session_last_error(sessionPtr);
+ LOGE(" ## deserializeJni(): failure - olm_unpickle_inbound_group_session() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## deserializeJni(): success - result=%lu ", static_cast<long unsigned int>(result));
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (pickledPtr)
+ {
+ env->ReleaseByteArrayElements(aSerializedDataBuffer, pickledPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ if (sessionPtr)
+ {
+ olm_clear_inbound_group_session(sessionPtr);
+ free(sessionPtr);
+ }
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)sessionPtr;
+}
diff --git a/android/olm-sdk/src/main/jni/olm_inbound_group_session.h b/android/olm-sdk/src/main/jni/olm_inbound_group_session.h
new file mode 100644
index 0000000..00990dd
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_inbound_group_session.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLINBOUND_GROUP_SESSION_H
+#define _OMLINBOUND_GROUP_SESSION_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+#include "olm/inbound_group_session.h"
+
+#define OLM_INBOUND_GROUP_SESSION_FUNC_DEF(func_name) FUNC_DEF(OlmInboundGroupSession,func_name)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// session creation/destruction
+JNIEXPORT void OLM_INBOUND_GROUP_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz, jbyteArray aSessionKeyBuffer);
+
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aEncryptedMsg, jobject aDecryptIndex);
+
+// serialization
+JNIEXPORT jbyteArray OLM_INBOUND_GROUP_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKey);
+JNIEXPORT jlong OLM_INBOUND_GROUP_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedData, jbyteArray aKey);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_jni.h b/android/olm-sdk/src/main/jni/olm_jni.h
new file mode 100644
index 0000000..e6a49e2
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_jni.h
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLJNI_H
+#define _OMLJNI_H
+
+#include <cstdlib>
+#include <cstdio>
+#include <string>
+#include <sstream>
+#include <jni.h>
+#include <android/log.h>
+
+
+#define TAG "OlmJniNative"
+
+/* logging macros */
+//#define ENABLE_JNI_LOG
+
+#ifdef NDK_DEBUG
+ #warning NDK_DEBUG is defined!
+#endif
+
+#ifdef ENABLE_JNI_LOG
+ #warning ENABLE_JNI_LOG is defined!
+#endif
+
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
+
+#ifdef ENABLE_JNI_LOG
+ #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
+ #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
+#else
+ #define LOGD(...)
+ #define LOGW(...)
+#endif
+
+#define FUNC_DEF(class_name,func_name) JNICALL Java_org_matrix_olm_##class_name##_##func_name
+
+namespace AndroidOlmSdk
+{
+
+}
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// internal helper functions
+bool setRandomInBuffer(JNIEnv *env, uint8_t **aBuffer2Ptr, size_t aRandomSize);
+
+struct OlmSession* getSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject);
+struct OlmAccount* getAccountInstanceId(JNIEnv* aJniEnv, jobject aJavaObject);
+struct OlmInboundGroupSession* getInboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject);
+struct OlmOutboundGroupSession* getOutboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject);
+struct OlmUtility* getUtilityInstanceId(JNIEnv* aJniEnv, jobject aJavaObject);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_jni_helper.cpp b/android/olm-sdk/src/main/jni/olm_jni_helper.cpp
new file mode 100644
index 0000000..a1f5c59
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_jni_helper.cpp
@@ -0,0 +1,214 @@
+/*
+ * 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.
+ */
+
+#include "olm_jni_helper.h"
+#include "olm/olm.h"
+#include <sys/time.h>
+
+using namespace AndroidOlmSdk;
+
+/**
+* Init a buffer with a given number of random values.
+* @param aBuffer2Ptr the buffer to be initialized
+* @param aRandomSize the number of random values to apply
+* @return true if operation succeed, false otherwise
+**/
+bool setRandomInBuffer(JNIEnv *env, uint8_t **aBuffer2Ptr, size_t aRandomSize)
+{
+ bool retCode = false;
+ int bufferLen = aRandomSize*sizeof(uint8_t);
+
+ if (!aBuffer2Ptr)
+ {
+ LOGE("## setRandomInBuffer(): failure - aBuffer=NULL");
+ }
+ else if (!aRandomSize)
+ {
+ LOGE("## setRandomInBuffer(): failure - random size=0");
+ }
+ else if (!(*aBuffer2Ptr = (uint8_t*)malloc(bufferLen)))
+ {
+ LOGE("## setRandomInBuffer(): failure - alloc mem OOM");
+ }
+ else
+ {
+ LOGD("## setRandomInBuffer(): randomSize=%lu",static_cast<long unsigned int>(aRandomSize));
+
+ // use the secureRandom class
+ jclass cls = env->FindClass("java/security/SecureRandom");
+
+ if (cls)
+ {
+ jobject newObj = 0;
+ jmethodID constructor = env->GetMethodID(cls, "<init>", "()V");
+ jmethodID nextByteMethod = env->GetMethodID(cls, "nextBytes", "([B)V");
+
+ if (constructor)
+ {
+ newObj = env->NewObject(cls, constructor);
+ jbyteArray tempByteArray = env->NewByteArray(bufferLen);
+
+ if (newObj && tempByteArray)
+ {
+ env->CallVoidMethod(newObj, nextByteMethod, tempByteArray);
+
+ if (!env->ExceptionOccurred())
+ {
+ jbyte* buffer = env->GetByteArrayElements(tempByteArray, NULL);
+
+ if (buffer)
+ {
+ memcpy(*aBuffer2Ptr, buffer, bufferLen);
+ retCode = true;
+
+ // clear tempByteArray to hide sensitive data.
+ memset(buffer, 0, bufferLen);
+ env->SetByteArrayRegion(tempByteArray, 0, bufferLen, buffer);
+
+ // ensure that the buffer is released
+ env->ReleaseByteArrayElements(tempByteArray, buffer, JNI_ABORT);
+ }
+ }
+ }
+
+ if (tempByteArray)
+ {
+ env->DeleteLocalRef(tempByteArray);
+ }
+
+ if (newObj)
+ {
+ env->DeleteLocalRef(newObj);
+ }
+ }
+ }
+
+ // debug purpose
+ /*for(int i = 0; i < aRandomSize; i++)
+ {
+ LOGD("## setRandomInBuffer(): randomBuffPtr[%ld]=%d",i, (*aBuffer2Ptr)[i]);
+ }*/
+ }
+
+ return retCode;
+}
+
+/**
+* Read the instance ID of the calling object.
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @param aCallingClass java calling class name
+* @return the related instance ID
+**/
+jlong getInstanceId(JNIEnv* aJniEnv, jobject aJavaObject, const char *aCallingClass)
+{
+ jlong instanceId = 0;
+
+ if (aJniEnv)
+ {
+ jclass requiredClass = aJniEnv->FindClass(aCallingClass);
+ jclass loaderClass = 0;
+
+ if (requiredClass && (JNI_TRUE != aJniEnv->IsInstanceOf(aJavaObject, requiredClass)))
+ {
+ LOGE("## getInstanceId() failure - invalid instance of");
+ }
+ else if ((loaderClass = aJniEnv->GetObjectClass(aJavaObject)))
+ {
+ jfieldID instanceIdField = aJniEnv->GetFieldID(loaderClass, "mNativeId", "J");
+
+ if (instanceIdField)
+ {
+ instanceId = aJniEnv->GetLongField(aJavaObject, instanceIdField);
+ LOGD("## getInstanceId(): read from java instanceId=%lld",instanceId);
+ }
+ else
+ {
+ LOGE("## getInstanceId() ERROR! GetFieldID=null");
+ }
+
+ aJniEnv->DeleteLocalRef(loaderClass);
+ }
+ else
+ {
+ LOGE("## getInstanceId() ERROR! GetObjectClass=null");
+ }
+ }
+ else
+ {
+ LOGE("## getInstanceId() ERROR! aJniEnv=NULL");
+ }
+
+ LOGD("## getInstanceId() success - instanceId=%p (jlong)(intptr_t)instanceId=%lld",(void*)instanceId, (jlong)(intptr_t)instanceId);
+
+ return instanceId;
+}
+
+/**
+* Read the account instance ID of the calling object.
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @return the related OlmAccount.
+**/
+struct OlmAccount* getAccountInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
+{
+ return (struct OlmAccount*)getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_ACCOUNT);
+}
+
+/**
+* Read the session instance ID of the calling object (aJavaObject).<br>
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @return the related OlmSession.
+**/
+struct OlmSession* getSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
+{
+ return (struct OlmSession*)getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_SESSION);
+}
+
+/**
+* Read the inbound group session instance ID of the calling object (aJavaObject).<br>
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @return the related OlmInboundGroupSession.
+**/
+struct OlmInboundGroupSession* getInboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
+{
+ return (struct OlmInboundGroupSession*)getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_INBOUND_GROUP_SESSION);
+}
+
+/**
+* Read the outbound group session instance ID of the calling object (aJavaObject).<br>
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @return the related OlmOutboundGroupSession
+**/
+struct OlmOutboundGroupSession* getOutboundGroupSessionInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
+{
+ return (struct OlmOutboundGroupSession*)getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_OUTBOUND_GROUP_SESSION);
+}
+
+/**
+* Read the utility instance ID of the calling object (aJavaObject).<br>
+* @param aJniEnv pointer pointing on the JNI function table
+* @param aJavaObject reference to the object on which the method is invoked
+* @return the related OlmUtility
+**/
+struct OlmUtility* getUtilityInstanceId(JNIEnv* aJniEnv, jobject aJavaObject)
+{
+ return (struct OlmUtility*)getInstanceId(aJniEnv, aJavaObject, CLASS_OLM_UTILITY);
+}
diff --git a/android/olm-sdk/src/main/jni/olm_jni_helper.h b/android/olm-sdk/src/main/jni/olm_jni_helper.h
new file mode 100644
index 0000000..a181b32
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_jni_helper.h
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+#include "olm_jni.h"
+
+// constant strings
+namespace AndroidOlmSdk
+{
+ static const char *CLASS_OLM_INBOUND_GROUP_SESSION = "org/matrix/olm/OlmInboundGroupSession";
+ static const char *CLASS_OLM_OUTBOUND_GROUP_SESSION = "org/matrix/olm/OlmOutboundGroupSession";
+ static const char *CLASS_OLM_SESSION = "org/matrix/olm/OlmSession";
+ static const char *CLASS_OLM_ACCOUNT = "org/matrix/olm/OlmAccount";
+ static const char *CLASS_OLM_UTILITY = "org/matrix/olm/OlmUtility";
+}
diff --git a/android/olm-sdk/src/main/jni/olm_manager.cpp b/android/olm-sdk/src/main/jni/olm_manager.cpp
new file mode 100644
index 0000000..8ee0df7
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_manager.cpp
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+#include "olm_manager.h"
+
+using namespace AndroidOlmSdk;
+
+JNIEXPORT jstring OLM_MANAGER_FUNC_DEF(getOlmLibVersionJni)(JNIEnv* env, jobject thiz)
+{
+ uint8_t majorVer=0, minorVer=0, patchVer=0;
+ jstring returnValueStr=0;
+ char buff[150];
+
+ olm_get_library_version(&majorVer, &minorVer, &patchVer);
+ LOGD("## getOlmLibVersionJni(): Major=%d Minor=%d Patch=%d", majorVer, minorVer, patchVer);
+
+ snprintf(buff, sizeof(buff), "%d.%d.%d", majorVer, minorVer, patchVer);
+ returnValueStr = env->NewStringUTF((const char*)buff);
+
+ return returnValueStr;
+} \ No newline at end of file
diff --git a/android/olm-sdk/src/main/jni/olm_manager.h b/android/olm-sdk/src/main/jni/olm_manager.h
new file mode 100644
index 0000000..5fb6da2
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_manager.h
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLMANAGER_H
+#define _OMLMANAGER_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+
+#define OLM_MANAGER_FUNC_DEF(func_name) FUNC_DEF(OlmManager,func_name)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jstring OLM_MANAGER_FUNC_DEF(getOlmLibVersionJni)(JNIEnv *env, jobject thiz);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_outbound_group_session.cpp b/android/olm-sdk/src/main/jni/olm_outbound_group_session.cpp
new file mode 100644
index 0000000..a821709
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_outbound_group_session.cpp
@@ -0,0 +1,550 @@
+/*
+ * 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.
+ */
+
+#include "olm_outbound_group_session.h"
+
+using namespace AndroidOlmSdk;
+
+/**
+ * Release the session allocation made by initializeOutboundGroupSessionMemory().<br>
+ * This method MUST be called when java counter part account instance is done.
+ *
+ */
+JNIEXPORT void OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## releaseSessionJni(): OutBound group session IN");
+
+ OlmOutboundGroupSession* sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz);
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## releaseSessionJni(): failure - invalid outbound group session instance");
+ }
+ else
+ {
+ LOGD(" ## releaseSessionJni(): sessionPtr=%p",sessionPtr);
+
+#ifdef ENABLE_JNI_LOG
+ size_t retCode = olm_clear_outbound_group_session(sessionPtr);
+ LOGD(" ## releaseSessionJni(): clear_outbound_group_session=%lu",static_cast<long unsigned int>(retCode));
+#else
+ olm_clear_outbound_group_session(sessionPtr);
+#endif
+
+ LOGD(" ## releaseSessionJni(): free IN");
+ free(sessionPtr);
+ LOGD(" ## releaseSessionJni(): free OUT");
+ }
+}
+
+/**
+ * Initialize a new outbound group session and return it to JAVA side.<br>
+ * Since a C prt is returned as a jlong, special care will be taken
+ * to make the cast (OlmOutboundGroupSession* => jlong) platform independent.
+ * @return the initialized OlmOutboundGroupSession* instance or throw an exception
+ **/
+JNIEXPORT jlong OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+
+ OlmOutboundGroupSession* sessionPtr = NULL;
+ size_t sessionSize = 0;
+
+ LOGD("## createNewSessionJni(): outbound group session IN");
+ sessionSize = olm_outbound_group_session_size();
+
+ if (0 == sessionSize)
+ {
+ LOGE(" ## createNewSessionJni(): failure - outbound group session size = 0");
+ errorMessage = "outbound group session size = 0";
+ }
+ else if (!(sessionPtr = (OlmOutboundGroupSession*)malloc(sessionSize)))
+ {
+ LOGE(" ## createNewSessionJni(): failure - outbound group session OOM");
+ errorMessage = "outbound group session OOM";
+ }
+ else
+ {
+ sessionPtr = olm_outbound_group_session(sessionPtr);
+ LOGD(" ## createNewSessionJni(): success - outbound group session size=%lu",static_cast<long unsigned int>(sessionSize));
+
+ // compute random buffer
+ size_t randomLength = olm_init_outbound_group_session_random_length(sessionPtr);
+ uint8_t *randomBuffPtr = NULL;
+
+ LOGW(" ## createNewSessionJni(): randomLength=%lu",static_cast<long unsigned int>(randomLength));
+
+ if ((0 != randomLength) && !setRandomInBuffer(env, &randomBuffPtr, randomLength))
+ {
+ LOGE(" ## createNewSessionJni(): failure - random buffer init");
+ errorMessage = "random buffer init";
+ }
+ else
+ {
+ if (0 == randomLength)
+ {
+ LOGW(" ## createNewSessionJni(): random buffer is not required");
+ }
+
+ size_t sessionResult = olm_init_outbound_group_session(sessionPtr, randomBuffPtr, randomLength);
+
+ if (sessionResult == olm_error()) {
+ errorMessage = (const char *)olm_outbound_group_session_last_error(sessionPtr);
+ LOGE(" ## createNewSessionJni(): failure - init outbound session creation Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## createNewSessionJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
+ }
+
+ // clear the random buffer
+ memset(randomBuffPtr, 0, randomLength);
+ free(randomBuffPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ if (sessionPtr)
+ {
+ olm_clear_outbound_group_session(sessionPtr);
+ free(sessionPtr);
+ }
+
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)sessionPtr;
+}
+
+/**
+ * Return the session identifier.
+ * An exception is thrown if the operation fails.
+ * @return the session identifier
+ */
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## sessionIdentifierJni(): outbound group session IN");
+
+ const char* errorMessage = NULL;
+ OlmOutboundGroupSession *sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz);
+ jbyteArray returnValue = 0;
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## sessionIdentifierJni(): failure - invalid outbound group session instance");
+ errorMessage = "invalid outbound group session instance";
+ }
+ else
+ {
+ // get the size to alloc
+ size_t lengthSessionId = olm_outbound_group_session_id_length(sessionPtr);
+ LOGD(" ## sessionIdentifierJni(): outbound group session lengthSessionId=%lu",static_cast<long unsigned int>(lengthSessionId));
+
+ uint8_t *sessionIdPtr = (uint8_t*)malloc(lengthSessionId*sizeof(uint8_t));
+
+ if (!sessionIdPtr)
+ {
+ LOGE(" ## sessionIdentifierJni(): failure - outbound identifier allocation OOM");
+ errorMessage = "outbound identifier allocation OOM";
+ }
+ else
+ {
+ size_t result = olm_outbound_group_session_id(sessionPtr, sessionIdPtr, lengthSessionId);
+
+ if (result == olm_error())
+ {
+ errorMessage = reinterpret_cast<const char*>(olm_outbound_group_session_last_error(sessionPtr));
+ LOGE(" ## sessionIdentifierJni(): failure - outbound group session identifier failure Msg=%s", errorMessage);
+ }
+ else
+ {
+ returnValue = env->NewByteArray(result);
+ env->SetByteArrayRegion(returnValue, 0 , result, (jbyte*)sessionIdPtr);
+
+ LOGD(" ## sessionIdentifierJni(): success - outbound group session identifier result=%lu sessionId= %.*s",static_cast<long unsigned int>(result), static_cast<int>(result), reinterpret_cast<char*>(sessionIdPtr));
+ }
+
+ // free alloc
+ free(sessionIdPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+
+/**
+ * Get the current message index for this session.<br>
+ * 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
+ */
+JNIEXPORT jint OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(messageIndexJni)(JNIEnv *env, jobject thiz)
+{
+ OlmOutboundGroupSession *sessionPtr = NULL;
+ jint indexRetValue = 0;
+
+ LOGD("## messageIndexJni(): IN");
+
+ if (!(sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz)))
+ {
+ LOGE(" ## messageIndexJni(): failure - invalid outbound group session instance");
+ }
+ else
+ {
+ indexRetValue = static_cast<jint>(olm_outbound_group_session_message_index(sessionPtr));
+ }
+
+ LOGD(" ## messageIndexJni(): success - index=%d",indexRetValue);
+
+ return indexRetValue;
+}
+
+/**
+ * Return the session key.
+ * An exception is thrown if the operation fails.
+ * @return the session key
+ */
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(sessionKeyJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## sessionKeyJni(): outbound group session IN");
+
+ const char* errorMessage = NULL;
+ OlmOutboundGroupSession *sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz);
+ jbyteArray returnValue = 0;
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## sessionKeyJni(): failure - invalid outbound group session instance");
+ errorMessage = "invalid outbound group session instance";
+ }
+ else
+ {
+ // get the size to alloc
+ size_t sessionKeyLength = olm_outbound_group_session_key_length(sessionPtr);
+ LOGD(" ## sessionKeyJni(): sessionKeyLength=%lu",static_cast<long unsigned int>(sessionKeyLength));
+
+ uint8_t *sessionKeyPtr = (uint8_t*)malloc(sessionKeyLength*sizeof(uint8_t));
+
+ if (!sessionKeyPtr)
+ {
+ LOGE(" ## sessionKeyJni(): failure - session key allocation OOM");
+ errorMessage = "session key allocation OOM";
+ }
+ else
+ {
+ size_t result = olm_outbound_group_session_key(sessionPtr, sessionKeyPtr, sessionKeyLength);
+
+ if (result == olm_error())
+ {
+ errorMessage = (const char *)olm_outbound_group_session_last_error(sessionPtr);
+ LOGE(" ## sessionKeyJni(): failure - session key failure Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## sessionKeyJni(): success - outbound group session key result=%lu sessionKey=%.*s",static_cast<long unsigned int>(result), static_cast<int>(result), reinterpret_cast<char*>(sessionKeyPtr));
+
+ returnValue = env->NewByteArray(result);
+ env->SetByteArrayRegion(returnValue, 0 , result, (jbyte*)sessionKeyPtr);
+ }
+
+ // free alloc
+ free(sessionKeyPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+/**
+ * Encrypt a bytes buffer messages.
+ * An exception is thrown if the operation fails.
+ * @param aClearMsgBuffer the message to encode
+ * @return the encoded message
+ */
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(encryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aClearMsgBuffer)
+{
+ LOGD("## encryptMessageJni(): IN");
+
+ const char* errorMessage = NULL;
+ jbyteArray encryptedMsgRet = 0;
+
+ OlmOutboundGroupSession *sessionPtr = NULL;
+ jbyte* clearMsgPtr = NULL;
+
+ if (!(sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz)))
+ {
+ LOGE(" ## encryptMessageJni(): failure - invalid outbound group session ptr=NULL");
+ errorMessage = "invalid outbound group session ptr=NULL";
+ }
+ else if (!aClearMsgBuffer)
+ {
+ LOGE(" ## encryptMessageJni(): failure - invalid clear message");
+ errorMessage = "invalid clear message";
+ }
+ else if (!(clearMsgPtr = env->GetByteArrayElements(aClearMsgBuffer, NULL)))
+ {
+ LOGE(" ## encryptMessageJni(): failure - clear message JNI allocation OOM");
+ errorMessage = "clear message JNI allocation OOM";
+ }
+ else
+ {
+ // get clear message length
+ size_t clearMsgLength = (size_t)env->GetArrayLength(aClearMsgBuffer);
+ LOGD(" ## encryptMessageJni(): clearMsgLength=%lu",static_cast<long unsigned int>(clearMsgLength));
+
+ // compute max encrypted length
+ size_t encryptedMsgLength = olm_group_encrypt_message_length(sessionPtr,clearMsgLength);
+ uint8_t *encryptedMsgPtr = (uint8_t*)malloc(encryptedMsgLength*sizeof(uint8_t));
+
+ if (!encryptedMsgPtr)
+ {
+ LOGE(" ## encryptMessageJni(): failure - encryptedMsgPtr buffer OOM");
+ errorMessage = "encryptedMsgPtr buffer OOM";
+ }
+ else
+ {
+ LOGD(" ## encryptMessageJni(): estimated encryptedMsgLength=%lu",static_cast<long unsigned int>(encryptedMsgLength));
+
+ size_t encryptedLength = olm_group_encrypt(sessionPtr,
+ (uint8_t*)clearMsgPtr,
+ clearMsgLength,
+ encryptedMsgPtr,
+ encryptedMsgLength);
+
+
+ if (encryptedLength == olm_error())
+ {
+ errorMessage = olm_outbound_group_session_last_error(sessionPtr);
+ LOGE(" ## encryptMessageJni(): failure - olm_group_decrypt_max_plaintext_length Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## encryptMessageJni(): encrypted returnedLg=%lu plainTextMsgPtr=%.*s",static_cast<long unsigned int>(encryptedLength), static_cast<int>(encryptedLength), reinterpret_cast<char*>(encryptedMsgPtr));
+
+ encryptedMsgRet = env->NewByteArray(encryptedLength);
+ env->SetByteArrayRegion(encryptedMsgRet, 0 , encryptedLength, (jbyte*)encryptedMsgPtr);
+ }
+
+ free(encryptedMsgPtr);
+ }
+ }
+
+ // free alloc
+ if (clearMsgPtr)
+ {
+ env->ReleaseByteArrayElements(aClearMsgBuffer, clearMsgPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return encryptedMsgRet;
+}
+
+/**
+ * Serialize and encrypt session instance into a base64 string.<br>
+ * An exception is thrown if the operation fails.
+ * @param aKey key used to encrypt the serialized session data
+ * @return a base64 string if operation succeed, null otherwise
+ **/
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ jbyteArray returnValue = 0;
+
+ jbyte* keyPtr = NULL;
+ OlmOutboundGroupSession* sessionPtr = NULL;
+
+ LOGD("## outbound group session serializeJni(): IN");
+
+ if (!(sessionPtr = (OlmOutboundGroupSession*)getOutboundGroupSessionInstanceId(env,thiz)))
+ {
+ LOGE(" ## serializeJni(): failure - invalid session ptr");
+ errorMessage = "invalid session ptr";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## serializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## serializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = olm_pickle_outbound_group_session_length(sessionPtr);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## serializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+
+ void *pickledPtr = malloc(pickledLength*sizeof(uint8_t));
+
+ if(!pickledPtr)
+ {
+ LOGE(" ## serializeJni(): failure - pickledPtr buffer OOM");
+ errorMessage = "pickledPtr buffer OOM";
+ }
+ else
+ {
+ size_t result = olm_pickle_outbound_group_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_outbound_group_session_last_error(sessionPtr);
+ LOGE(" ## serializeJni(): failure - olm_pickle_outbound_group_session() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## serializeJni(): success - result=%lu pickled=%.*s", static_cast<long unsigned int>(result), static_cast<int>(result), static_cast<char*>(pickledPtr));
+
+ returnValue = env->NewByteArray(pickledLength);
+ env->SetByteArrayRegion(returnValue, 0 , pickledLength, (jbyte*)pickledPtr);
+ }
+ }
+
+ free(pickledPtr);
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+/**
+ * Allocate a new session and initialize it with the serialisation data.<br>
+ * 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
+ **/
+JNIEXPORT jlong OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ size_t sessionSize = olm_outbound_group_session_size();
+ OlmOutboundGroupSession* sessionPtr = NULL;
+
+ jbyte* keyPtr = NULL;
+ jbyte* pickledPtr = NULL;
+
+ LOGD("## deserializeJni(): IN");
+
+ if (!sessionSize)
+ {
+ LOGE(" ## deserializeJni(): failure - outbound group session size = 0");
+ errorMessage = "outbound group session size = 0";
+ }
+ else if (!(sessionPtr = (OlmOutboundGroupSession*)malloc(sessionSize)))
+ {
+ LOGE(" ## deserializeJni(): failure - session failure OOM");
+ errorMessage = "session failure OOM";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!aSerializedDataBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - serialized data");
+ errorMessage = "invalid serialized data";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else if (!(pickledPtr = env->GetByteArrayElements(aSerializedDataBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - pickledPtr JNI allocation OOM");
+ errorMessage = "pickledPtr JNI allocation OOM";
+ }
+ else
+ {
+ sessionPtr = olm_outbound_group_session(sessionPtr);
+ size_t pickledLength = (size_t)env->GetArrayLength(aSerializedDataBuffer);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## deserializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+ LOGD(" ## deserializeJni(): pickled=%.*s", static_cast<int>(pickledLength), (char const *)pickledPtr);
+
+ size_t result = olm_unpickle_outbound_group_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_outbound_group_session_last_error(sessionPtr);
+ LOGE(" ## deserializeJni(): failure - olm_unpickle_outbound_group_session() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## deserializeJni(): success - result=%lu ", static_cast<long unsigned int>(result));
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (pickledPtr)
+ {
+ env->ReleaseByteArrayElements(aSerializedDataBuffer, pickledPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ if (sessionPtr)
+ {
+ olm_clear_outbound_group_session(sessionPtr);
+ free(sessionPtr);
+ }
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)sessionPtr;
+}
+
diff --git a/android/olm-sdk/src/main/jni/olm_outbound_group_session.h b/android/olm-sdk/src/main/jni/olm_outbound_group_session.h
new file mode 100644
index 0000000..f6abba2
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_outbound_group_session.h
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLOUTBOUND_GROUP_SESSION_H
+#define _OMLOUTBOUND_GROUP_SESSION_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+#include "olm/outbound_group_session.h"
+
+#define OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(func_name) FUNC_DEF(OlmOutboundGroupSession,func_name)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// session creation/destruction
+JNIEXPORT void OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jlong OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz);
+
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(sessionIdentifierJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jint OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(messageIndexJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(sessionKeyJni)(JNIEnv *env, jobject thiz);
+
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(encryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aClearMsgBuffer);
+
+// serialization
+JNIEXPORT jbyteArray OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKey);
+JNIEXPORT jlong OLM_OUTBOUND_GROUP_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedData, jbyteArray aKey);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_session.cpp b/android/olm-sdk/src/main/jni/olm_session.cpp
new file mode 100644
index 0000000..5ca49db
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_session.cpp
@@ -0,0 +1,961 @@
+/*
+ * 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.
+ */
+
+#include "olm_session.h"
+
+using namespace AndroidOlmSdk;
+
+/**
+* Init memory allocation for a session creation.<br>
+* Make sure releaseSessionJni() is called when one is done with the session instance.
+* @return valid memory allocation, NULL otherwise
+**/
+OlmSession* initializeSessionMemory()
+{
+ size_t sessionSize = olm_session_size();
+ OlmSession* sessionPtr = (OlmSession*)malloc(sessionSize);
+
+ if (sessionPtr)
+ {
+ // init session object
+ sessionPtr = olm_session(sessionPtr);
+ LOGD("## initializeSessionMemory(): success - OLM session size=%lu",static_cast<long unsigned int>(sessionSize));
+ }
+ else
+ {
+ LOGE("## initializeSessionMemory(): failure - OOM");
+ }
+
+ return sessionPtr;
+}
+
+JNIEXPORT jlong OLM_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## createNewSessionJni(): IN");
+ OlmSession* accountPtr = initializeSessionMemory();
+
+ if (!accountPtr)
+ {
+ LOGE("## initNewAccount(): failure - init session OOM");
+ env->ThrowNew(env->FindClass("java/lang/Exception"), "init session OOM");
+ }
+ else
+ {
+ LOGD(" ## createNewSessionJni(): success - accountPtr=%p (jlong)(intptr_t)accountPtr=%lld",accountPtr,(jlong)(intptr_t)accountPtr);
+ }
+
+ return (jlong)(intptr_t)accountPtr;
+}
+
+JNIEXPORT void OLM_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz)
+{
+ LOGD("## releaseSessionJni(): IN");
+ OlmSession* sessionPtr = getSessionInstanceId(env, thiz);
+
+ if (!sessionPtr)
+ {
+ LOGE("## releaseSessionJni(): failure - invalid Session ptr=NULL");
+ }
+ else
+ {
+ olm_clear_session(sessionPtr);
+
+ // even if free(NULL) does not crash, logs are performed for debug purpose
+ free(sessionPtr);
+ }
+}
+
+// *********************************************************************
+// ********************** OUTBOUND SESSION *****************************
+// *********************************************************************
+/**
+ * Create a new in-bound session for sending/receiving messages from an
+ * incoming PRE_KEY message.<br> The recipient is defined as the entity
+ * with whom the session is established.
+ * @param aOlmAccountId account instance
+ * @param aTheirIdentityKey the identity key of the recipient
+ * @param aTheirOneTimeKey the one time key of the recipient or an exception is thrown
+ **/
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initOutboundSessionJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aTheirIdentityKeyBuffer, jbyteArray aTheirOneTimeKeyBuffer)
+{
+ OlmSession* sessionPtr = getSessionInstanceId(env, thiz);
+ const char* errorMessage = NULL;
+ OlmAccount* accountPtr = NULL;
+
+ if (!sessionPtr)
+ {
+ LOGE("## initOutboundSessionJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else if (!(accountPtr = (OlmAccount*)aOlmAccountId))
+ {
+ LOGE("## initOutboundSessionJni(): failure - invalid Account ptr=NULL");
+ errorMessage = "invalid Account ptr=NULL";
+ }
+ else if (!aTheirIdentityKeyBuffer || !aTheirOneTimeKeyBuffer)
+ {
+ LOGE("## initOutboundSessionJni(): failure - invalid keys");
+ errorMessage = "invalid keys";
+ }
+ else
+ {
+ size_t randomSize = olm_create_outbound_session_random_length(sessionPtr);
+ uint8_t *randomBuffPtr = NULL;
+
+ LOGD("## initOutboundSessionJni(): randomSize=%lu",static_cast<long unsigned int>(randomSize));
+
+ if ( (0 != randomSize) && !setRandomInBuffer(env, &randomBuffPtr, randomSize))
+ {
+ LOGE("## initOutboundSessionJni(): failure - random buffer init");
+ errorMessage = "random buffer init";
+ }
+ else
+ {
+ jbyte* theirIdentityKeyPtr = NULL;
+ jbyte* theirOneTimeKeyPtr = NULL;
+
+ // convert identity & one time keys to C strings
+ if (!(theirIdentityKeyPtr = env->GetByteArrayElements(aTheirIdentityKeyBuffer, 0)))
+ {
+ LOGE("## initOutboundSessionJni(): failure - identityKey JNI allocation OOM");
+ errorMessage = "identityKey JNI allocation OOM";
+ }
+ else if (!(theirOneTimeKeyPtr = env->GetByteArrayElements(aTheirOneTimeKeyBuffer, 0)))
+ {
+ LOGE("## initOutboundSessionJni(): failure - one time Key JNI allocation OOM");
+ errorMessage = "one time Key JNI allocation OOM";
+ }
+ else
+ {
+ size_t theirIdentityKeyLength = (size_t)env->GetArrayLength(aTheirIdentityKeyBuffer);
+ size_t theirOneTimeKeyLength = (size_t)env->GetArrayLength(aTheirOneTimeKeyBuffer);
+ LOGD("## initOutboundSessionJni(): identityKey=%.*s oneTimeKey=%.*s", static_cast<int>(theirIdentityKeyLength), theirIdentityKeyPtr, static_cast<int>(theirOneTimeKeyLength), theirOneTimeKeyPtr);
+
+ size_t sessionResult = olm_create_outbound_session(sessionPtr,
+ accountPtr,
+ theirIdentityKeyPtr,
+ theirIdentityKeyLength,
+ theirOneTimeKeyPtr,
+ theirOneTimeKeyLength,
+ (void*)randomBuffPtr,
+ randomSize);
+ if (sessionResult == olm_error()) {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## initOutboundSessionJni(): failure - session creation Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## initOutboundSessionJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
+ }
+ }
+
+ if (theirIdentityKeyPtr)
+ {
+ env->ReleaseByteArrayElements(aTheirIdentityKeyBuffer, theirIdentityKeyPtr, JNI_ABORT);
+ }
+
+ if (theirOneTimeKeyPtr)
+ {
+ env->ReleaseByteArrayElements(aTheirOneTimeKeyBuffer, theirOneTimeKeyPtr, JNI_ABORT);
+ }
+
+ if (randomBuffPtr)
+ {
+ memset(randomBuffPtr, 0, randomSize);
+ free(randomBuffPtr);
+ }
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+
+// *********************************************************************
+// *********************** INBOUND SESSION *****************************
+// *********************************************************************
+/**
+ * Create a new in-bound session for sending/receiving messages from an
+ * incoming PRE_KEY message.<br>
+ * An exception is thrown if the operation fails.
+ * @param aOlmAccountId account instance
+ * @param aOneTimeKeyMsg PRE_KEY message
+ */
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initInboundSessionJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aOneTimeKeyMsgBuffer)
+{
+ const char* errorMessage = NULL;
+ OlmSession *sessionPtr = getSessionInstanceId(env,thiz);
+ OlmAccount *accountPtr = NULL;
+ size_t sessionResult;
+
+ if (!sessionPtr)
+ {
+ LOGE("## initInboundSessionJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else if (!(accountPtr = (OlmAccount*)aOlmAccountId))
+ {
+ LOGE("## initInboundSessionJni(): failure - invalid Account ptr=NULL");
+ errorMessage = "invalid Account ptr=NULL";
+ }
+ else if (!aOneTimeKeyMsgBuffer)
+ {
+ LOGE("## initInboundSessionJni(): failure - invalid message");
+ errorMessage = "invalid message";
+ }
+ else
+ {
+ jbyte* messagePtr = env->GetByteArrayElements(aOneTimeKeyMsgBuffer, 0);
+
+ if (!messagePtr)
+ {
+ LOGE("## initInboundSessionJni(): failure - message JNI allocation OOM");
+ errorMessage = "message JNI allocation OOM";
+ }
+ else
+ {
+ size_t messageLength = (size_t)env->GetArrayLength(aOneTimeKeyMsgBuffer);
+ LOGD("## initInboundSessionJni(): messageLength=%lu message=%.*s", static_cast<long unsigned int>(messageLength), static_cast<int>(messageLength), messagePtr);
+
+ sessionResult = olm_create_inbound_session(sessionPtr, accountPtr, (void*)messagePtr , messageLength);
+
+ if (sessionResult == olm_error())
+ {
+ errorMessage = olm_session_last_error(sessionPtr);
+ LOGE("## initInboundSessionJni(): failure - init inbound session creation Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## initInboundSessionJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
+ }
+
+ // free local alloc
+ env->ReleaseByteArrayElements(aOneTimeKeyMsgBuffer, messagePtr, JNI_ABORT);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+/**
+ * Create a new in-bound session for sending/receiving messages from an
+ * incoming PRE_KEY message based on the recipient identity key.<br>
+ * An exception is thrown if the operation fails.
+ * @param aOlmAccountId account instance
+ * @param aTheirIdentityKey the identity key of the recipient
+ * @param aOneTimeKeyMsg encrypted message
+ */
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initInboundSessionFromIdKeyJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aTheirIdentityKeyBuffer, jbyteArray aOneTimeKeyMsgBuffer)
+{
+ const char* errorMessage = NULL;
+
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+ OlmAccount *accountPtr = NULL;
+ jbyte *messagePtr = NULL;
+ jbyte *theirIdentityKeyPtr = NULL;
+ size_t sessionResult;
+
+ if (!sessionPtr)
+ {
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else if (!(accountPtr = (OlmAccount*)aOlmAccountId))
+ {
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - invalid Account ptr=NULL");
+ errorMessage = "invalid Account ptr=NULL";
+ }
+ else if (!aTheirIdentityKeyBuffer)
+ {
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - invalid theirIdentityKey");
+ errorMessage = "invalid theirIdentityKey";
+ }
+ else if (!aOneTimeKeyMsgBuffer)
+ {
+ LOGE("## initInboundSessionJni(): failure - invalid one time key message");
+ errorMessage = "invalid invalid one time key message";
+ }
+ else if (!(messagePtr = env->GetByteArrayElements(aOneTimeKeyMsgBuffer, 0)))
+ {
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - message JNI allocation OOM");
+ errorMessage = "message JNI allocation OOM";
+ }
+ else if(!(theirIdentityKeyPtr = env->GetByteArrayElements(aTheirIdentityKeyBuffer, 0)))
+ {
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - theirIdentityKey JNI allocation OOM");
+ errorMessage = "theirIdentityKey JNI allocation OOM";
+ }
+ else
+ {
+ size_t messageLength = (size_t)env->GetArrayLength(aOneTimeKeyMsgBuffer);
+ size_t theirIdentityKeyLength = (size_t)env->GetArrayLength(aTheirIdentityKeyBuffer);
+
+ LOGD("## initInboundSessionFromIdKeyJni(): message=%.*s messageLength=%lu", static_cast<int>(messageLength), messagePtr, static_cast<long unsigned int>(messageLength));
+
+ sessionResult = olm_create_inbound_session_from(sessionPtr, accountPtr, theirIdentityKeyPtr, theirIdentityKeyLength, (void*)messagePtr , messageLength);
+ if (sessionResult == olm_error())
+ {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## initInboundSessionFromIdKeyJni(): failure - init inbound session creation Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## initInboundSessionFromIdKeyJni(): success - result=%lu", static_cast<long unsigned int>(sessionResult));
+ }
+ }
+
+ // free local alloc
+ if (messagePtr)
+ {
+ env->ReleaseByteArrayElements(aOneTimeKeyMsgBuffer, messagePtr, JNI_ABORT);
+ }
+
+ if (theirIdentityKeyPtr)
+ {
+ env->ReleaseByteArrayElements(aTheirIdentityKeyBuffer, theirIdentityKeyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+}
+
+/**
+ * Checks if the PRE_KEY message is for this in-bound session.<br>
+ * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY).
+ * @param aOneTimeKeyMsg PRE KEY message
+ * @return true if the PRE_KEY message matches
+ */
+JNIEXPORT jboolean OLM_SESSION_FUNC_DEF(matchesInboundSessionJni)(JNIEnv *env, jobject thiz, jbyteArray aOneTimeKeyMsgBuffer)
+{
+ jboolean retCode = JNI_FALSE;
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+ jbyte *messagePtr = NULL;
+
+ if (!sessionPtr)
+ {
+ LOGE("## matchesInboundSessionJni(): failure - invalid Session ptr=NULL");
+ }
+ else if (!aOneTimeKeyMsgBuffer)
+ {
+ LOGE("## matchesInboundSessionJni(): failure - invalid one time key message");
+ }
+ else if (!(messagePtr = env->GetByteArrayElements(aOneTimeKeyMsgBuffer, 0)))
+ {
+ LOGE("## matchesInboundSessionJni(): failure - one time key JNI allocation OOM");
+ }
+ else
+ {
+ size_t messageLength = (size_t)env->GetArrayLength(aOneTimeKeyMsgBuffer);
+
+ size_t matchResult = olm_matches_inbound_session(sessionPtr, (void*)messagePtr , messageLength);
+ //if(matchResult == olm_error()) {
+ // for now olm_matches_inbound_session() returns 1 when it succeeds, otherwise 1- or 0
+ if (matchResult != 1) {
+ LOGE("## matchesInboundSessionJni(): failure - no match Msg=%s",(const char *)olm_session_last_error(sessionPtr));
+ }
+ else
+ {
+ retCode = JNI_TRUE;
+ LOGD("## matchesInboundSessionJni(): success - result=%lu", static_cast<long unsigned int>(matchResult));
+ }
+ }
+
+ // free local alloc
+ if (messagePtr)
+ {
+ env->ReleaseByteArrayElements(aOneTimeKeyMsgBuffer, messagePtr, JNI_ABORT);
+ }
+
+ return retCode;
+}
+
+/**
+ * Checks if the PRE_KEY message is for this in-bound session based on the sender identity key.<br>
+ * This API may be used to process a "m.room.encrypted" event when type = 1 (PRE_KEY).
+ * @param aTheirIdentityKey the identity key of the sender
+ * @param aOneTimeKeyMsg PRE KEY message
+ * @return true if the PRE_KEY message matches.
+ */
+JNIEXPORT jboolean JNICALL OLM_SESSION_FUNC_DEF(matchesInboundSessionFromIdKeyJni)(JNIEnv *env, jobject thiz, jbyteArray aTheirIdentityKeyBuffer, jbyteArray aOneTimeKeyMsgBuffer)
+{
+ jboolean retCode = JNI_FALSE;
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+ jbyte *messagePtr = NULL;
+ jbyte *theirIdentityKeyPtr = NULL;
+
+ if (!sessionPtr)
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - invalid Session ptr=NULL");
+ }
+ else if (!aTheirIdentityKeyBuffer)
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - invalid theirIdentityKey");
+ }
+ else if (!(theirIdentityKeyPtr = env->GetByteArrayElements(aTheirIdentityKeyBuffer, 0)))
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - theirIdentityKey JNI allocation OOM");
+ }
+ else if (!aOneTimeKeyMsgBuffer)
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - invalid one time key message");
+ }
+ else if (!(messagePtr = env->GetByteArrayElements(aOneTimeKeyMsgBuffer, 0)))
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - one time key JNI allocation OOM");
+ }
+ else
+ {
+ size_t identityKeyLength = (size_t)env->GetArrayLength(aTheirIdentityKeyBuffer);
+ size_t messageLength = (size_t)env->GetArrayLength(aOneTimeKeyMsgBuffer);
+ size_t matchResult = olm_matches_inbound_session_from(sessionPtr, (void const *)theirIdentityKeyPtr, identityKeyLength, (void*)messagePtr , messageLength);
+
+ //if(matchResult == olm_error()) {
+ // for now olm_matches_inbound_session() returns 1 when it succeeds, otherwise 1- or 0
+ if (matchResult != 1)
+ {
+ LOGE("## matchesInboundSessionFromIdKeyJni(): failure - no match Msg=%s",(const char *)olm_session_last_error(sessionPtr));
+ }
+ else
+ {
+ retCode = JNI_TRUE;
+ LOGD("## matchesInboundSessionFromIdKeyJni(): success - result=%lu", static_cast<long unsigned int>(matchResult));
+ }
+ }
+
+ // free local alloc
+ if (theirIdentityKeyPtr)
+ {
+ env->ReleaseByteArrayElements(aTheirIdentityKeyBuffer, theirIdentityKeyPtr, JNI_ABORT);
+ }
+
+ if (messagePtr)
+ {
+ env->ReleaseByteArrayElements(aOneTimeKeyMsgBuffer, messagePtr, JNI_ABORT);
+ }
+
+ return retCode;
+}
+
+/**
+ * Encrypt a message using the session.<br>
+ * An exception is thrown if the operation fails.
+ * @param aClearMsg clear text message
+ * @param [out] aEncryptedMsg ciphered message
+ * @return the encrypted message
+ */
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(encryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aClearMsgBuffer, jobject aEncryptedMsg)
+{
+ jbyteArray encryptedMsgRet = 0;
+ const char* errorMessage = NULL;
+
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+ jbyte *clearMsgPtr = NULL;
+ jclass encryptedMsgJClass = 0;
+ jfieldID typeMsgFieldId;
+
+ LOGD("## encryptMessageJni(): IN ");
+
+ if (!sessionPtr)
+ {
+ LOGE("## encryptMessageJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else if (!aClearMsgBuffer)
+ {
+ LOGE("## encryptMessageJni(): failure - invalid clear message");
+ errorMessage = "invalid clear message";
+ }
+ else if (!aEncryptedMsg)
+ {
+ LOGE("## encryptMessageJni(): failure - invalid encrypted message");
+ }
+ else if (!(clearMsgPtr = env->GetByteArrayElements(aClearMsgBuffer, 0)))
+ {
+ LOGE("## encryptMessageJni(): failure - clear message JNI allocation OOM");
+ errorMessage = "clear message JNI allocation OOM";
+ }
+ else if (!(encryptedMsgJClass = env->GetObjectClass(aEncryptedMsg)))
+ {
+ LOGE("## encryptMessageJni(): failure - unable to get crypted message class");
+ errorMessage = "unable to get crypted message class";
+ }
+ else if (!(typeMsgFieldId = env->GetFieldID(encryptedMsgJClass,"mType","J")))
+ {
+ LOGE("## encryptMessageJni(): failure - unable to get message type field");
+ errorMessage = "unable to get message type field";
+ }
+ else
+ {
+ // get message type
+ size_t messageType = olm_encrypt_message_type(sessionPtr);
+ uint8_t *randomBuffPtr = NULL;
+
+ // compute random buffer
+ // Note: olm_encrypt_random_length() can return 0, which means
+ // it just does not need new random data to encrypt a new message
+ size_t randomLength = olm_encrypt_random_length(sessionPtr);
+
+ LOGD("## encryptMessageJni(): randomLength=%lu", static_cast<long unsigned int>(randomLength));
+
+ if ((0 != randomLength) && !setRandomInBuffer(env, &randomBuffPtr, randomLength))
+ {
+ LOGE("## encryptMessageJni(): failure - random buffer init");
+ errorMessage = "random buffer init";
+ }
+ else
+ {
+ // alloc buffer for encrypted message
+ size_t clearMsgLength = (size_t)env->GetArrayLength(aClearMsgBuffer);
+ size_t encryptedMsgLength = olm_encrypt_message_length(sessionPtr, clearMsgLength);
+
+ void *encryptedMsgPtr = malloc(encryptedMsgLength*sizeof(uint8_t));
+
+ if (!encryptedMsgPtr)
+ {
+ LOGE("## encryptMessageJni(): failure - encryptedMsgPtr buffer OOM");
+ errorMessage = "encryptedMsgPtr buffer OOM";
+ }
+ else
+ {
+ if (0 == randomLength)
+ {
+ LOGW("## encryptMessageJni(): random buffer is not required");
+ }
+
+ LOGD("## encryptMessageJni(): messageType=%lu randomLength=%lu clearMsgLength=%lu encryptedMsgLength=%lu",static_cast<long unsigned int>(messageType),static_cast<long unsigned int>(randomLength), static_cast<long unsigned int>(clearMsgLength), static_cast<long unsigned int>(encryptedMsgLength));
+ // encrypt message
+ size_t result = olm_encrypt(sessionPtr,
+ (void const *)clearMsgPtr,
+ clearMsgLength,
+ randomBuffPtr,
+ randomLength,
+ encryptedMsgPtr,
+ encryptedMsgLength);
+ if (result == olm_error())
+ {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## encryptMessageJni(): failure - Msg=%s", errorMessage);
+ }
+ else
+ {
+ // update message type: PRE KEY or normal
+ env->SetLongField(aEncryptedMsg, typeMsgFieldId, (jlong)messageType);
+
+ encryptedMsgRet = env->NewByteArray(encryptedMsgLength);
+ env->SetByteArrayRegion(encryptedMsgRet, 0 , encryptedMsgLength, (jbyte*)encryptedMsgPtr);
+
+ LOGD("## encryptMessageJni(): success - result=%lu Type=%lu encryptedMsg=%.*s", static_cast<long unsigned int>(result), static_cast<unsigned long int>(messageType), static_cast<int>(result), (const char*)encryptedMsgPtr);
+ }
+
+ free(encryptedMsgPtr);
+ }
+
+ memset(randomBuffPtr, 0, randomLength);
+ free(randomBuffPtr);
+ }
+ }
+
+ // free alloc
+ if (clearMsgPtr)
+ {
+ env->ReleaseByteArrayElements(aClearMsgBuffer, clearMsgPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return encryptedMsgRet;
+}
+
+/**
+ * Decrypt a message using the session.<br>
+ * An exception is thrown if the operation fails.
+ * @param aEncryptedMsg message to decrypt
+ * @return decrypted message if operation succeed
+ */
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jobject aEncryptedMsg)
+{
+ const char* errorMessage = NULL;
+
+ jbyteArray decryptedMsgRet = 0;
+
+ jclass encryptedMsgJClass = 0;
+ jstring encryptedMsgJstring = 0; // <= obtained from encryptedMsgFieldId
+ // field IDs
+ jfieldID encryptedMsgFieldId;
+ jfieldID typeMsgFieldId;
+ // ptrs
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+ const char *encryptedMsgPtr = NULL; // <= obtained from encryptedMsgJstring
+ uint8_t *plainTextMsgPtr = NULL;
+ char *tempEncryptedPtr = NULL;
+
+ LOGD("## decryptMessageJni(): IN - OlmSession");
+
+ if (!sessionPtr)
+ {
+ LOGE("## decryptMessageJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else if (!aEncryptedMsg)
+ {
+ LOGE("## decryptMessageJni(): failure - invalid encrypted message");
+ errorMessage = "invalid encrypted message";
+ }
+ else if (!(encryptedMsgJClass = env->GetObjectClass(aEncryptedMsg)))
+ {
+ LOGE("## decryptMessageJni(): failure - unable to get encrypted message class");
+ errorMessage = "unable to get encrypted message class";
+ }
+ else if (!(encryptedMsgFieldId = env->GetFieldID(encryptedMsgJClass,"mCipherText","Ljava/lang/String;")))
+ {
+ LOGE("## decryptMessageJni(): failure - unable to get message field");
+ errorMessage = "unable to get message field";
+ }
+ else if (!(typeMsgFieldId = env->GetFieldID(encryptedMsgJClass,"mType","J")))
+ {
+ LOGE("## decryptMessageJni(): failure - unable to get message type field");
+ errorMessage = "unable to get message type field";
+ }
+ else if (!(encryptedMsgJstring = (jstring)env->GetObjectField(aEncryptedMsg, encryptedMsgFieldId)))
+ {
+ LOGE("## decryptMessageJni(): failure - JNI encrypted object ");
+ errorMessage = "JNI encrypted object";
+ }
+ else if (!(encryptedMsgPtr = env->GetStringUTFChars(encryptedMsgJstring, 0)))
+ {
+ LOGE("## decryptMessageJni(): failure - encrypted message JNI allocation OOM");
+ errorMessage = "encrypted message JNI allocation OOM";
+ }
+ else
+ {
+ // get message type
+ size_t encryptedMsgType = (size_t)env->GetLongField(aEncryptedMsg, typeMsgFieldId);
+ // get encrypted message length
+ size_t encryptedMsgLength = (size_t)env->GetStringUTFLength(encryptedMsgJstring);
+
+ // create a dedicated temp buffer to be used in next Olm API calls
+ tempEncryptedPtr = static_cast<char*>(malloc(encryptedMsgLength*sizeof(uint8_t)));
+ memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
+ LOGD("## decryptMessageJni(): MsgType=%lu encryptedMsgLength=%lu encryptedMsg=%.*s",static_cast<long unsigned int>(encryptedMsgType),static_cast<long unsigned int>(encryptedMsgLength), static_cast<int>(encryptedMsgLength), encryptedMsgPtr);
+
+ // get max plaintext length
+ size_t maxPlainTextLength = olm_decrypt_max_plaintext_length(sessionPtr,
+ static_cast<size_t>(encryptedMsgType),
+ static_cast<void*>(tempEncryptedPtr),
+ encryptedMsgLength);
+ // Note: tempEncryptedPtr is destroyed by olm_decrypt_max_plaintext_length()
+
+ if (maxPlainTextLength == olm_error())
+ {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## decryptMessageJni(): failure - olm_decrypt_max_plaintext_length Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## decryptMessageJni(): maxPlaintextLength=%lu",static_cast<long unsigned int>(maxPlainTextLength));
+
+ // allocate output decrypted message
+ plainTextMsgPtr = static_cast<uint8_t*>(malloc(maxPlainTextLength*sizeof(uint8_t)));
+
+ // decrypt, but before reload encrypted buffer (previous one was destroyed)
+ memcpy(tempEncryptedPtr, encryptedMsgPtr, encryptedMsgLength);
+ size_t plaintextLength = olm_decrypt(sessionPtr,
+ encryptedMsgType,
+ (void*)tempEncryptedPtr,
+ encryptedMsgLength,
+ plainTextMsgPtr,
+ maxPlainTextLength);
+ if (plaintextLength == olm_error())
+ {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## decryptMessageJni(): failure - olm_decrypt Msg=%s", errorMessage);
+ }
+ else
+ {
+ decryptedMsgRet = env->NewByteArray(plaintextLength);
+ env->SetByteArrayRegion(decryptedMsgRet, 0 , plaintextLength, (jbyte*)plainTextMsgPtr);
+
+ LOGD(" ## decryptMessageJni(): UTF-8 Conversion - decrypted returnedLg=%lu OK",static_cast<long unsigned int>(plaintextLength));
+ }
+ }
+ }
+
+ // free alloc
+ if (encryptedMsgPtr)
+ {
+ env->ReleaseStringUTFChars(encryptedMsgJstring, encryptedMsgPtr);
+ }
+
+ if (tempEncryptedPtr)
+ {
+ free(tempEncryptedPtr);
+ }
+
+ if (plainTextMsgPtr)
+ {
+ free(plainTextMsgPtr);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return decryptedMsgRet;
+}
+
+/**
+ * Get the session identifier for this session.
+ * An exception is thrown if the operation fails.
+ * @return the session identifier
+ */
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(getSessionIdentifierJni)(JNIEnv *env, jobject thiz)
+{
+ const char* errorMessage = NULL;
+ jbyteArray returnValue = 0;
+
+ LOGD("## getSessionIdentifierJni(): IN ");
+
+ OlmSession *sessionPtr = getSessionInstanceId(env, thiz);
+
+ if (!sessionPtr)
+ {
+ LOGE("## getSessionIdentifierJni(): failure - invalid Session ptr=NULL");
+ errorMessage = "invalid Session ptr=NULL";
+ }
+ else
+ {
+ // get the size to alloc to contain the id
+ size_t lengthSessionId = olm_session_id_length(sessionPtr);
+ LOGD("## getSessionIdentifierJni(): lengthSessionId=%lu",static_cast<long unsigned int>(lengthSessionId));
+
+ void *sessionIdPtr = malloc(lengthSessionId*sizeof(uint8_t));
+
+ if (!sessionIdPtr)
+ {
+ LOGE("## getSessionIdentifierJni(): failure - identifier allocation OOM");
+ errorMessage = "identifier allocation OOM";
+ }
+ else
+ {
+ size_t result = olm_session_id(sessionPtr, sessionIdPtr, lengthSessionId);
+
+ if (result == olm_error())
+ {
+ errorMessage = (const char *)olm_session_last_error(sessionPtr);
+ LOGE("## getSessionIdentifierJni(): failure - get session identifier failure Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD("## getSessionIdentifierJni(): success - result=%lu sessionId=%.*s",static_cast<long unsigned int>(result), static_cast<int>(result), (char*)sessionIdPtr);
+
+ returnValue = env->NewByteArray(result);
+ env->SetByteArrayRegion(returnValue, 0 , result, (jbyte*)sessionIdPtr);
+ }
+
+ free(sessionIdPtr);
+ }
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+/**
+ * Serialize and encrypt session instance.<br>
+ * 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.
+ **/
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ jbyteArray returnValue = 0;
+
+ jbyte* keyPtr = NULL;
+ OlmSession* sessionPtr = getSessionInstanceId(env, thiz);
+
+ LOGD("## serializeJni(): IN");
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## serializeJni(): failure - invalid session ptr");
+ errorMessage = "invalid session ptr";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## serializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## serializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "ikeyPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = olm_pickle_session_length(sessionPtr);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## serializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+
+ void *pickledPtr = malloc(pickledLength*sizeof(uint8_t));
+
+ if (!pickledPtr)
+ {
+ LOGE(" ## serializeJni(): failure - pickledPtr buffer OOM");
+ errorMessage = "pickledPtr buffer OOM";
+ }
+ else
+ {
+ size_t result = olm_pickle_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_session_last_error(sessionPtr);
+ LOGE(" ## serializeJni(): failure - olm_pickle_session() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## serializeJni(): success - result=%lu pickled=%.*s", static_cast<long unsigned int>(result), static_cast<int>(pickledLength), static_cast<char*>(pickledPtr));
+
+ returnValue = env->NewByteArray(pickledLength);
+ env->SetByteArrayRegion(returnValue, 0 , pickledLength, (jbyte*)pickledPtr);
+ }
+
+ free(pickledPtr);
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return returnValue;
+}
+
+/**
+ * Allocate a new session and initialize it with the serialisation data.<br>
+ * 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
+ **/
+JNIEXPORT jlong OLM_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedDataBuffer, jbyteArray aKeyBuffer)
+{
+ const char* errorMessage = NULL;
+ OlmSession* sessionPtr = initializeSessionMemory();
+ jbyte* keyPtr = NULL;
+ jbyte* pickledPtr = NULL;
+
+ LOGD("## deserializeJni(): IN");
+
+ if (!sessionPtr)
+ {
+ LOGE(" ## deserializeJni(): failure - session failure OOM");
+ errorMessage = "session failure OOM";
+ }
+ else if (!aKeyBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - invalid key");
+ errorMessage = "invalid key";
+ }
+ else if (!aSerializedDataBuffer)
+ {
+ LOGE(" ## deserializeJni(): failure - serialized data");
+ errorMessage = "serialized data";
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - keyPtr JNI allocation OOM");
+ errorMessage = "keyPtr JNI allocation OOM";
+ }
+ else if (!(pickledPtr = env->GetByteArrayElements(aSerializedDataBuffer, 0)))
+ {
+ LOGE(" ## deserializeJni(): failure - pickledPtr JNI allocation OOM");
+ errorMessage = "pickledPtr JNI allocation OOM";
+ }
+ else
+ {
+ size_t pickledLength = (size_t)env->GetArrayLength(aSerializedDataBuffer);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ LOGD(" ## deserializeJni(): pickledLength=%lu keyLength=%lu",static_cast<long unsigned int>(pickledLength), static_cast<long unsigned int>(keyLength));
+ LOGD(" ## deserializeJni(): pickled=%.*s",static_cast<int>(pickledLength), (char const *)pickledPtr);
+
+ size_t result = olm_unpickle_session(sessionPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void*)pickledPtr,
+ pickledLength);
+ if (result == olm_error())
+ {
+ errorMessage = olm_session_last_error(sessionPtr);
+ LOGE(" ## deserializeJni(): failure - olm_unpickle_account() Msg=%s", errorMessage);
+ }
+ else
+ {
+ LOGD(" ## initJni(): success - result=%lu ", static_cast<long unsigned int>(result));
+ }
+ }
+
+ // free alloc
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (pickledPtr)
+ {
+ env->ReleaseByteArrayElements(aSerializedDataBuffer, pickledPtr, JNI_ABORT);
+ }
+
+ if (errorMessage)
+ {
+ if (sessionPtr)
+ {
+ olm_clear_session(sessionPtr);
+ free(sessionPtr);
+ }
+ env->ThrowNew(env->FindClass("java/lang/Exception"), errorMessage);
+ }
+
+ return (jlong)(intptr_t)sessionPtr;
+} \ No newline at end of file
diff --git a/android/olm-sdk/src/main/jni/olm_session.h b/android/olm-sdk/src/main/jni/olm_session.h
new file mode 100644
index 0000000..b8cdd2f
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_session.h
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLSESSION_H
+#define _OMLSESSION_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+
+#define OLM_SESSION_FUNC_DEF(func_name) FUNC_DEF(OlmSession,func_name)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// session creation/destruction
+JNIEXPORT void OLM_SESSION_FUNC_DEF(releaseSessionJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jlong OLM_SESSION_FUNC_DEF(createNewSessionJni)(JNIEnv *env, jobject thiz);
+
+// outbound session
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initOutboundSessionJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aTheirIdentityKey, jbyteArray aTheirOneTimeKey);
+
+// inbound sessions: establishment based on PRE KEY message
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initInboundSessionJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aOneTimeKeyMsg);
+JNIEXPORT void OLM_SESSION_FUNC_DEF(initInboundSessionFromIdKeyJni)(JNIEnv *env, jobject thiz, jlong aOlmAccountId, jbyteArray aTheirIdentityKey, jbyteArray aOneTimeKeyMsg);
+
+// match inbound sessions: based on PRE KEY message
+JNIEXPORT jboolean OLM_SESSION_FUNC_DEF(matchesInboundSessionJni)(JNIEnv *env, jobject thiz, jbyteArray aOneTimeKeyMsg);
+JNIEXPORT jboolean OLM_SESSION_FUNC_DEF(matchesInboundSessionFromIdKeyJni)(JNIEnv *env, jobject thiz, jbyteArray aTheirIdentityKey, jbyteArray aOneTimeKeyMsg);
+
+// encrypt/decrypt
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(encryptMessageJni)(JNIEnv *env, jobject thiz, jbyteArray aClearMsg, jobject aEncryptedMsg);
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(decryptMessageJni)(JNIEnv *env, jobject thiz, jobject aEncryptedMsg);
+
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(getSessionIdentifierJni)(JNIEnv *env, jobject thiz);
+
+// serialization
+JNIEXPORT jbyteArray OLM_SESSION_FUNC_DEF(serializeJni)(JNIEnv *env, jobject thiz, jbyteArray aKey);
+JNIEXPORT jlong OLM_SESSION_FUNC_DEF(deserializeJni)(JNIEnv *env, jobject thiz, jbyteArray aSerializedData, jbyteArray aKey);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/android/olm-sdk/src/main/jni/olm_utility.cpp b/android/olm-sdk/src/main/jni/olm_utility.cpp
new file mode 100644
index 0000000..f6fe719
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_utility.cpp
@@ -0,0 +1,228 @@
+/*
+ * 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.
+ */
+
+#include "olm_utility.h"
+
+using namespace AndroidOlmSdk;
+
+OlmUtility* initializeUtilityMemory()
+{
+ size_t utilitySize = olm_utility_size();
+ OlmUtility* utilityPtr = (OlmUtility*)malloc(utilitySize);
+
+ if (utilityPtr)
+ {
+ utilityPtr = olm_utility(utilityPtr);
+ LOGD("## initializeUtilityMemory(): success - OLM utility size=%lu",static_cast<long unsigned int>(utilitySize));
+ }
+ else
+ {
+ LOGE("## initializeUtilityMemory(): failure - OOM");
+ }
+
+ return utilityPtr;
+}
+
+JNIEXPORT jlong OLM_UTILITY_FUNC_DEF(createUtilityJni)(JNIEnv *env, jobject thiz)
+{
+ OlmUtility* utilityPtr = initializeUtilityMemory();
+
+ LOGD("## createUtilityJni(): IN");
+
+ // init account memory allocation
+ if (!utilityPtr)
+ {
+ LOGE(" ## createUtilityJni(): failure - init OOM");
+ env->ThrowNew(env->FindClass("java/lang/Exception"), "init OOM");
+ }
+ else
+ {
+ LOGD(" ## createUtilityJni(): success");
+ }
+
+ return (jlong)(intptr_t)utilityPtr;
+}
+
+
+JNIEXPORT void OLM_UTILITY_FUNC_DEF(releaseUtilityJni)(JNIEnv *env, jobject thiz)
+{
+ OlmUtility* utilityPtr = getUtilityInstanceId(env, thiz);
+
+ LOGD("## releaseUtilityJni(): IN");
+
+ if (!utilityPtr)
+ {
+ LOGE("## releaseUtilityJni(): failure - utility ptr=NULL");
+ }
+ else
+ {
+ olm_clear_utility(utilityPtr);
+ free(utilityPtr);
+ }
+}
+
+
+/**
+ * Verify an ed25519 signature.
+ * @param aSignature the base64-encoded message signature to be checked.
+ * @param aKey the ed25519 key (fingerprint key)
+ * @param aMessage the message which was signed
+ * @return 0 if validation succeed, an error message string if operation failed
+ */
+JNIEXPORT jstring OLM_UTILITY_FUNC_DEF(verifyEd25519SignatureJni)(JNIEnv *env, jobject thiz, jbyteArray aSignatureBuffer, jbyteArray aKeyBuffer, jbyteArray aMessageBuffer)
+{
+ jstring errorMessageRetValue = 0;
+ OlmUtility* utilityPtr = getUtilityInstanceId(env, thiz);
+ jbyte* signaturePtr = NULL;
+ jbyte* keyPtr = NULL;
+ jbyte* messagePtr = NULL;
+
+ LOGD("## verifyEd25519SignatureJni(): IN");
+
+ if (!utilityPtr)
+ {
+ LOGE(" ## verifyEd25519SignatureJni(): failure - invalid utility ptr=NULL");
+ }
+ else if (!aSignatureBuffer || !aKeyBuffer || !aMessageBuffer)
+ {
+ LOGE(" ## verifyEd25519SignatureJni(): failure - invalid input parameters ");
+ }
+ else if (!(signaturePtr = env->GetByteArrayElements(aSignatureBuffer, 0)))
+ {
+ LOGE(" ## verifyEd25519SignatureJni(): failure - signature JNI allocation OOM");
+ }
+ else if (!(keyPtr = env->GetByteArrayElements(aKeyBuffer, 0)))
+ {
+ LOGE(" ## verifyEd25519SignatureJni(): failure - key JNI allocation OOM");
+ }
+ else if (!(messagePtr = env->GetByteArrayElements(aMessageBuffer, 0)))
+ {
+ LOGE(" ## verifyEd25519SignatureJni(): failure - message JNI allocation OOM");
+ }
+ else
+ {
+ size_t signatureLength = (size_t)env->GetArrayLength(aSignatureBuffer);
+ size_t keyLength = (size_t)env->GetArrayLength(aKeyBuffer);
+ size_t messageLength = (size_t)env->GetArrayLength(aMessageBuffer);
+ LOGD(" ## verifyEd25519SignatureJni(): signatureLength=%lu keyLength=%lu messageLength=%lu",static_cast<long unsigned int>(signatureLength),static_cast<long unsigned int>(keyLength),static_cast<long unsigned int>(messageLength));
+ LOGD(" ## verifyEd25519SignatureJni(): key=%.*s", static_cast<int>(keyLength), keyPtr);
+
+ size_t result = olm_ed25519_verify(utilityPtr,
+ (void const *)keyPtr,
+ keyLength,
+ (void const *)messagePtr,
+ messageLength,
+ (void*)signaturePtr,
+ signatureLength);
+ if (result == olm_error()) {
+ const char *errorMsgPtr = olm_utility_last_error(utilityPtr);
+ errorMessageRetValue = env->NewStringUTF(errorMsgPtr);
+ LOGE("## verifyEd25519SignatureJni(): failure - olm_ed25519_verify Msg=%s",errorMsgPtr);
+ }
+ else
+ {
+ LOGD("## verifyEd25519SignatureJni(): success - result=%lu", static_cast<long unsigned int>(result));
+ }
+ }
+
+ // free alloc
+ if (signaturePtr)
+ {
+ env->ReleaseByteArrayElements(aSignatureBuffer, signaturePtr, JNI_ABORT);
+ }
+
+ if (keyPtr)
+ {
+ env->ReleaseByteArrayElements(aKeyBuffer, keyPtr, JNI_ABORT);
+ }
+
+ if (messagePtr)
+ {
+ env->ReleaseByteArrayElements(aMessageBuffer, messagePtr, JNI_ABORT);
+ }
+
+ return errorMessageRetValue;
+}
+
+/**
+ * Compute the digest (SHA 256) for the message passed in parameter.<br>
+ * 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.
+ **/
+JNIEXPORT jbyteArray OLM_UTILITY_FUNC_DEF(sha256Jni)(JNIEnv *env, jobject thiz, jbyteArray aMessageToHashBuffer)
+{
+ jbyteArray sha256Ret = 0;
+
+ OlmUtility* utilityPtr = getUtilityInstanceId(env, thiz);
+ jbyte* messagePtr = NULL;
+
+ LOGD("## sha256Jni(): IN");
+
+ if (!utilityPtr)
+ {
+ LOGE(" ## sha256Jni(): failure - invalid utility ptr=NULL");
+ }
+ else if(!aMessageToHashBuffer)
+ {
+ LOGE(" ## sha256Jni(): failure - invalid message parameters ");
+ }
+ else if(!(messagePtr = env->GetByteArrayElements(aMessageToHashBuffer, 0)))
+ {
+ LOGE(" ## sha256Jni(): failure - message JNI allocation OOM");
+ }
+ else
+ {
+ // get lengths
+ size_t messageLength = (size_t)env->GetArrayLength(aMessageToHashBuffer);
+ size_t hashLength = olm_sha256_length(utilityPtr);
+ void* hashValuePtr = malloc((hashLength)*sizeof(uint8_t));
+
+ if (!hashValuePtr)
+ {
+ LOGE("## sha256Jni(): failure - hash value allocation OOM");
+ }
+ else
+ {
+ size_t result = olm_sha256(utilityPtr,
+ (void const *)messagePtr,
+ messageLength,
+ (void *)hashValuePtr,
+ hashLength);
+ if (result == olm_error())
+ {
+ LOGE("## sha256Jni(): failure - hash creation Msg=%s",(const char *)olm_utility_last_error(utilityPtr));
+ }
+ else
+ {
+ LOGD("## sha256Jni(): success - result=%lu hashValue=%.*s",static_cast<long unsigned int>(result), static_cast<int>(result), (char*)hashValuePtr);
+ sha256Ret = env->NewByteArray(result);
+ env->SetByteArrayRegion(sha256Ret, 0 , result, (jbyte*)hashValuePtr);
+ }
+
+ free(hashValuePtr);
+ }
+ }
+
+ if (messagePtr)
+ {
+ env->ReleaseByteArrayElements(aMessageToHashBuffer, messagePtr, JNI_ABORT);
+ }
+
+ return sha256Ret;
+} \ No newline at end of file
diff --git a/android/olm-sdk/src/main/jni/olm_utility.h b/android/olm-sdk/src/main/jni/olm_utility.h
new file mode 100644
index 0000000..de4b290
--- /dev/null
+++ b/android/olm-sdk/src/main/jni/olm_utility.h
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+#ifndef _OMLUTILITY_H
+#define _OMLUTILITY_H
+
+#include "olm_jni.h"
+#include "olm/olm.h"
+
+#define OLM_UTILITY_FUNC_DEF(func_name) FUNC_DEF(OlmUtility,func_name)
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jlong OLM_UTILITY_FUNC_DEF(createUtilityJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT void OLM_UTILITY_FUNC_DEF(releaseUtilityJni)(JNIEnv *env, jobject thiz);
+JNIEXPORT jstring OLM_UTILITY_FUNC_DEF(verifyEd25519SignatureJni)(JNIEnv *env, jobject thiz, jbyteArray aSignature, jbyteArray aKey, jbyteArray aMessage);
+JNIEXPORT jbyteArray OLM_UTILITY_FUNC_DEF(sha256Jni)(JNIEnv *env, jobject thiz, jbyteArray aMessageToHash);
+#ifdef __cplusplus
+}
+#endif
+
+
+
+#endif