Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* 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;
}