1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mozglue/android/NativeCrypto.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,74 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +#include "NativeCrypto.h" 1.9 + 1.10 +#include <jni.h> 1.11 + 1.12 +#include <errno.h> 1.13 +#include <stdlib.h> 1.14 +#include <inttypes.h> 1.15 + 1.16 +#include "mozilla/SHA1.h" 1.17 +#include "pbkdf2_sha256.h" 1.18 + 1.19 +/** 1.20 + * Helper function to invoke native PBKDF2 function with JNI 1.21 + * arguments. 1.22 + */ 1.23 +extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_pbkdf2SHA256 1.24 + (JNIEnv *env, jclass jc, jbyteArray jpassword, jbyteArray jsalt, jint c, jint dkLen) { 1.25 + if (dkLen < 0) { 1.26 + env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), 1.27 + "dkLen should not be less than 0"); 1.28 + return NULL; 1.29 + } 1.30 + 1.31 + jbyte *password = env->GetByteArrayElements(jpassword, NULL); 1.32 + size_t passwordLen = env->GetArrayLength(jpassword); 1.33 + 1.34 + jbyte *salt = env->GetByteArrayElements(jsalt, NULL); 1.35 + size_t saltLen = env->GetArrayLength(jsalt); 1.36 + 1.37 + uint8_t hashResult[dkLen]; 1.38 + PBKDF2_SHA256((uint8_t *) password, passwordLen, (uint8_t *) salt, saltLen, 1.39 + (uint64_t) c, hashResult, (size_t) dkLen); 1.40 + 1.41 + env->ReleaseByteArrayElements(jpassword, password, JNI_ABORT); 1.42 + env->ReleaseByteArrayElements(jsalt, salt, JNI_ABORT); 1.43 + 1.44 + jbyteArray out = env->NewByteArray(dkLen); 1.45 + if (out == NULL) { 1.46 + return NULL; 1.47 + } 1.48 + env->SetByteArrayRegion(out, 0, dkLen, (jbyte *) hashResult); 1.49 + 1.50 + return out; 1.51 +} 1.52 + 1.53 +using namespace mozilla; 1.54 + 1.55 +/** 1.56 + * Helper function to invoke native SHA-1 function with JNI arguments. 1.57 + */ 1.58 +extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_sha1 1.59 + (JNIEnv *env, jclass jc, jbyteArray jstr) { 1.60 + jbyte *str = env->GetByteArrayElements(jstr, NULL); 1.61 + size_t strLen = env->GetArrayLength(jstr); 1.62 + 1.63 + SHA1Sum sha1; 1.64 + SHA1Sum::Hash hashResult; 1.65 + sha1.update((void *) str, (uint32_t) strLen); 1.66 + sha1.finish(hashResult); 1.67 + 1.68 + env->ReleaseByteArrayElements(jstr, str, JNI_ABORT); 1.69 + 1.70 + jbyteArray out = env->NewByteArray(SHA1Sum::HashSize); 1.71 + if (out == NULL) { 1.72 + return NULL; 1.73 + } 1.74 + env->SetByteArrayRegion(out, 0, SHA1Sum::HashSize, (jbyte *) hashResult); 1.75 + 1.76 + return out; 1.77 +}