com_spirent_its_security_NativeSecurity.c 2.1 KB
Newer Older
Yann Garcia's avatar
Yann Garcia committed
/* system headers */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
//add whatever is needed
#include <jni.h>
#include "com_spirent_its_security_NativeSecurity.h"

#include "lib_its_security.h"

//if you use other memory allocation function, please inform me!
#ifdef WIN32
DLLAPI void* _tt_calloc(size_t, size_t);
#define calloc(NUM, SIZE) _tt_calloc(NUM, SIZE)
DLLAPI void _tt_free(void*);
#define free(PTR) _tt_free(PTR)
#else
#endif //WIN32

#ifdef WIN32
void* _tt_calloc(size_t num, size_t elemSize) {
#if (_MSC_VER >= 1700) // newer than Visual Studio 2012
    size_t size = num * elemSize;
    void* res = CoTaskMemAlloc(size);
    memset(res, 0, size);
    return res;
#else
    return HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS | HEAP_ZERO_MEMORY, (num) * (elemSize));
#endif
}

void _tt_free(void* ptr) {
#if (_MSC_VER >= 1700) // newer than Visual Studio 2012
    CoTaskMemFree(ptr);
#else
    HeapFree(GetProcessHeap(), 0, ptr);
#endif
}
#endif //WIN32

/*
 * Class:     com_spirent_its_security_NativeSecurity
 * Method:    hashWithSha256
 * Signature: ([B)[B
 */
JNIEXPORT jbyteArray JNICALL Java_com_spirent_its_security_NativeSecurity_hashWithSha256(JNIEnv* env, jobject jobj, jbyteArray p_toBeHashedData) {
    jbyteArray java_hashed_data;
    int32_t result;

    // Extract buffers
    size_t to_be_hashed_data_length = (*env)->GetArrayLength(env, p_toBeHashedData);
    uint8_t* to_be_hashed_data = (uint8_t*)calloc(sizeof(uint8_t), to_be_hashed_data_length);
    (*env)->GetByteArrayRegion(env, p_toBeHashedData, 0, (jsize)to_be_hashed_data_length, (jbyte*)to_be_hashed_data);
    // Call lib_its_security implementation
    uint8_t* hashed_data = NULL;
    result = hash_with_sha256(to_be_hashed_data, to_be_hashed_data_length, &hashed_data);
    // Prepare return value
    java_hashed_data = (*env)->NewByteArray(env, (jsize)to_be_hashed_data_length);
    if (result == 0) {
        (*env)->SetByteArrayRegion(env, java_hashed_data, 0, (jsize)to_be_hashed_data_length, (jbyte*)hashed_data);
    }
    // Free allocated resources
    free(hashed_data);

    return java_hashed_data;
}