michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "NativeCrypto.h" michael@0: michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "mozilla/SHA1.h" michael@0: #include "pbkdf2_sha256.h" michael@0: michael@0: /** michael@0: * Helper function to invoke native PBKDF2 function with JNI michael@0: * arguments. michael@0: */ michael@0: extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_pbkdf2SHA256 michael@0: (JNIEnv *env, jclass jc, jbyteArray jpassword, jbyteArray jsalt, jint c, jint dkLen) { michael@0: if (dkLen < 0) { michael@0: env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), michael@0: "dkLen should not be less than 0"); michael@0: return NULL; michael@0: } michael@0: michael@0: jbyte *password = env->GetByteArrayElements(jpassword, NULL); michael@0: size_t passwordLen = env->GetArrayLength(jpassword); michael@0: michael@0: jbyte *salt = env->GetByteArrayElements(jsalt, NULL); michael@0: size_t saltLen = env->GetArrayLength(jsalt); michael@0: michael@0: uint8_t hashResult[dkLen]; michael@0: PBKDF2_SHA256((uint8_t *) password, passwordLen, (uint8_t *) salt, saltLen, michael@0: (uint64_t) c, hashResult, (size_t) dkLen); michael@0: michael@0: env->ReleaseByteArrayElements(jpassword, password, JNI_ABORT); michael@0: env->ReleaseByteArrayElements(jsalt, salt, JNI_ABORT); michael@0: michael@0: jbyteArray out = env->NewByteArray(dkLen); michael@0: if (out == NULL) { michael@0: return NULL; michael@0: } michael@0: env->SetByteArrayRegion(out, 0, dkLen, (jbyte *) hashResult); michael@0: michael@0: return out; michael@0: } michael@0: michael@0: using namespace mozilla; michael@0: michael@0: /** michael@0: * Helper function to invoke native SHA-1 function with JNI arguments. michael@0: */ michael@0: extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_sha1 michael@0: (JNIEnv *env, jclass jc, jbyteArray jstr) { michael@0: jbyte *str = env->GetByteArrayElements(jstr, NULL); michael@0: size_t strLen = env->GetArrayLength(jstr); michael@0: michael@0: SHA1Sum sha1; michael@0: SHA1Sum::Hash hashResult; michael@0: sha1.update((void *) str, (uint32_t) strLen); michael@0: sha1.finish(hashResult); michael@0: michael@0: env->ReleaseByteArrayElements(jstr, str, JNI_ABORT); michael@0: michael@0: jbyteArray out = env->NewByteArray(SHA1Sum::HashSize); michael@0: if (out == NULL) { michael@0: return NULL; michael@0: } michael@0: env->SetByteArrayRegion(out, 0, SHA1Sum::HashSize, (jbyte *) hashResult); michael@0: michael@0: return out; michael@0: }