forked from trustwallet/wallet-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRandom.cpp
More file actions
51 lines (40 loc) · 1.53 KB
/
Random.cpp
File metadata and controls
51 lines (40 loc) · 1.53 KB
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
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include <jni.h>
#include <string.h>
static JavaVM* cachedJVM;
extern "C" {
uint32_t random32();
void random_buffer(uint8_t *buf, size_t len);
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
cachedJVM = jvm;
return JNI_VERSION_1_2;
}
uint32_t random32() {
uint32_t result;
random_buffer((uint8_t*) &result, sizeof(uint32_t));
return result;
}
void random_buffer(uint8_t *buf, size_t len) {
JNIEnv *env;
cachedJVM->AttachCurrentThread(&env, NULL);
// SecureRandom random = new SecureRandom();
jclass secureRandomClass = env->FindClass("java/security/SecureRandom");
jmethodID constructor = env->GetMethodID(secureRandomClass, "<init>", "()V");
jobject random = env->NewObject(secureRandomClass, constructor);
//byte array[] = new byte[len];
jbyteArray array = env->NewByteArray(len);
//random.nextBytes(bytes);
jmethodID nextBytes = env->GetMethodID(secureRandomClass, "nextBytes", "([B)V");
env->CallVoidMethod(random, nextBytes, array);
jbyte* bytes = env->GetByteArrayElements(array, nullptr);
memcpy(buf, bytes, len);
env->ReleaseByteArrayElements(array, bytes, JNI_ABORT);
env->DeleteLocalRef(array);
env->DeleteLocalRef(random);
env->DeleteLocalRef(secureRandomClass);
}