|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 #include "NativeCrypto.h" |
|
6 |
|
7 #include <jni.h> |
|
8 |
|
9 #include <errno.h> |
|
10 #include <stdlib.h> |
|
11 #include <inttypes.h> |
|
12 |
|
13 #include "mozilla/SHA1.h" |
|
14 #include "pbkdf2_sha256.h" |
|
15 |
|
16 /** |
|
17 * Helper function to invoke native PBKDF2 function with JNI |
|
18 * arguments. |
|
19 */ |
|
20 extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_pbkdf2SHA256 |
|
21 (JNIEnv *env, jclass jc, jbyteArray jpassword, jbyteArray jsalt, jint c, jint dkLen) { |
|
22 if (dkLen < 0) { |
|
23 env->ThrowNew(env->FindClass("java/lang/IllegalArgumentException"), |
|
24 "dkLen should not be less than 0"); |
|
25 return NULL; |
|
26 } |
|
27 |
|
28 jbyte *password = env->GetByteArrayElements(jpassword, NULL); |
|
29 size_t passwordLen = env->GetArrayLength(jpassword); |
|
30 |
|
31 jbyte *salt = env->GetByteArrayElements(jsalt, NULL); |
|
32 size_t saltLen = env->GetArrayLength(jsalt); |
|
33 |
|
34 uint8_t hashResult[dkLen]; |
|
35 PBKDF2_SHA256((uint8_t *) password, passwordLen, (uint8_t *) salt, saltLen, |
|
36 (uint64_t) c, hashResult, (size_t) dkLen); |
|
37 |
|
38 env->ReleaseByteArrayElements(jpassword, password, JNI_ABORT); |
|
39 env->ReleaseByteArrayElements(jsalt, salt, JNI_ABORT); |
|
40 |
|
41 jbyteArray out = env->NewByteArray(dkLen); |
|
42 if (out == NULL) { |
|
43 return NULL; |
|
44 } |
|
45 env->SetByteArrayRegion(out, 0, dkLen, (jbyte *) hashResult); |
|
46 |
|
47 return out; |
|
48 } |
|
49 |
|
50 using namespace mozilla; |
|
51 |
|
52 /** |
|
53 * Helper function to invoke native SHA-1 function with JNI arguments. |
|
54 */ |
|
55 extern "C" JNIEXPORT jbyteArray JNICALL Java_org_mozilla_gecko_background_nativecode_NativeCrypto_sha1 |
|
56 (JNIEnv *env, jclass jc, jbyteArray jstr) { |
|
57 jbyte *str = env->GetByteArrayElements(jstr, NULL); |
|
58 size_t strLen = env->GetArrayLength(jstr); |
|
59 |
|
60 SHA1Sum sha1; |
|
61 SHA1Sum::Hash hashResult; |
|
62 sha1.update((void *) str, (uint32_t) strLen); |
|
63 sha1.finish(hashResult); |
|
64 |
|
65 env->ReleaseByteArrayElements(jstr, str, JNI_ABORT); |
|
66 |
|
67 jbyteArray out = env->NewByteArray(SHA1Sum::HashSize); |
|
68 if (out == NULL) { |
|
69 return NULL; |
|
70 } |
|
71 env->SetByteArrayRegion(out, 0, SHA1Sum::HashSize, (jbyte *) hashResult); |
|
72 |
|
73 return out; |
|
74 } |