Home | History | Annotate | Download | only in jni
      1 /*
      2  * Copyright (C) 2018 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "Scrypt"
     18 
     19 #include <nativehelper/JNIHelp.h>
     20 #include "jni.h"
     21 
     22 #include <android_runtime/Log.h>
     23 #include <utils/Timers.h>
     24 #include <utils/misc.h>
     25 #include <utils/String8.h>
     26 #include <utils/Log.h>
     27 
     28 extern "C" {
     29 #include "crypto_scrypt.h"
     30 }
     31 
     32 namespace android {
     33 
     34 static jbyteArray android_security_Scrypt_nativeScrypt(JNIEnv* env, jobject, jbyteArray password, jbyteArray salt, jint N, jint r, jint p, jint outLen) {
     35     if (!password || !salt) {
     36         return NULL;
     37     }
     38 
     39     int passwordLen = env->GetArrayLength(password);
     40     int saltLen = env->GetArrayLength(salt);
     41     jbyteArray ret = env->NewByteArray(outLen);
     42 
     43     jbyte* passwordPtr = (jbyte*)env->GetByteArrayElements(password, NULL);
     44     jbyte* saltPtr = (jbyte*)env->GetByteArrayElements(salt, NULL);
     45     jbyte* retPtr = (jbyte*)env->GetByteArrayElements(ret, NULL);
     46 
     47     int rc = crypto_scrypt((const uint8_t *)passwordPtr, passwordLen,
     48                        (const uint8_t *)saltPtr, saltLen, N, r, p, (uint8_t *)retPtr,
     49                        outLen);
     50     env->ReleaseByteArrayElements(password, passwordPtr, JNI_ABORT);
     51     env->ReleaseByteArrayElements(salt, saltPtr, JNI_ABORT);
     52     env->ReleaseByteArrayElements(ret, retPtr, 0);
     53 
     54     if (!rc) {
     55         return ret;
     56     } else {
     57         SLOGE("scrypt failed");
     58         return NULL;
     59     }
     60 }
     61 
     62 static const JNINativeMethod sMethods[] = {
     63      /* name, signature, funcPtr */
     64     {"nativeScrypt", "([B[BIIII)[B", (void*)android_security_Scrypt_nativeScrypt},
     65 };
     66 
     67 int register_android_security_Scrypt(JNIEnv* env) {
     68     return jniRegisterNativeMethods(env, "android/security/Scrypt",
     69                                     sMethods, NELEM(sMethods));
     70 }
     71 
     72 } /* namespace android */
     73