Skip to content

Commit

Permalink
Merge branch 'master' into feat-support-spl-token2022
Browse files Browse the repository at this point in the history
  • Loading branch information
satoshiotomakan authored Aug 16, 2024
2 parents 83b6959 + d65c344 commit 96fb730
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions jni/cpp/Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <jni.h>
#include <string.h>
#include <stdint.h>
#include <fstream>

static JavaVM* cachedJVM;

Expand All @@ -25,31 +26,42 @@ uint32_t random32() {
}

void random_buffer(uint8_t *buf, size_t len) {
JNIEnv *env;

if (cachedJVM)
{
JNIEnv *env;

#if defined(__ANDROID__) || defined(ANDROID)
cachedJVM->AttachCurrentThread(&env, nullptr);
#else
cachedJVM->AttachCurrentThread((void **) &env, nullptr);
#endif

// SecureRandom random = new SecureRandom();
jclass secureRandomClass = env->FindClass("java/security/SecureRandom");
jmethodID constructor = env->GetMethodID(secureRandomClass, "<init>", "()V");
jobject random = env->NewObject(secureRandomClass, constructor);
// 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(static_cast<jsize>(len));
//byte array[] = new byte[len];
jbyteArray array = env->NewByteArray(static_cast<jsize>(len));

//random.nextBytes(bytes);
jmethodID nextBytes = env->GetMethodID(secureRandomClass, "nextBytes", "([B)V");
env->CallVoidMethod(random, nextBytes, array);
//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);
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);
env->DeleteLocalRef(array);
env->DeleteLocalRef(random);
env->DeleteLocalRef(secureRandomClass);
}
else
{
std::ifstream randomData("/dev/urandom", std::ios::in | std::ios::binary);
if (randomData.is_open()) {
randomData.read(reinterpret_cast<char*>(buf), len);
randomData.close();
}
}
}

0 comments on commit 96fb730

Please sign in to comment.