Merge pull request #53 from cconlon/synchronization

Add synchronization around native pointers (Md5/Sha/Des3/Hmac/Aes/DhKey/RsaKey/ecc_key)
pull/54/head
JacobBarthelmeh 2023-08-10 14:10:43 -06:00 committed by GitHub
commit 0c4ec4f6f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
54 changed files with 3761 additions and 714 deletions

View File

@ -23,34 +23,34 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Aes_DECRYPT_MODE 1L
/*
* Class: com_wolfssl_wolfcrypt_Aes
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Aes_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Aes_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Aes
* Method: native_set_key
* Method: native_set_key_internal
* Signature: ([B[BI)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1set_1key
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1set_1key_1internal
(JNIEnv *, jobject, jbyteArray, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Aes
* Method: native_update
* Method: native_update_internal
* Signature: (I[BII[BI)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1update__I_3BII_3BI
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1update_1internal__I_3BII_3BI
(JNIEnv *, jobject, jint, jbyteArray, jint, jint, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Aes
* Method: native_update
* Method: native_update_internal
* Signature: (ILjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;I)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1update__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Aes_native_1update_1internal__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jint, jobject, jint, jint, jobject, jint);
#ifdef __cplusplus

View File

@ -17,6 +17,30 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Des3_ENCRYPT_MODE 0L
#undef com_wolfssl_wolfcrypt_Des3_DECRYPT_MODE
#define com_wolfssl_wolfcrypt_Des3_DECRYPT_MODE 1L
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_set_key_internal
* Signature: ([B[BI)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1set_1key_1internal
(JNIEnv *, jobject, jbyteArray, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_update_internal
* Signature: (I[BII[BI)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1update_1internal__I_3BII_3BI
(JNIEnv *, jobject, jint, jbyteArray, jint, jint, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_update_internal
* Signature: (ILjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;I)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1update_1internal__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jint, jobject, jint, jint, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: mallocNativeStruct
@ -25,30 +49,6 @@ extern "C" {
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Des3_mallocNativeStruct
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_set_key
* Signature: ([B[BI)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1set_1key
(JNIEnv *, jobject, jbyteArray, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_update
* Signature: (I[BII[BI)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1update__I_3BII_3BI
(JNIEnv *, jobject, jint, jbyteArray, jint, jint, jbyteArray, jint);
/*
* Class: com_wolfssl_wolfcrypt_Des3
* Method: native_update
* Signature: (ILjava/nio/ByteBuffer;IILjava/nio/ByteBuffer;I)I
*/
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_Des3_native_1update__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jint, jobject, jint, jint, jobject, jint);
#ifdef __cplusplus
}
#endif

View File

@ -11,10 +11,10 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Dh_NULL 0LL
/*
* Class: com_wolfssl_wolfcrypt_Dh
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Dh_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Dh_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*

View File

@ -15,58 +15,58 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Md5_DIGEST_SIZE 16L
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Md5_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Md5_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_init
* Method: native_init_internal
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1init
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1init_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_copy
* Method: native_copy_internal
* Signature: (Lcom/wolfssl/wolfcrypt/Md5;)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1copy_1internal
(JNIEnv *, jobject, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_update
* Method: native_update_internal
* Signature: (Ljava/nio/ByteBuffer;II)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1update__Ljava_nio_ByteBuffer_2II
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1update_1internal__Ljava_nio_ByteBuffer_2II
(JNIEnv *, jobject, jobject, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_update
* Method: native_update_internal
* Signature: ([BII)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1update___3BII
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1update_1internal___3BII
(JNIEnv *, jobject, jbyteArray, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_final
* Method: native_final_internal
* Signature: (Ljava/nio/ByteBuffer;I)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1final__Ljava_nio_ByteBuffer_2I
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal__Ljava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Md5
* Method: native_final
* Method: native_final_internal
* Signature: ([B)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1final___3B
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal___3B
(JNIEnv *, jobject, jbyteArray);
#ifdef __cplusplus

View File

@ -15,58 +15,58 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Sha_DIGEST_SIZE 20L
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_init
* Method: native_init_internal
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1init
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1init_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_copy
* Method: native_copy_internal
* Signature: (Lcom/wolfssl/wolfcrypt/Sha;)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1copy_1internal
(JNIEnv *, jobject, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_update
* Method: native_update_internal
* Signature: (Ljava/nio/ByteBuffer;II)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1update__Ljava_nio_ByteBuffer_2II
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1update_1internal__Ljava_nio_ByteBuffer_2II
(JNIEnv *, jobject, jobject, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_update
* Method: native_update_internal
* Signature: ([BII)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1update___3BII
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1update_1internal___3BII
(JNIEnv *, jobject, jbyteArray, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_final
* Method: native_final_internal
* Signature: (Ljava/nio/ByteBuffer;I)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1final__Ljava_nio_ByteBuffer_2I
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1final_1internal__Ljava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha
* Method: native_final
* Method: native_final_internal
* Signature: ([B)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1final___3B
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1final_1internal___3B
(JNIEnv *, jobject, jbyteArray);
#ifdef __cplusplus

View File

@ -15,58 +15,58 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Sha256_DIGEST_SIZE 32L
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha256_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha256_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_init
* Method: native_init_internal
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1init
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1init_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_copy
* Method: native_copy_internal
* Signature: (Lcom/wolfssl/wolfcrypt/Sha256;)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1copy_1internal
(JNIEnv *, jobject, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_update
* Method: native_update_internal
* Signature: (Ljava/nio/ByteBuffer;II)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1update__Ljava_nio_ByteBuffer_2II
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1update_1internal__Ljava_nio_ByteBuffer_2II
(JNIEnv *, jobject, jobject, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_update
* Method: native_update_internal
* Signature: ([BII)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1update___3BII
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1update_1internal___3BII
(JNIEnv *, jobject, jbyteArray, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_final
* Method: native_final_internal
* Signature: (Ljava/nio/ByteBuffer;I)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1final__Ljava_nio_ByteBuffer_2I
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1final_1internal__Ljava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha256
* Method: native_final
* Method: native_final_internal
* Signature: ([B)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1final___3B
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1final_1internal___3B
(JNIEnv *, jobject, jbyteArray);
#ifdef __cplusplus

View File

@ -15,58 +15,58 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Sha384_DIGEST_SIZE 48L
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha384_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha384_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_init
* Method: native_init_internal
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1init
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1init_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_copy
* Method: native_copy_internal
* Signature: (Lcom/wolfssl/wolfcrypt/Sha384;)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1copy_1internal
(JNIEnv *, jobject, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_update
* Method: native_update_internal
* Signature: (Ljava/nio/ByteBuffer;II)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1update__Ljava_nio_ByteBuffer_2II
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1update_1internal__Ljava_nio_ByteBuffer_2II
(JNIEnv *, jobject, jobject, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_update
* Method: native_update_internal
* Signature: ([BII)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1update___3BII
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1update_1internal___3BII
(JNIEnv *, jobject, jbyteArray, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_final
* Method: native_final_internal
* Signature: (Ljava/nio/ByteBuffer;I)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1final__Ljava_nio_ByteBuffer_2I
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1final_1internal__Ljava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha384
* Method: native_final
* Method: native_final_internal
* Signature: ([B)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1final___3B
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1final_1internal___3B
(JNIEnv *, jobject, jbyteArray);
#ifdef __cplusplus

View File

@ -15,58 +15,58 @@ extern "C" {
#define com_wolfssl_wolfcrypt_Sha512_DIGEST_SIZE 64L
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: mallocNativeStruct
* Method: mallocNativeStruct_internal
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha512_mallocNativeStruct
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Sha512_mallocNativeStruct_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_init
* Method: native_init_internal
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1init
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1init_1internal
(JNIEnv *, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_copy
* Method: native_copy_internal
* Signature: (Lcom/wolfssl/wolfcrypt/Sha512;)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1copy_1internal
(JNIEnv *, jobject, jobject);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_update
* Method: native_update_internal
* Signature: (Ljava/nio/ByteBuffer;II)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1update__Ljava_nio_ByteBuffer_2II
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1update_1internal__Ljava_nio_ByteBuffer_2II
(JNIEnv *, jobject, jobject, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_update
* Method: native_update_internal
* Signature: ([BII)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1update___3BII
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1update_1internal___3BII
(JNIEnv *, jobject, jbyteArray, jint, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_final
* Method: native_final_internal
* Signature: (Ljava/nio/ByteBuffer;I)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1final__Ljava_nio_ByteBuffer_2I
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1final_1internal__Ljava_nio_ByteBuffer_2I
(JNIEnv *, jobject, jobject, jint);
/*
* Class: com_wolfssl_wolfcrypt_Sha512
* Method: native_final
* Method: native_final_internal
* Signature: ([B)V
*/
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1final___3B
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1final_1internal___3B
(JNIEnv *, jobject, jbyteArray);
#ifdef __cplusplus

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -33,31 +35,33 @@
/* #define WOLFCRYPT_JNI_DEBUG_ON */
#include <wolfcrypt_jni_debug.h>
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Aes_mallocNativeStruct(
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Aes_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
void* ret = NULL;
#ifndef NO_AES
ret = (void*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Aes* aes = NULL;
if (ret == NULL) {
aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (aes == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Aes object");
}
else {
XMEMSET(ret, 0, sizeof(Aes));
XMEMSET(aes, 0, sizeof(Aes));
}
LogStr("new Aes() = %p\n", ret);
LogStr("new Aes() = %p\n", aes);
return (jlong)(uintptr_t)aes;
#else
throwNotCompiledInException(env);
#endif
return (jlong)ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Aes_native_1set_1key(
Java_com_wolfssl_wolfcrypt_Aes_native_1set_1key_1internal(
JNIEnv* env, jobject this, jbyteArray key_object, jbyteArray iv_object,
jint opmode)
{
@ -96,7 +100,7 @@ Java_com_wolfssl_wolfcrypt_Aes_native_1set_1key(
}
JNIEXPORT jint JNICALL
Java_com_wolfssl_wolfcrypt_Aes_native_1update__I_3BII_3BI(
Java_com_wolfssl_wolfcrypt_Aes_native_1update_1internal__I_3BII_3BI(
JNIEnv* env, jobject this, jint opmode,
jbyteArray input_object, jint offset, jint length,
jbyteArray output_object, jint outputOffset)
@ -164,7 +168,7 @@ Java_com_wolfssl_wolfcrypt_Aes_native_1update__I_3BII_3BI(
}
JNIEXPORT jint JNICALL
Java_com_wolfssl_wolfcrypt_Aes_native_1update__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Aes_native_1update_1internal__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jint opmode,
jobject input_object, jint offset, jint length,
jobject output_object, jint outputOffset)

View File

@ -20,6 +20,7 @@
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -40,21 +41,26 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Chacha_mallocNativeStruct(
JNIEnv* env, jobject this)
{
void* ret = 0;
#ifdef HAVE_CHACHA
ret = (void*)XMALLOC(sizeof(ChaCha), NULL, DYNAMIC_TYPE_TMP_BUFFER);
ChaCha* chacha = NULL;
if (ret == NULL)
chacha = (ChaCha*)XMALLOC(sizeof(ChaCha), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (chacha == NULL) {
throwOutOfMemoryException(env, "Failed to allocate ChaCha object");
}
else {
XMEMSET(chacha, 0, sizeof(ChaCha));
}
LogStr("new ChaCha object allocated = %p\n", chacha);
return (jlong)(uintptr_t)chacha;
XMEMSET(ret, 0, sizeof(ChaCha));
LogStr("new ChaCha object allocated = %p\n", ret);
#else
throwNotCompiledInException(env);
#endif
return (jlong)(uintptr_t)ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Chacha_wc_1Chacha_1setIV
@ -162,6 +168,8 @@ Java_com_wolfssl_wolfcrypt_Chacha_wc_1Chacha_1process(
}
if (ret == 0) {
XMEMSET(output, 0, inputSz);
ret = wc_Chacha_Process(chacha, output, input, inputSz);
}

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -44,20 +46,26 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Curve25519_mallocNativeStruct(
JNIEnv* env, jobject this)
{
void* ret = 0;
#ifdef HAVE_CURVE25519
ret = XMALLOC(sizeof(curve25519_key), NULL, DYNAMIC_TYPE_TMP_BUFFER);
curve25519_key* key = NULL;
if (ret == NULL)
key = (curve25519_key*)XMALLOC(sizeof(curve25519_key), NULL,
DYNAMIC_TYPE_TMP_BUFFER);
if (key == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Curve25519 object");
}
else {
XMEMSET(key, 0, sizeof(curve25519_key));
}
LogStr("new Curve25519() = %p\n", (void*)ret);
LogStr("new Curve25519() = %p\n", key);
return (jlong)(uintptr_t)key;
#else
throwNotCompiledInException(env);
#endif
return (jlong) ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
@ -277,6 +285,7 @@ Java_com_wolfssl_wolfcrypt_Curve25519_wc_1curve25519_1export_1private(
throwOutOfMemoryException(env, "Failed to allocate key buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!curve25519)
? BAD_FUNC_ARG
@ -332,6 +341,7 @@ Java_com_wolfssl_wolfcrypt_Curve25519_wc_1curve25519_1export_1public (
throwOutOfMemoryException(env, "Failed to allocate key buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!curve25519)
? BAD_FUNC_ARG
@ -394,6 +404,7 @@ Java_com_wolfssl_wolfcrypt_Curve25519_wc_1curve25519_1make_1shared_1secret(
"Failed to allocate shared secret buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!curve25519 || !pub)
? BAD_FUNC_ARG

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -36,24 +38,29 @@
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Des3_mallocNativeStruct(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_DES3
ret = (jlong) XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Des3* des = NULL;
if (!ret)
des = (Des3*) XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (des == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Des3 object");
}
else {
XMEMSET(des, 0, sizeof(Des3));
}
LogStr("new Des3() = %p\n", (void*)ret);
LogStr("new Des3() = %p\n", des);
return (jlong)(uintptr_t)des;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Des3_native_1set_1key(
Java_com_wolfssl_wolfcrypt_Des3_native_1set_1key_1internal(
JNIEnv* env, jobject this, jbyteArray key_object, jbyteArray iv_object,
jint opmode)
{
@ -89,7 +96,7 @@ Java_com_wolfssl_wolfcrypt_Des3_native_1set_1key(
}
JNIEXPORT jint JNICALL
Java_com_wolfssl_wolfcrypt_Des3_native_1update__I_3BII_3BI(
Java_com_wolfssl_wolfcrypt_Des3_native_1update_1internal__I_3BII_3BI(
JNIEnv* env, jobject this, jint opmode,
jbyteArray input_object, jint offset, jint length,
jbyteArray output_object, jint outputOffset)
@ -156,7 +163,7 @@ Java_com_wolfssl_wolfcrypt_Des3_native_1update__I_3BII_3BI(
}
JNIEXPORT jint JNICALL
Java_com_wolfssl_wolfcrypt_Des3_native_1update__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Des3_native_1update_1internal__ILjava_nio_ByteBuffer_2IILjava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jint opmode,
jobject input_object, jint offset, jint length,
jobject output_object, jint outputOffset)

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -37,23 +39,29 @@
#define RNG WC_RNG
#endif
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Dh_mallocNativeStruct(
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Dh_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_DH
ret = (jlong) XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_TMP_BUFFER);
DhKey* dh = NULL;
if (!ret)
dh = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (dh == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Dh object");
}
else {
XMEMSET(dh, 0, sizeof(DhKey));
}
LogStr("new Dh() = %p\n", (void*)ret);
LogStr("new Dh() = %p\n", dh);
return (jlong)(uintptr_t)dh;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
@ -61,13 +69,17 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1InitDhKey(
JNIEnv* env, jobject this)
{
#ifndef NO_DH
int ret = 0;
DhKey* key = (DhKey*) getNativeStruct(env, this);
if ((*env)->ExceptionOccurred(env)) {
/* getNativeStruct may throw exception */
return;
}
wc_InitDhKey(key);
ret = wc_InitDhKey(key);
if (ret != 0) {
throwWolfCryptExceptionFromError(env, ret);
}
LogStr("wc_InitDhKey(key=%p)\n", key);
#else
@ -80,13 +92,17 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1FreeDhKey(
JNIEnv* env, jobject this)
{
#ifndef NO_DH
int ret = 0;
DhKey* key = (DhKey*) getNativeStruct(env, this);
if ((*env)->ExceptionOccurred(env)) {
/* getNativeStruct may throw exception */
return;
}
wc_FreeDhKey(key);
ret = wc_FreeDhKey(key);
if (ret != 0) {
throwWolfCryptExceptionFromError(env, ret);
}
LogStr("wc_FreeDhKey(key=%p)\n", key);
#else
@ -116,12 +132,16 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhSetKey(
g = getByteArray(env, g_object);
gSz = getByteArrayLength(env, g_object);
ret = (!key || !p || !g)
? BAD_FUNC_ARG
: wc_DhSetKey(key, p, pSz, g, gSz);
if (key == NULL || p == NULL || g == NULL) {
ret = BAD_FUNC_ARG;
}
else {
ret = wc_DhSetKey(key, p, pSz, g, gSz);
}
if (ret != 0)
if (ret != 0) {
throwWolfCryptExceptionFromError(env, ret);
}
LogStr("wc_DhSetKey(key=%p, p, pSz, g, gSz) = %d\n", key, ret);
LogStr("p[%u]: [%p]\n", (word32)pSz, p);
@ -164,26 +184,29 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhGenerateKeyPair(
return;
}
if (!key || !rng || (size < 0))
if (key == NULL || rng == NULL || (size < 0)) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
priv = XMALLOC(privSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (priv == NULL) {
throwOutOfMemoryException(env,
"Failed to allocate private key buffer");
"Failed to allocate private key buffer");
return;
}
XMEMSET(priv, 0, privSz);
pub = XMALLOC(pubSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (pub == NULL) {
XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
throwOutOfMemoryException(env,
"Failed to allocate public key buffer");
"Failed to allocate public key buffer");
return;
}
XMEMSET(pub, 0, pubSz);
ret = wc_DhGenerateKeyPair(key, rng, priv, &privSz, pub, &pubSz);
}
@ -191,11 +214,13 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhGenerateKeyPair(
if (ret == 0) {
/* keys should be positive, if leading bit is set, add zero byte */
if (priv[0] & 0x80)
if (priv[0] & 0x80) {
lBitPriv = 1;
}
if (pub[0] & 0x80)
if (pub[0] & 0x80) {
lBitPub = 1;
}
jbyteArray privateKey = (*env)->NewByteArray(env, lBitPriv + privSz);
jbyteArray publicKey = (*env)->NewByteArray(env, lBitPub + pubSz);
@ -219,6 +244,7 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhGenerateKeyPair(
} else {
throwWolfCryptException(env, "Failed to allocate privateKey");
exceptionThrown = 1;
}
if (publicKey && (exceptionThrown == 0)) {
@ -247,10 +273,14 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhGenerateKeyPair(
LogStr("public[%u]: [%p]\n", pubSz, pub);
LogHex(pub, 0, pubSz);
if (priv)
if (priv != NULL) {
XMEMSET(priv, 0, privSz);
XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (pub)
}
if (pub != NULL) {
XMEMSET(pub, 0, pubSz);
XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
}
#else
throwNotCompiledInException(env);
#endif
@ -275,12 +305,16 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhCheckPubKey(
pub = getByteArray(env, pub_object);
pubSz = getByteArrayLength(env, pub_object);
ret = (!key || !pub)
? BAD_FUNC_ARG
: wc_DhCheckPubKey(key, pub, pubSz);
if (key == NULL || pub == NULL) {
ret = BAD_FUNC_ARG;
}
else {
ret = wc_DhCheckPubKey(key, pub, pubSz);
}
if (ret != 0)
if (ret != 0) {
throwWolfCryptExceptionFromError(env, ret);
}
LogStr("wc_DhCheckPubKey(key=%p, pub, pubSz) = %d\n", key, ret);
LogStr("p[%u]: [%p]\n", (word32)pubSz, pub);
@ -327,10 +361,14 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhAgree(
return result;
}
XMEMSET(secret, 0, pubSz);
ret = (!key || !priv || !pub)
? BAD_FUNC_ARG
: wc_DhAgree(key, secret, &secretSz, priv, privSz, pub, pubSz);
if (key == NULL || priv == NULL || pub == NULL) {
ret = BAD_FUNC_ARG;
}
else {
ret = wc_DhAgree(key, secret, &secretSz, priv, privSz, pub, pubSz);
}
if (ret == 0) {
result = (*env)->NewByteArray(env, secretSz);
@ -350,7 +388,10 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhAgree(
LogStr("secret[%u]: [%p]\n", secretSz, secret);
LogHex(secret, 0, secretSz);
XFREE(secret, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (secret != NULL) {
XMEMSET(secret, 0, secretSz);
XFREE(secret, NULL, DYNAMIC_TYPE_TMP_BUFFER);
}
releaseByteArray(env, priv_object, priv, JNI_ABORT);
releaseByteArray(env, pub_object, pub, JNI_ABORT);
@ -360,3 +401,4 @@ Java_com_wolfssl_wolfcrypt_Dh_wc_1DhAgree(
return result;
}

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -44,24 +46,25 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Ecc_mallocNativeStruct(
JNIEnv* env, jobject this)
{
void* ret = NULL;
#ifdef HAVE_ECC
ret = (void*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_TMP_BUFFER);
ecc_key* ecc = NULL;
if (ret == NULL) {
ecc = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (ecc == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Ecc object");
}
else {
XMEMSET(ret, 0, sizeof(ecc_key));
XMEMSET(ecc, 0, sizeof(ecc_key));
}
LogStr("new Ecc() = %p\n", (void*)ret);
LogStr("new Ecc() = %p\n", ecc);
return (jlong)(uintptr_t)ecc;
#else
throwNotCompiledInException(env);
#endif
return (jlong) ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -44,20 +46,25 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Ed25519_mallocNativeStruct(
JNIEnv* env, jobject this)
{
void* ret = 0;
#ifdef HAVE_ED25519
ret = XMALLOC(sizeof(ed25519_key), NULL, DYNAMIC_TYPE_TMP_BUFFER);
ed25519_key* key = NULL;
if (ret == NULL)
key = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (key == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Ed25519 object");
}
else {
XMEMSET(key, 0, sizeof(ed25519_key));
}
LogStr("new Ed25519() = %p\n", (void*)ret);
LogStr("new Ed25519() = %p\n", key);
return (jlong)(uintptr_t)key;
#else
throwNotCompiledInException(env);
#endif
return (jlong) ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
@ -303,6 +310,7 @@ Java_com_wolfssl_wolfcrypt_Ed25519_wc_1ed25519_1export_1private(
throwOutOfMemoryException(env, "Failed to allocate key buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!ed25519)
? BAD_FUNC_ARG
@ -358,6 +366,7 @@ Java_com_wolfssl_wolfcrypt_Ed25519_wc_1ed25519_1export_1private_1only(
throwOutOfMemoryException(env, "Failed to allocate key buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!ed25519)
? BAD_FUNC_ARG
@ -413,6 +422,7 @@ Java_com_wolfssl_wolfcrypt_Ed25519_wc_1ed25519_1export_1public(
throwOutOfMemoryException(env, "Failed to allocate key buffer");
return result;
}
XMEMSET(output, 0, outputSz);
ret = (!ed25519)
? BAD_FUNC_ARG
@ -460,13 +470,23 @@ JNIEXPORT jbyteArray JNICALL Java_com_wolfssl_wolfcrypt_Ed25519_wc_1ed25519_1sig
/* getNativeStruct may throw exception, prevent throwing another */
return NULL;
}
msg = getByteArray(env, msg_in);
len = getByteArrayLength(env, msg_in);
output = XMALLOC(outlen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (!ed25519) {
if (ed25519 == NULL) {
ret = BAD_FUNC_ARG;
} else {
}
if (ret == 0) {
msg = getByteArray(env, msg_in);
len = getByteArrayLength(env, msg_in);
output = XMALLOC(outlen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (output == NULL) {
ret = MEMORY_E;
}
}
if (ret == 0) {
XMEMSET(output, 0, outlen);
ret = wc_ed25519_sign_msg(msg, len, output, &outlen, ed25519);
}

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -104,20 +106,26 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Hmac_mallocNativeStruct(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_HMAC
ret = (jlong) XMALLOC(sizeof(Hmac), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Hmac* hmac = NULL;
if (!ret)
hmac = (Hmac*) XMALLOC(sizeof(Hmac), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (hmac == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Hmac object");
}
else {
XMEMSET(hmac, 0, sizeof(Hmac));
}
LogStr("new Hmac() = %p\n", hmac);
return (jlong)(uintptr_t)hmac;
LogStr("new Hmac() = %p\n", (void*)ret);
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL

View File

@ -20,6 +20,7 @@
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -47,27 +48,32 @@
#endif
JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Md5_mallocNativeStruct(
Java_com_wolfssl_wolfcrypt_Md5_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_MD5
ret = (jlong)(uintptr_t)XMALLOC(sizeof(Md5), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Md5* md5 = NULL;
if (!ret)
md5 = (Md5*)XMALLOC(sizeof(Md5), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (md5 == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Md5 object");
}
else {
XMEMSET(md5, 0, sizeof(Md5));
}
LogStr("new Md5() = %p\n", (void*)ret);
LogStr("new Md5() = %p\n", md5);
return (jlong)(uintptr_t)md5;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Md5_native_1init(
Java_com_wolfssl_wolfcrypt_Md5_native_1init_1internal(
JNIEnv* env, jobject this)
{
#ifndef NO_MD5
@ -91,7 +97,7 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1init(
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1copy_1internal
(JNIEnv* env, jobject this, jobject toBeCopied)
{
#ifndef NO_MD5
@ -125,7 +131,7 @@ JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Md5_native_1copy
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Md5_native_1update__Ljava_nio_ByteBuffer_2II(
Java_com_wolfssl_wolfcrypt_Md5_native_1update_1internal__Ljava_nio_ByteBuffer_2II(
JNIEnv* env, jobject this, jobject data_buffer, jint position, jint len)
{
#ifndef NO_MD5
@ -159,7 +165,7 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1update__Ljava_nio_ByteBuffer_2II(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Md5_native_1update___3BII(
Java_com_wolfssl_wolfcrypt_Md5_native_1update_1internal___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset, jint len)
{
#ifndef NO_MD5
@ -198,7 +204,7 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1update___3BII(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Md5_native_1final__Ljava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jobject hash_buffer, jint position)
{
#ifndef NO_MD5
@ -232,7 +238,7 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1final__Ljava_nio_ByteBuffer_2I(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Md5_native_1final___3B(
Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal___3B(
JNIEnv* env, jobject this, jbyteArray hash_buffer)
{
#ifndef NO_MD5

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -43,20 +45,25 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Rng_mallocNativeStruct(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef WC_NO_RNG
ret = (jlong) XMALLOC(sizeof(RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER);
RNG* rng = NULL;
if (!ret)
rng = (RNG*)XMALLOC(sizeof(RNG), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (rng == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Rng object");
}
else {
XMEMSET(rng, 0, sizeof(RNG));
}
LogStr("new Rng() = %p\n", (void*)ret);
LogStr("new Rng() = %p\n", rng);
return (jlong)(uintptr_t)rng;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -45,23 +47,25 @@ JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Rsa_mallocNativeStruct(
JNIEnv* env, jobject this)
{
void* ret = NULL;
#ifndef NO_RSA
ret = (void*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (ret == NULL) {
RsaKey* rsa = NULL;
rsa = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (rsa == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Rsa object");
}
else {
XMEMSET(ret, 0, sizeof(RsaKey));
XMEMSET(rsa, 0, sizeof(RsaKey));
}
LogStr("new Rsa() = %p\n", (void*)ret);
LogStr("new Rsa() = %p\n", rsa);
return (jlong)(uintptr_t)rsa;
#else
throwNotCompiledInException(env);
#endif
return (jlong)ret;
return (jlong)0;
#endif
}
JNIEXPORT jlong JNICALL Java_com_wolfssl_wolfcrypt_Rsa_getDefaultRsaExponent
@ -366,6 +370,8 @@ JNIEXPORT jbyteArray JNICALL Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaKeyToDer
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaKeyToDer(key, output, outputSz);
if (ret > 0) {
outputSz = ret;
@ -441,6 +447,8 @@ JNIEXPORT jbyteArray JNICALL Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaKeyToPublicDe
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaKeyToPublicDer(key, output, outputSz);
if (ret > 0) {
outputSz = ret;
@ -898,6 +906,8 @@ Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaPublicEncrypt(
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaPublicEncrypt(plaintext, size, output, outputSz, key, rng);
if (ret > 0) {
outputSz = ret;
@ -974,6 +984,8 @@ Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaPrivateDecrypt(
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaPrivateDecrypt(ciphertext, size, output, outputSz, key);
if (ret > 0) {
outputSz = ret;
@ -1057,6 +1069,8 @@ Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaSSL_1Sign(
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaSSL_Sign(data, size, output, outputSz, key, rng);
if (ret > 0) {
outputSz = ret;
@ -1133,6 +1147,8 @@ Java_com_wolfssl_wolfcrypt_Rsa_wc_1RsaSSL_1Verify(
}
if (ret == 0) {
XMEMSET(output, 0, outputSz);
ret = wc_RsaSSL_Verify(signature, size, output, outputSz, key);
if (ret > 0) {
outputSz = ret;

View File

@ -19,6 +19,8 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdint.h>
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#elif !defined(__ANDROID__)
@ -64,87 +66,107 @@
#endif
JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Sha_mallocNativeStruct(
Java_com_wolfssl_wolfcrypt_Sha_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_SHA
ret = (jlong) XMALLOC(sizeof(Sha), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Sha* sha = NULL;
if (!ret)
sha = (Sha*) XMALLOC(sizeof(Sha), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (sha == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Sha object");
}
else {
XMEMSET(sha, 0, sizeof(Sha));
}
LogStr("new Sha() = %p\n", (void*)ret);
LogStr("new Sha() = %p\n", sha);
return (jlong)(uintptr_t)sha;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_mallocNativeStruct(
Java_com_wolfssl_wolfcrypt_Sha256_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifndef NO_SHA256
ret = (jlong) XMALLOC(sizeof(Sha256), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Sha256* sha = NULL;
if (!ret)
sha = (Sha256*) XMALLOC(sizeof(Sha256), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (sha == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Sha256 object");
}
else {
XMEMSET(sha, 0, sizeof(Sha256));
}
LogStr("new Sha256() = %p\n", (void*)ret);
LogStr("new Sha256() = %p\n", sha);
return (jlong)(uintptr_t)sha;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_mallocNativeStruct(
Java_com_wolfssl_wolfcrypt_Sha384_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifdef WOLFSSL_SHA384
ret = (jlong) XMALLOC(sizeof(Sha384), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Sha384* sha = NULL;
if (!ret)
sha = (Sha384*) XMALLOC(sizeof(Sha384), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (sha == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Sha384 object");
}
else {
XMEMSET(sha, 0, sizeof(Sha384));
}
LogStr("new Sha384() = %p\n", (void*)ret);
LogStr("new Sha384() = %p\n", sha);
return (jlong)(uintptr_t)sha;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT jlong JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_mallocNativeStruct(
Java_com_wolfssl_wolfcrypt_Sha512_mallocNativeStruct_1internal(
JNIEnv* env, jobject this)
{
jlong ret = 0;
#ifdef WOLFSSL_SHA512
ret = (jlong) XMALLOC(sizeof(Sha512), NULL, DYNAMIC_TYPE_TMP_BUFFER);
Sha512* sha = NULL;
if (!ret)
sha = (Sha512*) XMALLOC(sizeof(Sha512), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (sha == NULL) {
throwOutOfMemoryException(env, "Failed to allocate Sha512 object");
}
else {
XMEMSET(sha, 0, sizeof(Sha512));
}
LogStr("new Sha512() = %p\n", (void*)ret);
LogStr("new Sha512() = %p\n", sha);
return (jlong)(uintptr_t)sha;
#else
throwNotCompiledInException(env);
#endif
return ret;
return (jlong)0;
#endif
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha_native_1init(
Java_com_wolfssl_wolfcrypt_Sha_native_1init_1internal(
JNIEnv* env, jobject this)
{
#ifndef NO_SHA
@ -166,7 +188,7 @@ Java_com_wolfssl_wolfcrypt_Sha_native_1init(
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1copy_1internal
(JNIEnv* env, jobject this, jobject toBeCopied)
{
#ifndef NO_SHA
@ -200,7 +222,7 @@ JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha_native_1copy
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha_native_1update__Ljava_nio_ByteBuffer_2II(
Java_com_wolfssl_wolfcrypt_Sha_native_1update_1internal__Ljava_nio_ByteBuffer_2II(
JNIEnv* env, jobject this, jobject data_buffer, jint position, jint len)
{
#ifndef NO_SHA
@ -232,7 +254,7 @@ Java_com_wolfssl_wolfcrypt_Sha_native_1update__Ljava_nio_ByteBuffer_2II(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha_native_1update___3BII(
Java_com_wolfssl_wolfcrypt_Sha_native_1update_1internal___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset, jint len)
{
#ifndef NO_SHA
@ -272,7 +294,7 @@ Java_com_wolfssl_wolfcrypt_Sha_native_1update___3BII(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha_native_1final__Ljava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Sha_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jobject hash_buffer, jint position)
{
#ifndef NO_SHA
@ -304,7 +326,7 @@ Java_com_wolfssl_wolfcrypt_Sha_native_1final__Ljava_nio_ByteBuffer_2I(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha_native_1final___3B(
Java_com_wolfssl_wolfcrypt_Sha_native_1final_1internal___3B(
JNIEnv* env, jobject this, jbyteArray hash_buffer)
{
#ifndef NO_SHA
@ -338,7 +360,7 @@ Java_com_wolfssl_wolfcrypt_Sha_native_1final___3B(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_native_1init(
Java_com_wolfssl_wolfcrypt_Sha256_native_1init_1internal(
JNIEnv* env, jobject this)
{
#ifndef NO_SHA256
@ -360,7 +382,7 @@ Java_com_wolfssl_wolfcrypt_Sha256_native_1init(
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1copy_1internal
(JNIEnv* env, jobject this, jobject toBeCopied)
{
#ifndef NO_SHA256
@ -394,7 +416,7 @@ JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha256_native_1copy
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_native_1update__Ljava_nio_ByteBuffer_2II(
Java_com_wolfssl_wolfcrypt_Sha256_native_1update_1internal__Ljava_nio_ByteBuffer_2II(
JNIEnv* env, jobject this, jobject data_buffer, jint position, jint len)
{
#ifndef NO_SHA256
@ -426,9 +448,9 @@ Java_com_wolfssl_wolfcrypt_Sha256_native_1update__Ljava_nio_ByteBuffer_2II(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_native_1update___3BII(
Java_com_wolfssl_wolfcrypt_Sha256_native_1update_1internal___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset,
jint len)
jint len)
{
#ifndef NO_SHA256
int ret = 0;
@ -468,7 +490,7 @@ Java_com_wolfssl_wolfcrypt_Sha256_native_1update___3BII(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_native_1final__Ljava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Sha256_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jobject hash_buffer, jint position)
{
#ifndef NO_SHA256
@ -500,7 +522,7 @@ Java_com_wolfssl_wolfcrypt_Sha256_native_1final__Ljava_nio_ByteBuffer_2I(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha256_native_1final___3B(
Java_com_wolfssl_wolfcrypt_Sha256_native_1final_1internal___3B(
JNIEnv* env, jobject this, jbyteArray hash_buffer)
{
#ifndef NO_SHA256
@ -534,7 +556,7 @@ Java_com_wolfssl_wolfcrypt_Sha256_native_1final___3B(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_native_1init(
Java_com_wolfssl_wolfcrypt_Sha384_native_1init_1internal(
JNIEnv* env, jobject this)
{
#ifdef WOLFSSL_SHA384
@ -556,7 +578,7 @@ Java_com_wolfssl_wolfcrypt_Sha384_native_1init(
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1copy_1internal
(JNIEnv* env, jobject this, jobject toBeCopied)
{
#ifdef WOLFSSL_SHA384
@ -590,7 +612,7 @@ JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha384_native_1copy
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_native_1update__Ljava_nio_ByteBuffer_2II(
Java_com_wolfssl_wolfcrypt_Sha384_native_1update_1internal__Ljava_nio_ByteBuffer_2II(
JNIEnv* env, jobject this, jobject data_buffer, jint position, jint len)
{
#ifdef WOLFSSL_SHA384
@ -622,9 +644,8 @@ Java_com_wolfssl_wolfcrypt_Sha384_native_1update__Ljava_nio_ByteBuffer_2II(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_native_1update___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset,
jint len)
Java_com_wolfssl_wolfcrypt_Sha384_native_1update_1internal___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset, jint len)
{
#ifdef WOLFSSL_SHA384
int ret = 0;
@ -664,7 +685,7 @@ Java_com_wolfssl_wolfcrypt_Sha384_native_1update___3BII(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_native_1final__Ljava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Sha384_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jobject hash_buffer, jint position)
{
#ifdef WOLFSSL_SHA384
@ -696,7 +717,7 @@ Java_com_wolfssl_wolfcrypt_Sha384_native_1final__Ljava_nio_ByteBuffer_2I(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha384_native_1final___3B(
Java_com_wolfssl_wolfcrypt_Sha384_native_1final_1internal___3B(
JNIEnv* env, jobject this, jbyteArray hash_buffer)
{
#ifdef WOLFSSL_SHA384
@ -730,7 +751,7 @@ Java_com_wolfssl_wolfcrypt_Sha384_native_1final___3B(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_native_1init(
Java_com_wolfssl_wolfcrypt_Sha512_native_1init_1internal(
JNIEnv* env, jobject this)
{
#ifdef WOLFSSL_SHA512
@ -752,7 +773,7 @@ Java_com_wolfssl_wolfcrypt_Sha512_native_1init(
#endif
}
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1copy
JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1copy_1internal
(JNIEnv* env, jobject this, jobject toBeCopied)
{
#ifdef WOLFSSL_SHA512
@ -786,7 +807,7 @@ JNIEXPORT void JNICALL Java_com_wolfssl_wolfcrypt_Sha512_native_1copy
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_native_1update__Ljava_nio_ByteBuffer_2II(
Java_com_wolfssl_wolfcrypt_Sha512_native_1update_1internal__Ljava_nio_ByteBuffer_2II(
JNIEnv* env, jobject this, jobject data_buffer, jint position, jint len)
{
#ifdef WOLFSSL_SHA512
@ -818,9 +839,9 @@ Java_com_wolfssl_wolfcrypt_Sha512_native_1update__Ljava_nio_ByteBuffer_2II(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_native_1update___3BII(
Java_com_wolfssl_wolfcrypt_Sha512_native_1update_1internal___3BII(
JNIEnv* env, jobject this, jbyteArray data_buffer, jint offset,
jint len)
jint len)
{
#ifdef WOLFSSL_SHA512
int ret = 0;
@ -860,7 +881,7 @@ Java_com_wolfssl_wolfcrypt_Sha512_native_1update___3BII(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_native_1final__Ljava_nio_ByteBuffer_2I(
Java_com_wolfssl_wolfcrypt_Sha512_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
JNIEnv* env, jobject this, jobject hash_buffer, jint position)
{
#ifdef WOLFSSL_SHA512
@ -892,7 +913,7 @@ Java_com_wolfssl_wolfcrypt_Sha512_native_1final__Ljava_nio_ByteBuffer_2I(
}
JNIEXPORT void JNICALL
Java_com_wolfssl_wolfcrypt_Sha512_native_1final___3B(
Java_com_wolfssl_wolfcrypt_Sha512_native_1final_1internal___3B(
JNIEnv* env, jobject this, jbyteArray hash_buffer)
{
#ifdef WOLFSSL_SHA512

View File

@ -47,6 +47,17 @@ public class Aes extends BlockCipher {
private int opmode;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_set_key_internal(byte[] key, byte[] iv,
int opmode);
private native int native_update_internal(int opmode, byte[] input,
int offset, int length, byte[] output, int outputOffset);
private native int native_update_internal(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset);
/**
* Malloc native JNI AES structure
*
@ -54,7 +65,13 @@ public class Aes extends BlockCipher {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Set native AES key
@ -64,7 +81,12 @@ public class Aes extends BlockCipher {
* @param opmode AES mode, either Aes.ENCRYPT_MODE or
* Aes.DECRYPT_MODE
*/
protected native void native_set_key(byte[] key, byte[] iv, int opmode);
protected void native_set_key(byte[] key, byte[] iv, int opmode) {
synchronized (pointerLock) {
native_set_key_internal(key, iv, opmode);
}
}
/**
* Native AES encrypt/decrypt update operation
@ -79,8 +101,14 @@ public class Aes extends BlockCipher {
*
* @return number of bytes stored in output
*/
protected native int native_update(int opmode, byte[] input, int offset,
int length, byte[] output, int outputOffset);
protected int native_update(int opmode, byte[] input, int offset,
int length, byte[] output, int outputOffset) {
synchronized (pointerLock) {
return native_update_internal(opmode, input, offset, length,
output, outputOffset);
}
}
/**
* Native AES encrypt/decrypt update operation
@ -95,8 +123,14 @@ public class Aes extends BlockCipher {
*
* @return number of bytes stored in output
*/
protected native int native_update(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset);
protected int native_update(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset) {
synchronized (pointerLock) {
return native_update_internal(opmode, input, offset, length,
output, outputOffset);
}
}
/**
* Create new Aes object

View File

@ -84,7 +84,8 @@ public abstract class BlockCipher extends NativeStruct {
* @param iv block cipher initialization vector (IV) array
* @param opmode block cipher operation mode, dependent on subclass type
*/
public void setKey(byte[] key, byte[] iv, int opmode) {
public synchronized void setKey(byte[] key, byte[] iv, int opmode) {
native_set_key(key, iv, opmode);
this.opmode = opmode;
@ -96,7 +97,8 @@ public abstract class BlockCipher extends NativeStruct {
*
* @throws IllegalStateException if algorithm or key not usable
*/
public void willUseKey() {
public synchronized void willUseKey() {
if (state != WolfCryptState.READY)
throw new IllegalStateException(
"No available key to perform the opperation.");
@ -109,7 +111,8 @@ public abstract class BlockCipher extends NativeStruct {
*
* @return output data array from update operation
*/
public byte[] update(byte[] input) {
public synchronized byte[] update(byte[] input) {
return update(input, 0, input.length);
}
@ -122,7 +125,8 @@ public abstract class BlockCipher extends NativeStruct {
*
* @return output data array from update operation
*/
public byte[] update(byte[] input, int offset, int length) {
public synchronized byte[] update(byte[] input, int offset, int length) {
willUseKey();
byte[] output = new byte[input.length];
@ -145,8 +149,9 @@ public abstract class BlockCipher extends NativeStruct {
*
* @throws ShortBufferException if output buffer is too small
*/
public int update(byte[] input, int offset, int length, byte[] output,
int outputOffset) throws ShortBufferException {
public synchronized int update(byte[] input, int offset, int length,
byte[] output, int outputOffset) throws ShortBufferException {
willUseKey();
if (outputOffset + length > output.length)
@ -167,8 +172,9 @@ public abstract class BlockCipher extends NativeStruct {
*
* @throws ShortBufferException if output buffer is not large enough
*/
public int update(ByteBuffer input, ByteBuffer output)
throws ShortBufferException {
public synchronized int update(ByteBuffer input, ByteBuffer output)
throws ShortBufferException {
willUseKey();
int ret = 0;
@ -187,7 +193,7 @@ public abstract class BlockCipher extends NativeStruct {
}
@Override
public void releaseNativeStruct() {
public synchronized void releaseNativeStruct() {
/* reset state first, then free */
state = WolfCryptState.UNINITIALIZED;
@ -203,7 +209,8 @@ public abstract class BlockCipher extends NativeStruct {
* @return Number of PKCS#7 pad bytes that would be appended to an input
* of size inputSize.
*/
public static int getPKCS7PadSize(int inputSize, int blockSize) {
public static synchronized int getPKCS7PadSize(int inputSize,
int blockSize) {
int padSz = 0;
@ -228,7 +235,7 @@ public abstract class BlockCipher extends NativeStruct {
* @throws WolfCryptException if input is null, zero length,
* or blockSize is invalid
*/
public static byte[] padPKCS7(byte[] in, int blockSize)
public static synchronized byte[] padPKCS7(byte[] in, int blockSize)
throws WolfCryptException {
int padSz = 0;
@ -268,7 +275,7 @@ public abstract class BlockCipher extends NativeStruct {
* @throws WolfCryptException if input is null, zero length,
* or blockSize is invalid
*/
public static byte[] unPadPKCS7(byte[] in, int blockSize) {
public static synchronized byte[] unPadPKCS7(byte[] in, int blockSize) {
byte padValue = 0;
byte[] unpadded = null;

View File

@ -40,6 +40,16 @@ public class Des3 extends BlockCipher {
private WolfCryptState state = WolfCryptState.UNINITIALIZED;
private int opmode;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native void native_set_key_internal(byte[] key, byte[] iv,
int opmode);
private native int native_update_internal(int opmode, byte[] input,
int offset, int length, byte[] output, int outputOffset);
private native int native_update_internal(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset);
/**
* Malloc native JNI Des3 structure
*
@ -57,7 +67,12 @@ public class Des3 extends BlockCipher {
* @param opmode 3DES mode, either Des3.ENCRYPT_MODE or
* Des3.DECRYPT_MODE
*/
protected native void native_set_key(byte[] key, byte[] iv, int opmode);
protected void native_set_key(byte[] key, byte[] iv, int opmode) {
synchronized (pointerLock) {
native_set_key_internal(key, iv, opmode);
}
}
/**
* Native Des3 encrypt/decrypt update operation
@ -72,8 +87,14 @@ public class Des3 extends BlockCipher {
*
* @return number of bytes stored in output
*/
protected native int native_update(int opmode, byte[] input, int offset,
int length, byte[] output, int outputOffset);
protected int native_update(int opmode, byte[] input, int offset,
int length, byte[] output, int outputOffset) {
synchronized (pointerLock) {
return native_update_internal(opmode, input, offset, length,
output, outputOffset);
}
}
/**
* Native Des3 encrypt/decrypt update operation
@ -88,8 +109,14 @@ public class Des3 extends BlockCipher {
*
* @return number of bytes stored in output
*/
protected native int native_update(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset);
protected int native_update(int opmode, ByteBuffer input,
int offset, int length, ByteBuffer output, int outputOffset) {
synchronized (pointerLock) {
return native_update_internal(opmode, input, offset, length,
output, outputOffset);
}
}
/**
* Create new Des3 object

View File

@ -31,6 +31,9 @@ public class Dh extends NativeStruct {
private byte[] publicKey = null;
private int pSize = 0;
/* Lock around object state */
protected final Object stateLock = new Object();
/**
* Create new Dh object
*/
@ -50,12 +53,19 @@ public class Dh extends NativeStruct {
}
@Override
public void releaseNativeStruct() {
public synchronized void releaseNativeStruct() {
free();
super.releaseNativeStruct();
}
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void wc_InitDhKey();
private native void wc_FreeDhKey();
private native void wc_DhSetKey(byte[] p, byte[] g);
private native void wc_DhGenerateKeyPair(Rng rng, int pSize);
private native byte[] wc_DhAgree(byte[] priv, byte[] pub);
/**
* Malloc native JNI DH structure
*
@ -63,34 +73,46 @@ public class Dh extends NativeStruct {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
private native void wc_InitDhKey();
private native void wc_FreeDhKey();
private native void wc_DhSetKey(byte[] p, byte[] g);
private native void wc_DhGenerateKeyPair(Rng rng, int pSize);
private native byte[] wc_DhAgree(byte[] priv, byte[] pub);
/** Initialize Dh object */
protected void init() {
if (state == WolfCryptState.UNINITIALIZED) {
wc_InitDhKey();
state = WolfCryptState.INITIALIZED;
} else {
throw new IllegalStateException(
"Native resources already initialized.");
synchronized (stateLock) {
if (state == WolfCryptState.UNINITIALIZED) {
synchronized (pointerLock) {
wc_InitDhKey();
}
state = WolfCryptState.INITIALIZED;
} else {
throw new IllegalStateException(
"Native resources already initialized");
}
}
}
/** Free Dh object */
protected void free() {
if (state != WolfCryptState.UNINITIALIZED) {
wc_FreeDhKey();
protected synchronized void free() {
setPrivateKey(new byte[0]);
setPublicKey(new byte[0]);
synchronized (stateLock) {
if (state != WolfCryptState.UNINITIALIZED) {
state = WolfCryptState.UNINITIALIZED;
synchronized (pointerLock) {
wc_FreeDhKey();
}
setPrivateKey(new byte[0]);
setPublicKey(new byte[0]);
state = WolfCryptState.UNINITIALIZED;
}
}
}
@ -101,16 +123,22 @@ public class Dh extends NativeStruct {
*
* @throws IllegalStateException if object uninitialized
*/
public void setPrivateKey(byte[] priv) {
if (state != WolfCryptState.UNINITIALIZED) {
if (privateKey != null)
for (int i = 0; i < privateKey.length; i++)
privateKey[i] = 0;
public synchronized void setPrivateKey(byte[] priv)
throws IllegalStateException {
privateKey = priv.clone();
} else {
throw new IllegalStateException(
"No available parameters to perform opetarion.");
synchronized (stateLock) {
if (state != WolfCryptState.UNINITIALIZED) {
if (privateKey != null) {
for (int i = 0; i < privateKey.length; i++) {
privateKey[i] = 0;
}
}
privateKey = priv.clone();
} else {
throw new IllegalStateException(
"No available parameters to perform operation");
}
}
}
@ -121,16 +149,21 @@ public class Dh extends NativeStruct {
*
* @throws IllegalStateException if object uninitialized
*/
public void setPublicKey(byte[] pub) {
if (state != WolfCryptState.UNINITIALIZED) {
if (publicKey != null)
for (int i = 0; i < publicKey.length; i++)
publicKey[i] = 0;
public synchronized void setPublicKey(byte[] pub) {
publicKey = pub.clone();
} else {
throw new IllegalStateException(
"No available parameters to perform opetarion.");
synchronized (stateLock) {
if (state != WolfCryptState.UNINITIALIZED) {
if (publicKey != null) {
for (int i = 0; i < publicKey.length; i++) {
publicKey[i] = 0;
}
}
publicKey = pub.clone();
} else {
throw new IllegalStateException(
"No available parameters to perform operation");
}
}
}
@ -139,7 +172,7 @@ public class Dh extends NativeStruct {
*
* @return public key as byte array
*/
public byte[] getPublicKey() {
public synchronized byte[] getPublicKey() {
return publicKey;
}
@ -148,7 +181,7 @@ public class Dh extends NativeStruct {
*
* @return private key as byte array
*/
public byte[] getPrivateKey() {
public synchronized byte[] getPrivateKey() {
return privateKey;
}
@ -161,13 +194,21 @@ public class Dh extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already initialized
*/
public void setParams(byte[] p, byte[] g) {
if (state == WolfCryptState.INITIALIZED) {
wc_DhSetKey(p, g);
this.pSize = p.length;
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has parameters.");
public synchronized void setParams(byte[] p, byte[] g)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_DhSetKey(p, g);
}
this.pSize = p.length;
state = WolfCryptState.READY;
} else {
throw new IllegalStateException(
"Object already has parameters");
}
}
}
@ -179,12 +220,16 @@ public class Dh extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void makeKey(Rng rng) {
public synchronized void makeKey(Rng rng)
throws WolfCryptException, IllegalStateException {
if (privateKey == null) {
/* use size of P to allocate key buffer size */
wc_DhGenerateKeyPair(rng, this.pSize);
synchronized (pointerLock) {
wc_DhGenerateKeyPair(rng, this.pSize);
}
} else {
throw new IllegalStateException("Object already has a key.");
throw new IllegalStateException("Object already has a key");
}
}
@ -198,14 +243,18 @@ public class Dh extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] makeSharedSecret(Dh pubKey) {
public synchronized byte[] makeSharedSecret(Dh pubKey)
throws WolfCryptException, IllegalStateException {
byte[] publicKey = pubKey.getPublicKey();
if (privateKey != null || publicKey != null) {
return wc_DhAgree(privateKey, publicKey);
synchronized (pointerLock) {
return wc_DhAgree(privateKey, publicKey);
}
} else {
throw new IllegalStateException(
"No available key to perform the opperation.");
"No available key to perform the operation");
}
}
}

View File

@ -38,6 +38,9 @@ public class Ecc extends NativeStruct {
/* used with native wc_ecc_set_rng() */
private Rng rng = null;
/* Lock around object state */
protected final Object stateLock = new Object();
/**
* Create new Ecc object
*/
@ -46,7 +49,7 @@ public class Ecc extends NativeStruct {
}
@Override
public void releaseNativeStruct() {
public synchronized void releaseNativeStruct() {
free();
super.releaseNativeStruct();
@ -89,19 +92,24 @@ public class Ecc extends NativeStruct {
* Initialize Ecc object
*/
protected void init() {
if (state == WolfCryptState.UNINITIALIZED) {
wc_ecc_init();
synchronized (stateLock) {
if (state == WolfCryptState.UNINITIALIZED) {
/* used with native wc_ecc_set_rng() */
if (rng == null) {
rng = new Rng();
rng.init();
synchronized (pointerLock) {
wc_ecc_init();
}
/* used with native wc_ecc_set_rng() */
if (rng == null) {
rng = new Rng();
rng.init();
}
state = WolfCryptState.INITIALIZED;
} else {
throw new IllegalStateException(
"Native resources already initialized.");
}
state = WolfCryptState.INITIALIZED;
} else {
throw new IllegalStateException(
"Native resources already initialized.");
}
}
@ -109,15 +117,20 @@ public class Ecc extends NativeStruct {
* Free Ecc object
*/
protected void free() {
if (state != WolfCryptState.UNINITIALIZED) {
wc_ecc_free();
synchronized (stateLock) {
if (state != WolfCryptState.UNINITIALIZED) {
if (this.rng != null) {
rng.free();
rng.releaseNativeStruct();
synchronized (pointerLock) {
wc_ecc_free();
}
if (this.rng != null) {
rng.free();
rng.releaseNativeStruct();
}
state = WolfCryptState.UNINITIALIZED;
}
state = WolfCryptState.UNINITIALIZED;
}
}
@ -130,12 +143,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void makeKey(Rng rng, int size) {
if (state == WolfCryptState.INITIALIZED) {
wc_ecc_make_key(rng, size);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void makeKey(Rng rng, int size)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_ecc_make_key(rng, size);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -149,12 +169,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void makeKeyOnCurve(Rng rng, int size, String curveName) {
if (state == WolfCryptState.INITIALIZED) {
wc_ecc_make_key_ex(rng, size, curveName.toUpperCase());
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void makeKeyOnCurve(Rng rng, int size, String curveName)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_ecc_make_key_ex(rng, size, curveName.toUpperCase());
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -165,12 +192,19 @@ public class Ecc extends NativeStruct {
* incorrect or invalid
* @throws IllegalStateException if object does not have a key
*/
public void checkKey() {
if (state == WolfCryptState.READY) {
wc_ecc_check_key();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized void checkKey()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
wc_ecc_check_key();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -183,12 +217,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void importPrivate(byte[] privKey, byte[] x963Key) {
if (state == WolfCryptState.INITIALIZED) {
wc_ecc_import_private(privKey, x963Key, null);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void importPrivate(byte[] privKey, byte[] x963Key)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_ecc_import_private(privKey, x963Key, null);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -202,13 +243,20 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void importPrivateOnCurve(byte[] privKey, byte[] x963Key,
String curveName) {
if (state == WolfCryptState.INITIALIZED) {
wc_ecc_import_private(privKey, x963Key, curveName);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void importPrivateOnCurve(byte[] privKey,
byte[] x963Key, String curveName)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_ecc_import_private(privKey, x963Key, curveName);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -220,12 +268,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] exportPrivate() {
if (state == WolfCryptState.READY) {
return wc_ecc_export_private();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] exportPrivate()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_ecc_export_private();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -237,12 +292,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void importX963(byte[] key) {
if (state == WolfCryptState.INITIALIZED) {
wc_ecc_import_x963(key);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void importX963(byte[] key)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_ecc_import_x963(key);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -254,12 +316,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] exportX963() {
if (state == WolfCryptState.READY) {
return wc_ecc_export_x963();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] exportX963()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_ecc_export_x963();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -271,12 +340,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void privateKeyDecode(byte[] key) {
if (state == WolfCryptState.INITIALIZED) {
wc_EccPrivateKeyDecode(key);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void privateKeyDecode(byte[] key)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_EccPrivateKeyDecode(key);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -288,12 +364,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] privateKeyEncode() {
if (state == WolfCryptState.READY) {
return wc_EccKeyToDer();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] privateKeyEncode()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_EccKeyToDer();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -305,12 +388,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object already has a key
*/
public void publicKeyDecode(byte[] key) {
if (state == WolfCryptState.INITIALIZED) {
wc_EccPublicKeyDecode(key);
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
public synchronized void publicKeyDecode(byte[] key)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.INITIALIZED) {
synchronized (pointerLock) {
wc_EccPublicKeyDecode(key);
}
state = WolfCryptState.READY;
} else {
throw new IllegalStateException("Object already has a key.");
}
}
}
@ -322,12 +412,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] publicKeyEncode() {
if (state == WolfCryptState.READY) {
return wc_EccPublicKeyToDer();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] publicKeyEncode()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_EccPublicKeyToDer();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -341,12 +438,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] makeSharedSecret(Ecc pubKey) {
if (state == WolfCryptState.READY) {
return wc_ecc_shared_secret(pubKey, this.rng);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] makeSharedSecret(Ecc pubKey)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_ecc_shared_secret(pubKey, this.rng);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -361,14 +465,20 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] sign(byte[] hash, Rng rng) {
public synchronized byte[] sign(byte[] hash, Rng rng)
throws WolfCryptException, IllegalStateException {
byte[] signature = new byte[0];
if (state == WolfCryptState.READY) {
signature = wc_ecc_sign_hash(hash, rng);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
signature = wc_ecc_sign_hash(hash, rng);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
return signature;
@ -385,14 +495,21 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public boolean verify(byte[] hash, byte[] signature) {
public synchronized boolean verify(byte[] hash, byte[] signature)
throws WolfCryptException, IllegalStateException {
boolean result = false;
if (state == WolfCryptState.READY) {
result = wc_ecc_verify_hash(hash, signature);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
result = wc_ecc_verify_hash(hash, signature);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
return result;
@ -408,9 +525,10 @@ public class Ecc extends NativeStruct {
* @return size of ECC curve
*
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public static int getCurveSizeFromName(String curveName) {
public static int getCurveSizeFromName(String curveName)
throws WolfCryptException {
/* Ecc object doesn't need to be initialied before call */
return wc_ecc_get_curve_size_from_name(curveName);
}
@ -423,12 +541,19 @@ public class Ecc extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] privateKeyEncodePKCS8() {
if (state == WolfCryptState.READY) {
return wc_ecc_private_key_to_pkcs8();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] privateKeyEncodePKCS8()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_ecc_private_key_to_pkcs8();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
}
@ -444,8 +569,8 @@ public class Ecc extends NativeStruct {
* is not an instance of ECFieldFp
*/
public static String getCurveName(ECParameterSpec spec)
throws InvalidAlgorithmParameterException
{
throws WolfCryptException, InvalidAlgorithmParameterException {
int curve_id;
/* Ecc object doesn't need to be initialied before call */

View File

@ -50,6 +50,9 @@ public class Hmac extends NativeStruct {
private int type = -1;
private byte[] key;
/* Lock around object state */
protected final Object stateLock = new Object();
/**
* Create new Hmac object
*/
@ -90,7 +93,9 @@ public class Hmac extends NativeStruct {
/* check if type is -1, if so that type is not compiled in at native
* wolfSSL level. Throw exception if so. */
private void checkHashTypeCompiledIn(int type) throws WolfCryptException {
private void checkHashTypeCompiledIn(int type)
throws WolfCryptException {
WolfCryptError notCompiledIn = WolfCryptError.NOT_COMPILED_IN;
if (type == -1) {
throw new WolfCryptException(notCompiledIn.getCode());
@ -105,16 +110,21 @@ public class Hmac extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public void setKey(int type, byte[] key) {
public synchronized void setKey(int type, byte[] key)
throws WolfCryptException {
/* verify hash type is compiled in */
checkHashTypeCompiledIn(type);
synchronized (stateLock) {
/* verify hash type is compiled in */
checkHashTypeCompiledIn(type);
wc_HmacSetKey(type, key);
this.type = type;
this.key = key;
synchronized (pointerLock) {
wc_HmacSetKey(type, key);
}
this.type = type;
this.key = key;
state = WolfCryptState.READY;
state = WolfCryptState.READY;
}
}
/**
@ -123,12 +133,16 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public void reset() {
if (state == WolfCryptState.READY) {
setKey(type, key);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized void reset()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
setKey(type, key);
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -140,12 +154,19 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public void update(byte data) {
if (state == WolfCryptState.READY) {
wc_HmacUpdate(data);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized void update(byte data)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
wc_HmacUpdate(data);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -157,12 +178,19 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public void update(byte[] data) {
if (state == WolfCryptState.READY) {
wc_HmacUpdate(data, 0, data.length);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public void update(byte[] data)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
wc_HmacUpdate(data, 0, data.length);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -176,12 +204,19 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public void update(byte[] data, int offset, int length) {
if (state == WolfCryptState.READY) {
wc_HmacUpdate(data, offset, length);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized void update(byte[] data, int offset, int length)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
wc_HmacUpdate(data, offset, length);
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -193,17 +228,23 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public void update(ByteBuffer data) {
if (state == WolfCryptState.READY) {
int offset = data.position();
int length = data.remaining();
public synchronized void update(ByteBuffer data)
throws WolfCryptException, IllegalStateException {
wc_HmacUpdate(data, offset, length);
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
int offset = data.position();
int length = data.remaining();
data.position(offset + length);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
synchronized (pointerLock) {
wc_HmacUpdate(data, offset, length);
}
data.position(offset + length);
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -215,12 +256,19 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] doFinal() {
if (state == WolfCryptState.READY) {
return wc_HmacFinal();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] doFinal()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
synchronized (pointerLock) {
return wc_HmacFinal();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -234,13 +282,20 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public byte[] doFinal(byte[] data) {
if (state == WolfCryptState.READY) {
update(data);
return wc_HmacFinal();
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized byte[] doFinal(byte[] data)
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
update(data);
synchronized (pointerLock) {
return wc_HmacFinal();
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
@ -251,28 +306,30 @@ public class Hmac extends NativeStruct {
*
* @throws IllegalStateException if object has no key
*/
public String getAlgorithm() {
if (state == WolfCryptState.READY) {
public synchronized String getAlgorithm()
throws IllegalStateException {
if (type == MD5) {
return "HmacMD5";
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
if (type == MD5) {
return "HmacMD5";
}
else if (type == SHA256) {
return "HmacSHA256";
}
else if (type == SHA384) {
return "HmacSHA384";
}
else if (type == SHA512) {
return "HmacSHA512";
}
else {
return "";
}
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
else if (type == SHA256) {
return "HmacSHA256";
}
else if (type == SHA384) {
return "HmacSHA384";
}
else if (type == SHA512) {
return "HmacSHA512";
}
else {
return "";
}
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
}
}
@ -284,12 +341,18 @@ public class Hmac extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object has no key
*/
public int getMacLength() {
if (state == WolfCryptState.READY) {
return wc_HmacSizeByType(type);
} else {
throw new IllegalStateException(
"No available key to perform the operation.");
public synchronized int getMacLength()
throws WolfCryptException, IllegalStateException {
synchronized (stateLock) {
if (state == WolfCryptState.READY) {
/* Does not use Hmac poiner, no need to lock */
return wc_HmacSizeByType(type);
} else {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}

View File

@ -33,6 +33,19 @@ public class Md5 extends MessageDigest {
/** MD5 digest size */
public static final int DIGEST_SIZE = 16;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_init_internal();
private native void native_copy_internal(Md5 toBeCopied);
private native void native_update_internal(ByteBuffer data, int offset,
int len);
private native void native_update_internal(byte[] data, int offset,
int len);
private native void native_final_internal(ByteBuffer hash, int offset);
private native void native_final_internal(byte[] hash);
/**
* Malloc native JNI Md5 structure
*
@ -40,12 +53,26 @@ public class Md5 extends MessageDigest {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Initialize Md5 object
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_init();
protected void native_init()
throws WolfCryptException {
synchronized (pointerLock) {
native_init_internal();
}
}
/**
* Copy existing native WC_MD5 struct (Md5 object) into this one.
@ -55,7 +82,13 @@ public class Md5 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_copy(Md5 toBeCopied);
protected void native_copy(Md5 toBeCopied)
throws WolfCryptException {
synchronized (pointerLock) {
native_copy_internal(toBeCopied);
}
}
/**
* Native Md5 update
@ -66,7 +99,13 @@ public class Md5 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(ByteBuffer data, int offset, int len);
protected void native_update(ByteBuffer data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native Md5 update
@ -77,7 +116,13 @@ public class Md5 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(byte[] data, int offset, int len);
protected void native_update(byte[] data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native Md5 final, calculate final digest
@ -87,7 +132,13 @@ public class Md5 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(ByteBuffer hash, int offset);
protected void native_final(ByteBuffer hash, int offset)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash, offset);
}
}
/**
* Native Md5 final, calculate final digest
@ -96,7 +147,13 @@ public class Md5 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(byte[] hash);
protected void native_final(byte[] hash)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash);
}
}
/**
* Create new Md5 object

View File

@ -92,7 +92,7 @@ public abstract class MessageDigest extends NativeStruct {
/**
* Initialize object
*/
public void init() {
public synchronized void init() {
native_init();
state = WolfCryptState.READY;
}
@ -106,7 +106,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public void update(ByteBuffer data, int length) {
public synchronized void update(ByteBuffer data, int length)
throws WolfCryptException, IllegalStateException {
if (state == WolfCryptState.READY) {
length = Math.min(length, data.remaining());
@ -126,7 +128,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public void update(ByteBuffer data) {
public synchronized void update(ByteBuffer data)
throws WolfCryptException, IllegalStateException {
update(data, data.remaining());
}
@ -140,7 +144,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public void update(byte[] data, int offset, int len) {
public synchronized void update(byte[] data, int offset, int len)
throws WolfCryptException, IllegalStateException {
if (state == WolfCryptState.READY) {
if (offset >= data.length || offset < 0 || len < 0)
return;
@ -164,7 +170,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public void update(byte[] data, int len) {
public synchronized void update(byte[] data, int len)
throws WolfCryptException, IllegalStateException {
update(data, 0, len);
}
@ -176,7 +184,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public void update(byte[] data) {
public synchronized void update(byte[] data)
throws WolfCryptException, IllegalStateException {
update(data, 0, data.length);
}
@ -189,7 +199,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws ShortBufferException if input buffer is too small
* @throws IllegalStateException object not initialized
*/
public void digest(ByteBuffer hash) throws ShortBufferException {
public synchronized void digest(ByteBuffer hash)
throws ShortBufferException, WolfCryptException, IllegalStateException {
if (state == WolfCryptState.READY) {
if (hash.remaining() < digestSize())
throw new ShortBufferException(
@ -212,7 +224,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws ShortBufferException if input buffer is too small
* @throws IllegalStateException object not initialized
*/
public void digest(byte[] hash) throws ShortBufferException {
public synchronized void digest(byte[] hash)
throws ShortBufferException, WolfCryptException, IllegalStateException {
if (state == WolfCryptState.READY) {
if (hash.length < digestSize())
throw new ShortBufferException(
@ -233,7 +247,9 @@ public abstract class MessageDigest extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException object not initialized
*/
public byte[] digest() {
public synchronized byte[] digest()
throws WolfCryptException, IllegalStateException {
if (state == WolfCryptState.READY) {
byte[] hash = new byte[digestSize()];
@ -247,7 +263,7 @@ public abstract class MessageDigest extends NativeStruct {
}
@Override
public void releaseNativeStruct() {
public synchronized void releaseNativeStruct() {
/* reset state first, then free */
state = WolfCryptState.UNINITIALIZED;

View File

@ -37,11 +37,18 @@ public abstract class NativeStruct extends WolfObject {
}
/* points to the internal native structure */
private long pointer;
private long pointer = 0;
/* Lock around native pointer use */
protected final Object pointerLock = new Object();
/**
* Get pointer to wrapped native structure
*
* WARNING: the pointer returned from this function has not been locked
* and may cause threading synchronization issues if used in a
* multi-threaded use case or application.
*
* @return pointer to native structure
*/
public long getNativeStruct() {
@ -57,10 +64,14 @@ public abstract class NativeStruct extends WolfObject {
* @param nativeStruct pointer to initialized native structure
*/
protected void setNativeStruct(long nativeStruct) {
if (this.pointer != NULL)
xfree(this.pointer);
this.pointer = nativeStruct;
synchronized (pointerLock) {
if (this.pointer != NULL) {
xfree(this.pointer);
}
this.pointer = nativeStruct;
}
}
/**

View File

@ -32,6 +32,9 @@ public class Rsa extends NativeStruct {
private boolean hasPrivateKey = false;
private Rng rng;
/* Lock around object state */
protected final Object stateLock = new Object();
/**
* Malloc native JNI Rsa structure
*
@ -135,15 +138,18 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public void setRng(Rng rng) throws WolfCryptException {
public synchronized void setRng(Rng rng) throws WolfCryptException {
init();
if (wc_RsaSetRNG(rng))
this.rng = rng;
synchronized (pointerLock) {
if (wc_RsaSetRNG(rng)) {
this.rng = rng;
}
}
}
@Override
public void releaseNativeStruct() {
public synchronized void releaseNativeStruct() {
free();
super.releaseNativeStruct();
@ -155,9 +161,15 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
*/
protected void init() throws WolfCryptException {
if (state == WolfCryptState.UNINITIALIZED) {
wc_InitRsaKey();
state = WolfCryptState.INITIALIZED;
synchronized (stateLock) {
if (state == WolfCryptState.UNINITIALIZED) {
synchronized (pointerLock) {
wc_InitRsaKey();
}
state = WolfCryptState.INITIALIZED;
}
}
}
@ -172,8 +184,11 @@ public class Rsa extends NativeStruct {
init();
if (state != WolfCryptState.INITIALIZED)
throw new IllegalStateException("Object already has a key.");
synchronized (stateLock) {
if (state != WolfCryptState.INITIALIZED) {
throw new IllegalStateException("Object already has a key");
}
}
}
/**
@ -185,13 +200,18 @@ public class Rsa extends NativeStruct {
* @throws IllegalStateException if object has no public key
*/
protected void willUseKey(boolean priv) throws IllegalStateException {
if (priv && !hasPrivateKey)
throw new IllegalStateException(
"No available private key to perform the operation.");
if (state != WolfCryptState.READY)
if (priv && !hasPrivateKey) {
throw new IllegalStateException(
"No available key to perform the operation.");
"No available private key to perform the operation");
}
synchronized (stateLock) {
if (state != WolfCryptState.READY) {
throw new IllegalStateException(
"No available key to perform the operation");
}
}
}
/**
@ -200,9 +220,15 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
*/
protected void free() throws WolfCryptException {
if (state != WolfCryptState.UNINITIALIZED) {
wc_FreeRsaKey();
state = WolfCryptState.UNINITIALIZED;
synchronized (stateLock) {
if (state != WolfCryptState.UNINITIALIZED) {
synchronized (pointerLock) {
wc_FreeRsaKey();
}
state = WolfCryptState.UNINITIALIZED;
}
}
}
@ -216,14 +242,19 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void makeKey(int size, long e, Rng rng)
public synchronized void makeKey(int size, long e, Rng rng)
throws WolfCryptException, IllegalStateException {
willSetKey();
MakeRsaKey(size, e, rng);
synchronized (stateLock) {
synchronized (pointerLock) {
MakeRsaKey(size, e, rng);
}
state = WolfCryptState.READY;
hasPrivateKey = true;
state = WolfCryptState.READY;
hasPrivateKey = true;
}
}
/**
@ -234,12 +265,17 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodePublicKey(byte[] key)
public synchronized void decodePublicKey(byte[] key)
throws WolfCryptException, IllegalStateException {
willSetKey();
wc_RsaPublicKeyDecode(key);
state = WolfCryptState.READY;
synchronized (stateLock) {
synchronized (pointerLock) {
wc_RsaPublicKeyDecode(key);
}
state = WolfCryptState.READY;
}
}
/**
@ -250,13 +286,18 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodePrivateKey(byte[] key)
public synchronized void decodePrivateKey(byte[] key)
throws WolfCryptException, IllegalStateException {
willSetKey();
wc_RsaPrivateKeyDecode(key);
state = WolfCryptState.READY;
hasPrivateKey = true;
synchronized (stateLock) {
synchronized (pointerLock) {
wc_RsaPrivateKeyDecode(key);
}
state = WolfCryptState.READY;
hasPrivateKey = true;
}
}
/**
@ -267,14 +308,19 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodePrivateKeyPKCS8(byte[] key)
public synchronized void decodePrivateKeyPKCS8(byte[] key)
throws WolfCryptException, IllegalStateException {
willSetKey();
wc_RsaPrivateKeyDecodePKCS8(key);
synchronized (stateLock) {
synchronized (pointerLock) {
wc_RsaPrivateKeyDecodePKCS8(key);
}
state = WolfCryptState.READY;
hasPrivateKey = true;
state = WolfCryptState.READY;
hasPrivateKey = true;
}
}
/**
@ -286,8 +332,9 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodeRawPublicKey(byte[] n, byte[] e)
public synchronized void decodeRawPublicKey(byte[] n, byte[] e)
throws WolfCryptException, IllegalStateException {
decodeRawPublicKey(n, n.length, e, e.length);
}
@ -302,12 +349,18 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodeRawPublicKey(byte[] n, long nSize, byte[] e, long eSize)
public synchronized void decodeRawPublicKey(byte[] n, long nSize,
byte[] e, long eSize)
throws WolfCryptException, IllegalStateException {
willSetKey();
wc_RsaPublicKeyDecodeRaw(n, nSize, e, eSize);
state = WolfCryptState.READY;
synchronized (stateLock) {
synchronized (pointerLock) {
wc_RsaPublicKeyDecodeRaw(n, nSize, e, eSize);
}
state = WolfCryptState.READY;
}
}
/**
@ -319,8 +372,9 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodeRawPublicKey(ByteBuffer n, ByteBuffer e)
public synchronized void decodeRawPublicKey(ByteBuffer n, ByteBuffer e)
throws WolfCryptException, IllegalStateException {
decodeRawPublicKey(n, n.limit(), e, e.limit());
}
@ -335,12 +389,18 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object is already initialized
*/
public void decodeRawPublicKey(ByteBuffer n, long nSz, ByteBuffer e,
long eSz) throws WolfCryptException, IllegalStateException {
public synchronized void decodeRawPublicKey(ByteBuffer n, long nSz,
ByteBuffer e, long eSz)
throws WolfCryptException, IllegalStateException {
willSetKey();
wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz);
state = WolfCryptState.READY;
synchronized (stateLock) {
synchronized (pointerLock) {
wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz);
}
state = WolfCryptState.READY;
}
}
/**
@ -355,11 +415,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public void exportRawPublicKey(byte[] n, long[] nSz, byte[] e, long[] eSz)
throws WolfCryptException {
public synchronized void exportRawPublicKey(byte[] n, long[] nSz, byte[] e,
long[] eSz) throws WolfCryptException {
willUseKey(false);
RsaFlattenPublicKey(n, nSz, e, eSz);
synchronized (pointerLock) {
RsaFlattenPublicKey(n, nSz, e, eSz);
}
}
/**
@ -370,11 +433,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public void exportRawPublicKey(ByteBuffer n, ByteBuffer e)
public synchronized void exportRawPublicKey(ByteBuffer n, ByteBuffer e)
throws WolfCryptException {
willUseKey(false);
RsaFlattenPublicKey(n, e);
synchronized (pointerLock) {
RsaFlattenPublicKey(n, e);
}
}
/**
@ -384,10 +450,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] exportPrivateDer() throws WolfCryptException {
public synchronized byte[] exportPrivateDer()
throws WolfCryptException {
willUseKey(true);
return wc_RsaKeyToDer();
synchronized (pointerLock) {
return wc_RsaKeyToDer();
}
}
/**
@ -397,10 +467,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] exportPublicDer() throws WolfCryptException {
public synchronized byte[] exportPublicDer()
throws WolfCryptException {
willUseKey(false);
return wc_RsaKeyToPublicDer();
synchronized (pointerLock) {
return wc_RsaKeyToPublicDer();
}
}
/**
@ -410,10 +484,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] privateKeyEncodePKCS8() throws WolfCryptException {
public synchronized byte[] privateKeyEncodePKCS8()
throws WolfCryptException {
willUseKey(true);
return wc_RsaPrivateKeyToPkcs8();
synchronized (pointerLock) {
return wc_RsaPrivateKeyToPkcs8();
}
}
/**
@ -423,10 +501,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public int getEncryptSize() throws WolfCryptException {
public synchronized int getEncryptSize()
throws WolfCryptException {
willUseKey(false);
return wc_RsaEncryptSize();
synchronized (pointerLock) {
return wc_RsaEncryptSize();
}
}
/**
@ -439,10 +521,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] encrypt(byte[] plain, Rng rng) throws WolfCryptException {
public synchronized byte[] encrypt(byte[] plain, Rng rng)
throws WolfCryptException {
willUseKey(false);
return wc_RsaPublicEncrypt(plain, rng);
synchronized (pointerLock) {
return wc_RsaPublicEncrypt(plain, rng);
}
}
/**
@ -454,10 +540,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] decrypt(byte[] ciphertext) throws WolfCryptException {
public synchronized byte[] decrypt(byte[] ciphertext)
throws WolfCryptException {
willUseKey(true);
return wc_RsaPrivateDecrypt(ciphertext);
synchronized (pointerLock) {
return wc_RsaPrivateDecrypt(ciphertext);
}
}
/**
@ -471,10 +561,14 @@ public class Rsa extends NativeStruct {
* @throws WolfCryptException if native operation fails
* @throws IllegalStateException if object does not have key
*/
public byte[] sign(byte[] data, Rng rng) throws WolfCryptException {
public synchronized byte[] sign(byte[] data, Rng rng)
throws WolfCryptException {
willUseKey(true);
return wc_RsaSSL_Sign(data, rng);
synchronized (pointerLock) {
return wc_RsaSSL_Sign(data, rng);
}
}
/**
@ -486,10 +580,14 @@ public class Rsa extends NativeStruct {
*
* @throws WolfCryptException if native operation fails
*/
public byte[] verify(byte[] signature) throws WolfCryptException {
public synchronized byte[] verify(byte[] signature)
throws WolfCryptException {
willUseKey(false);
return wc_RsaSSL_Verify(signature);
synchronized (pointerLock) {
return wc_RsaSSL_Verify(signature);
}
}
}

View File

@ -33,6 +33,19 @@ public class Sha extends MessageDigest {
/** SHA-1 digest size */
public static final int DIGEST_SIZE = 20;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_init_internal();
private native void native_copy_internal(Sha toBeCopied);
private native void native_update_internal(ByteBuffer data, int offset,
int len);
private native void native_update_internal(byte[] data, int offset,
int len);
private native void native_final_internal(ByteBuffer hash, int offset);
private native void native_final_internal(byte[] hash);
/**
* Malloc native JNI Sha structure
*
@ -40,12 +53,26 @@ public class Sha extends MessageDigest {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Initialize Sha object
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_init();
protected void native_init()
throws WolfCryptException {
synchronized (pointerLock) {
native_init_internal();
}
}
/**
* Copy existing native WC_SHA struct (Sha object) into this one.
@ -55,7 +82,13 @@ public class Sha extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_copy(Sha toBeCopied);
protected void native_copy(Sha toBeCopied)
throws WolfCryptException {
synchronized (pointerLock) {
native_copy_internal(toBeCopied);
}
}
/**
* Native SHA-1 update
@ -66,7 +99,13 @@ public class Sha extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(ByteBuffer data, int offset, int len);
protected void native_update(ByteBuffer data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA-1 update
@ -77,7 +116,13 @@ public class Sha extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(byte[] data, int offset, int len);
protected void native_update(byte[] data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA-1 final, calculate final digest
@ -87,7 +132,13 @@ public class Sha extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(ByteBuffer hash, int offset);
protected void native_final(ByteBuffer hash, int offset)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash, offset);
}
}
/**
* Native SHA-1 final, calculate final digest
@ -96,7 +147,13 @@ public class Sha extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(byte[] hash);
protected void native_final(byte[] hash)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash);
}
}
/**
* Create new SHA-1 object

View File

@ -33,6 +33,19 @@ public class Sha256 extends MessageDigest {
/** SHA2-256 digest size */
public static final int DIGEST_SIZE = 32;
/* native JNI methods, internally reach back and grab/use pointer
* from NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_init_internal();
private native void native_copy_internal(Sha256 toBeCopied);
private native void native_update_internal(ByteBuffer data, int offset,
int len);
private native void native_update_internal(byte[] data, int offset,
int len);
private native void native_final_internal(ByteBuffer hash, int offset);
private native void native_final_internal(byte[] hash);
/**
* Malloc native JNI Sha256 structure
*
@ -40,12 +53,26 @@ public class Sha256 extends MessageDigest {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Initialize Sha256 object
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_init();
protected void native_init()
throws WolfCryptException {
synchronized (pointerLock) {
native_init_internal();
}
}
/**
* Copy existing native WC_SHA256 struct (Sha256 object) into this one.
@ -55,7 +82,13 @@ public class Sha256 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_copy(Sha256 toBeCopied);
protected void native_copy(Sha256 toBeCopied)
throws WolfCryptException {
synchronized (pointerLock) {
native_copy_internal(toBeCopied);
}
}
/**
* Native SHA2-256 update
@ -66,7 +99,13 @@ public class Sha256 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(ByteBuffer data, int offset, int len);
protected void native_update(ByteBuffer data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-256 update
@ -77,7 +116,13 @@ public class Sha256 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(byte[] data, int offset, int len);
protected void native_update(byte[] data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-256 final, calculate final digest
@ -87,7 +132,13 @@ public class Sha256 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(ByteBuffer hash, int offset);
protected void native_final(ByteBuffer hash, int offset)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash, offset);
}
}
/**
* Native SHA2-256 final, calculate final digest
@ -96,7 +147,13 @@ public class Sha256 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(byte[] hash);
protected void native_final(byte[] hash)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash);
}
}
/**
* Create new SHA2-256 object

View File

@ -33,6 +33,19 @@ public class Sha384 extends MessageDigest {
/** SHA2-384 digest size */
public static final int DIGEST_SIZE = 48;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_init_internal();
private native void native_copy_internal(Sha384 toBeCopied);
private native void native_update_internal(ByteBuffer data, int offset,
int len);
private native void native_update_internal(byte[] data, int offset,
int len);
private native void native_final_internal(ByteBuffer hash, int offset);
private native void native_final_internal(byte[] hash);
/**
* Malloc native JNI Sha384 structure
*
@ -40,12 +53,26 @@ public class Sha384 extends MessageDigest {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Initialize Sha384 object
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_init();
protected void native_init()
throws WolfCryptException {
synchronized (pointerLock) {
native_init_internal();
}
}
/**
* Copy existing native WC_SHA384 struct (Sha384 object) into this one.
@ -55,7 +82,13 @@ public class Sha384 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_copy(Sha384 toBeCopied);
protected void native_copy(Sha384 toBeCopied)
throws WolfCryptException {
synchronized (pointerLock) {
native_copy_internal(toBeCopied);
}
}
/**
* Native SHA2-384 update
@ -66,7 +99,13 @@ public class Sha384 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(ByteBuffer data, int offset, int len);
protected void native_update(ByteBuffer data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-384 update
@ -77,7 +116,13 @@ public class Sha384 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(byte[] data, int offset, int len);
protected void native_update(byte[] data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-384 final, calculate final digest
@ -87,7 +132,13 @@ public class Sha384 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(ByteBuffer hash, int offset);
protected void native_final(ByteBuffer hash, int offset)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash, offset);
}
}
/**
* Native SHA2-384 final, calculate final digest
@ -96,7 +147,13 @@ public class Sha384 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(byte[] hash);
protected void native_final(byte[] hash)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash);
}
}
/**
* Create new SHA2-384 object

View File

@ -33,6 +33,19 @@ public class Sha512 extends MessageDigest {
/** SHA2-512 digest size */
public static final int DIGEST_SIZE = 64;
/* native JNI methods, internally reach back and grab/use pointer from
* NativeStruct.java. We wrap calls to these below in order to
* synchronize access to native pointer between threads */
private native long mallocNativeStruct_internal() throws OutOfMemoryError;
private native void native_init_internal();
private native void native_copy_internal(Sha512 toBeCopied);
private native void native_update_internal(ByteBuffer data, int offset,
int len);
private native void native_update_internal(byte[] data, int offset,
int len);
private native void native_final_internal(ByteBuffer hash, int offset);
private native void native_final_internal(byte[] hash);
/**
* Malloc native JNI Sha512 structure
*
@ -40,12 +53,26 @@ public class Sha512 extends MessageDigest {
*
* @throws OutOfMemoryError when malloc fails with memory error
*/
protected native long mallocNativeStruct() throws OutOfMemoryError;
protected long mallocNativeStruct()
throws OutOfMemoryError {
synchronized (pointerLock) {
return mallocNativeStruct_internal();
}
}
/**
* Initialize Sha512 object
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_init();
protected void native_init()
throws WolfCryptException {
synchronized (pointerLock) {
native_init_internal();
}
}
/**
* Copy existing native WC_SHA512 struct (Sha512 object) into this one.
@ -55,7 +82,13 @@ public class Sha512 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_copy(Sha512 toBeCopied);
protected void native_copy(Sha512 toBeCopied)
throws WolfCryptException {
synchronized (pointerLock) {
native_copy_internal(toBeCopied);
}
}
/**
* Native SHA2-512 update
@ -66,7 +99,13 @@ public class Sha512 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(ByteBuffer data, int offset, int len);
protected void native_update(ByteBuffer data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-512 update
@ -77,7 +116,13 @@ public class Sha512 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_update(byte[] data, int offset, int len);
protected void native_update(byte[] data, int offset, int len)
throws WolfCryptException {
synchronized (pointerLock) {
native_update_internal(data, offset, len);
}
}
/**
* Native SHA2-512 final, calculate final digest
@ -87,7 +132,13 @@ public class Sha512 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(ByteBuffer hash, int offset);
protected void native_final(ByteBuffer hash, int offset)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash, offset);
}
}
/**
* Native SHA2-512 final, calculate final digest
@ -96,7 +147,13 @@ public class Sha512 extends MessageDigest {
*
* @throws WolfCryptException if native operation fails
*/
protected native void native_final(byte[] hash);
protected void native_final(byte[] hash)
throws WolfCryptException {
synchronized (pointerLock) {
native_final_internal(hash);
}
}
/**
* Create new SHA2-512 object

View File

@ -27,7 +27,13 @@ import org.junit.BeforeClass;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
@ -77,6 +83,9 @@ public class WolfCryptCipherTest {
private static HashMap<String, Integer> expectedBlockSizes =
new HashMap<String, Integer>();
/* One static SecureRandom to share */
private static SecureRandom secureRandom = new SecureRandom();
@BeforeClass
public static void testProviderInstallationAtRuntime()
throws NoSuchProviderException, NoSuchPaddingException {
@ -1357,6 +1366,114 @@ public class WolfCryptCipherTest {
assertArrayEquals(plain, input);
}
@Test
public void testAesCbcThreaded() throws InterruptedException {
int numThreads = 50;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] rand2kBuf = new byte[2048];
final byte[] key = new byte[] {
(byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33,
(byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37,
(byte)0x38, (byte)0x39, (byte)0x61, (byte)0x62,
(byte)0x63, (byte)0x64, (byte)0x65, (byte)0x66
};
final byte[] iv = new byte[] {
(byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34,
(byte)0x35, (byte)0x36, (byte)0x37, (byte)0x38,
(byte)0x39, (byte)0x30, (byte)0x61, (byte)0x62,
(byte)0x63, (byte)0x64, (byte)0x65, (byte)0x66
};
if (!enabledJCEAlgos.contains("AES/CBC/NoPadding")) {
/* skip if AES/CBC/NoPadding is not enabled */
return;
}
/* fill large input buffer with random bytes */
new Random().nextBytes(rand2kBuf);
/* encrypt / decrypt input data, make sure decrypted matches original */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int ret = 0;
try {
Cipher enc = Cipher.getInstance(
"AES/CBC/NoPadding", jceProvider);
enc.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv));
Cipher dec = Cipher.getInstance(
"AES/CBC/NoPadding", jceProvider);
dec.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv));
byte[] encrypted = new byte[2048];
byte[] plaintext = new byte[2048];
/* encrypt in 128-byte chunks */
Arrays.fill(encrypted, (byte)0);
for (int j = 0; j < rand2kBuf.length; j+= 128) {
ret = enc.update(rand2kBuf, j, 128, encrypted, j);
if (ret != 128) {
throw new Exception(
"Cipher.update(Aes,ENCRYPT_MODE) returned "
+ ret);
}
}
/* decrypt in 128-byte chunks */
Arrays.fill(plaintext, (byte)0);
for (int j = 0; j < encrypted.length; j+= 128) {
ret = dec.update(encrypted, j, 128, plaintext, j);
if (ret != 128) {
throw new Exception(
"Cipher.update(Aes,DECRYPT_MODE) returned "
+ ret);
}
}
/* make sure decrypted is same as input */
if (Arrays.equals(rand2kBuf, plaintext)) {
results.add(0);
}
else {
/* not equal, error case */
results.add(1);
}
} catch (Exception e) {
e.printStackTrace();
results.add(1);
} finally {
latch.countDown();
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in AES Cipher thread test");
}
}
}
@Test
public void testDESedeCbcNoPadding()
throws NoSuchProviderException, NoSuchAlgorithmException,
@ -1496,6 +1613,115 @@ public class WolfCryptCipherTest {
}
}
@Test
public void testDESedeCbcNoPaddingThreaded() throws InterruptedException {
int numThreads = 50;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] rand2kBuf = new byte[2048];
final byte key[] = new byte[] {
(byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67,
(byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef,
(byte)0xfe, (byte)0xde, (byte)0xba, (byte)0x98,
(byte)0x76, (byte)0x54, (byte)0x32, (byte)0x10,
(byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef,
(byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67
};
final byte iv[] = new byte[] {
(byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78,
(byte)0x90, (byte)0xab, (byte)0xcd, (byte)0xef,
};
if (!enabledJCEAlgos.contains("DESede/CBC/NoPadding")) {
/* skip if DESede/CBC/NoPadding is not enabled */
return;
}
/* fill large input buffer with random bytes */
new Random().nextBytes(rand2kBuf);
/* encrypt / decrypt input data, make sure decrypted matches original */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int ret = 0;
try {
Cipher enc = Cipher.getInstance(
"DESede/CBC/NoPadding", jceProvider);
enc.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec(key, "DESede"),
new IvParameterSpec(iv));
Cipher dec = Cipher.getInstance(
"DESede/CBC/NoPadding", jceProvider);
dec.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(key, "DESede"),
new IvParameterSpec(iv));
byte[] encrypted = new byte[2048];
byte[] plaintext = new byte[2048];
/* encrypt in 128-byte chunks */
Arrays.fill(encrypted, (byte)0);
for (int j = 0; j < rand2kBuf.length; j+= 128) {
ret = enc.update(rand2kBuf, j, 128, encrypted, j);
if (ret != 128) {
throw new Exception(
"Cipher.update(DES,ENCRYPT_MODE) returned "
+ ret);
}
}
/* decrypt in 128-byte chunks */
Arrays.fill(plaintext, (byte)0);
for (int j = 0; j < encrypted.length; j+= 128) {
ret = dec.update(encrypted, j, 128, plaintext, j);
if (ret != 128) {
throw new Exception(
"Cipher.update(DES,DECRYPT_MODE) returned "
+ ret);
}
}
/* make sure decrypted is same as input */
if (Arrays.equals(rand2kBuf, plaintext)) {
results.add(0);
}
else {
/* not equal, error case */
results.add(1);
}
} catch (Exception e) {
e.printStackTrace();
results.add(1);
} finally {
latch.countDown();
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in DESede Cipher thread test");
}
}
}
private void testRSAPublicPrivateEncryptDecrypt(String algo)
throws NoSuchProviderException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
@ -1524,7 +1750,7 @@ public class WolfCryptCipherTest {
byte[] plaintext = null;
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
keyGen.initialize(2048, secureRandom);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
@ -1582,7 +1808,7 @@ public class WolfCryptCipherTest {
byte[] plaintext = null;
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
keyGen.initialize(2048, secureRandom);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
@ -1673,7 +1899,7 @@ public class WolfCryptCipherTest {
byte[] plaintextB = null;
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
keyGen.initialize(2048, secureRandom);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
@ -1789,7 +2015,7 @@ public class WolfCryptCipherTest {
byte[] inputB = new byte[100];
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
keyGen.initialize(2048, secureRandom);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
@ -1907,7 +2133,7 @@ public class WolfCryptCipherTest {
byte[] plaintext = null;
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
keyGen.initialize(2048, secureRandom);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();

View File

@ -27,6 +27,12 @@ import org.junit.BeforeClass;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.KeyAgreement;
import javax.crypto.ShortBufferException;
@ -94,6 +100,9 @@ public class WolfCryptKeyAgreementTest {
private static ArrayList<String> disabledCurves =
new ArrayList<String>();
/* One static SecureRandom to share */
private static SecureRandom secureRandom = new SecureRandom();
private static void printDisabledCurves() {
if (disabledCurves.size() > 0)
@ -179,7 +188,7 @@ public class WolfCryptKeyAgreementTest {
/* initialize key pair generator */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "wolfJCE");
keyGen.initialize(dhParams, new SecureRandom());
keyGen.initialize(dhParams, secureRandom);
KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "wolfJCE");
KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "wolfJCE");
@ -230,7 +239,7 @@ public class WolfCryptKeyAgreementTest {
/* initialize key pair generator */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "wolfJCE");
keyGen.initialize(dhParams, new SecureRandom());
keyGen.initialize(dhParams, secureRandom);
KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "wolfJCE");
KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "wolfJCE");
@ -284,7 +293,7 @@ public class WolfCryptKeyAgreementTest {
/* initialize key pair generator */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "wolfJCE");
keyGen.initialize(dhParams, new SecureRandom());
keyGen.initialize(dhParams, secureRandom);
KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "wolfJCE");
KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH");
@ -494,5 +503,136 @@ public class WolfCryptKeyAgreementTest {
assertArrayEquals(secretA2, secretC);
}
private void threadRunnerKeyAgreeTest(String algo)
throws InterruptedException, NoSuchAlgorithmException {
int numThreads = 10;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final String currentAlgo = algo;
/* DH Tests */
AlgorithmParameterGenerator paramGen =
AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(512);
final AlgorithmParameters params = paramGen.generateParameters();
/* Do encrypt/decrypt and sign/verify in parallel across numThreads
* threads, all operations should pass */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
KeyPairGenerator keyGen = null;
KeyAgreement aKeyAgree = null;
KeyAgreement bKeyAgree = null;
KeyAgreement cKeyAgree = null;
KeyPair aPair = null;
KeyPair bPair = null;
KeyPair cPair = null;
try {
/* Set up KeyPairGenerator */
if (currentAlgo.equals("DH")) {
DHParameterSpec dhParams =
(DHParameterSpec)params.getParameterSpec(
DHParameterSpec.class);
keyGen = KeyPairGenerator.getInstance(
"DH", "wolfJCE");
keyGen.initialize(dhParams, secureRandom);
} else {
ECGenParameterSpec ecsp =
new ECGenParameterSpec("secp256r1");
keyGen = KeyPairGenerator.getInstance(
"EC", "wolfJCE");
keyGen.initialize(ecsp);
}
/* Get KeyAgreement objects */
aKeyAgree = KeyAgreement.getInstance(
currentAlgo, "wolfJCE");
bKeyAgree = KeyAgreement.getInstance(
currentAlgo, "wolfJCE");
/* Generate key pairs */
aPair = keyGen.generateKeyPair();
bPair = keyGen.generateKeyPair();
/* Initialize KeyAgreement objects with private keys */
aKeyAgree.init(aPair.getPrivate());
bKeyAgree.init(bPair.getPrivate());
aKeyAgree.doPhase(bPair.getPublic(), true);
bKeyAgree.doPhase(aPair.getPublic(), true);
/* Generate shared secrets */
byte secretA[] = aKeyAgree.generateSecret();
byte secretB[] = bKeyAgree.generateSecret();
if (!Arrays.equals(secretA, secretB)) {
failed = 1;
}
if (failed == 0) {
cKeyAgree = KeyAgreement.getInstance(
currentAlgo, "wolfJCE");
cPair = keyGen.generateKeyPair();
cKeyAgree.init(cPair.getPrivate());
aKeyAgree.doPhase(cPair.getPublic(), true);
cKeyAgree.doPhase(aPair.getPublic(), true);
byte secretA2[] = aKeyAgree.generateSecret();
byte secretC[] = cKeyAgree.generateSecret();
if (!Arrays.equals(secretA2, secretC)) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in KeyAgreement thread test");
}
}
}
@Test
public void testThreadedKeyAgreement()
throws InterruptedException, NoSuchAlgorithmException {
threadRunnerKeyAgreeTest("DH");
threadRunnerKeyAgreeTest("ECDH");
}
}

View File

@ -26,11 +26,17 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.security.Provider;
@ -665,6 +671,274 @@ public class WolfCryptMacTest {
}
}
private void threadRunnerMacTest(String hmacAlgo, String digest,
HmacVector vector) throws InterruptedException {
int numThreads = 20;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final String currentAlgo = hmacAlgo;
final String mdAlgo = digest;
final byte[] key = vector.getKey();
final byte[] input = vector.getInput();
final byte[] output = vector.getOutput();
/* Do MAC in parallel across numThreads threads, all ops should pass */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
SecretKeySpec keyspec = null;
Mac mac = null;
try {
keyspec = new SecretKeySpec(key, mdAlgo);
mac = Mac.getInstance(currentAlgo, "wolfJCE");
mac.init(keyspec);
mac.update(input);
byte out[] = mac.doFinal();
if (!Arrays.equals(out, output)) {
failed = 1;
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in MAC thread test: " + currentAlgo);
}
}
}
@Test
public void testThreadedMac() throws InterruptedException {
HmacVector md5Vector = new HmacVector(
new byte[] {
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
},
new byte[] {
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD
},
new byte[] {
(byte)0x56, (byte)0xbe, (byte)0x34, (byte)0x52,
(byte)0x1d, (byte)0x14, (byte)0x4c, (byte)0x88,
(byte)0xdb, (byte)0xb8, (byte)0xc7, (byte)0x33,
(byte)0xf0, (byte)0xe8, (byte)0xb3, (byte)0xf6
}
);
HmacVector sha1Vector = new HmacVector(
new byte[] {
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA
},
new byte[] {
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD
},
new byte[] {
(byte)0x12, (byte)0x5d, (byte)0x73, (byte)0x42,
(byte)0xb9, (byte)0xac, (byte)0x11, (byte)0xcd,
(byte)0x91, (byte)0xa3, (byte)0x9a, (byte)0xf4,
(byte)0x8a, (byte)0xa1, (byte)0x7b, (byte)0x4f,
(byte)0x63, (byte)0xf1, (byte)0x75, (byte)0xd3
}
);
HmacVector sha256Vector = new HmacVector(
new byte[] {
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA
},
new byte[] {
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD
},
new byte[] {
(byte)0x77, (byte)0x3e, (byte)0xa9, (byte)0x1e,
(byte)0x36, (byte)0x80, (byte)0x0e, (byte)0x46,
(byte)0x85, (byte)0x4d, (byte)0xb8, (byte)0xeb,
(byte)0xd0, (byte)0x91, (byte)0x81, (byte)0xa7,
(byte)0x29, (byte)0x59, (byte)0x09, (byte)0x8b,
(byte)0x3e, (byte)0xf8, (byte)0xc1, (byte)0x22,
(byte)0xd9, (byte)0x63, (byte)0x55, (byte)0x14,
(byte)0xce, (byte)0xd5, (byte)0x65, (byte)0xfe
}
);
HmacVector sha384Vector = new HmacVector(
new byte[] {
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA
},
new byte[] {
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD
},
new byte[] {
(byte)0x88, (byte)0x06, (byte)0x26, (byte)0x08,
(byte)0xd3, (byte)0xe6, (byte)0xad, (byte)0x8a,
(byte)0x0a, (byte)0xa2, (byte)0xac, (byte)0xe0,
(byte)0x14, (byte)0xc8, (byte)0xa8, (byte)0x6f,
(byte)0x0a, (byte)0xa6, (byte)0x35, (byte)0xd9,
(byte)0x47, (byte)0xac, (byte)0x9f, (byte)0xeb,
(byte)0xe8, (byte)0x3e, (byte)0xf4, (byte)0xe5,
(byte)0x59, (byte)0x66, (byte)0x14, (byte)0x4b,
(byte)0x2a, (byte)0x5a, (byte)0xb3, (byte)0x9d,
(byte)0xc1, (byte)0x38, (byte)0x14, (byte)0xb9,
(byte)0x4e, (byte)0x3a, (byte)0xb6, (byte)0xe1,
(byte)0x01, (byte)0xa3, (byte)0x4f, (byte)0x27
}
);
HmacVector sha512Vector = new HmacVector(
new byte[] {
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA,
(byte)0xAA, (byte)0xAA, (byte)0xAA, (byte)0xAA
},
new byte[] {
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD, (byte)0xDD, (byte)0xDD,
(byte)0xDD, (byte)0xDD
},
new byte[] {
(byte)0xfa, (byte)0x73, (byte)0xb0, (byte)0x08,
(byte)0x9d, (byte)0x56, (byte)0xa2, (byte)0x84,
(byte)0xef, (byte)0xb0, (byte)0xf0, (byte)0x75,
(byte)0x6c, (byte)0x89, (byte)0x0b, (byte)0xe9,
(byte)0xb1, (byte)0xb5, (byte)0xdb, (byte)0xdd,
(byte)0x8e, (byte)0xe8, (byte)0x1a, (byte)0x36,
(byte)0x55, (byte)0xf8, (byte)0x3e, (byte)0x33,
(byte)0xb2, (byte)0x27, (byte)0x9d, (byte)0x39,
(byte)0xbf, (byte)0x3e, (byte)0x84, (byte)0x82,
(byte)0x79, (byte)0xa7, (byte)0x22, (byte)0xc8,
(byte)0x06, (byte)0xb4, (byte)0x85, (byte)0xa4,
(byte)0x7e, (byte)0x67, (byte)0xc8, (byte)0x07,
(byte)0xb9, (byte)0x46, (byte)0xa3, (byte)0x37,
(byte)0xbe, (byte)0xe8, (byte)0x94, (byte)0x26,
(byte)0x74, (byte)0x27, (byte)0x88, (byte)0x59,
(byte)0xe1, (byte)0x32, (byte)0x92, (byte)0xfb
}
);
if (enabledAlgos.contains("HmacMD5")) {
threadRunnerMacTest("HmacMD5", "MD5", md5Vector);
}
if (enabledAlgos.contains("HmacSHA1")) {
threadRunnerMacTest("HmacSHA1", "SHA1", sha1Vector);
}
if (enabledAlgos.contains("HmacSHA256")) {
threadRunnerMacTest("HmacSHA256", "SHA256", sha256Vector);
}
if (enabledAlgos.contains("HmacSHA384")) {
threadRunnerMacTest("HmacSHA384", "SHA384", sha384Vector);
}
if (enabledAlgos.contains("HmacSHA512")) {
threadRunnerMacTest("HmacSHA512", "SHA512", sha512Vector);
}
}
private class HmacVector {
private byte key[];

View File

@ -26,6 +26,14 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
import java.security.MessageDigest;
@ -273,5 +281,66 @@ public class WolfCryptMessageDigestMd5Test {
MessageDigest md5 = MessageDigest.getInstance("MD5", "wolfJCE");
assertEquals(Md5.DIGEST_SIZE, md5.getDigestLength());
}
@Test
public void testMd5Threaded()
throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance(
"MD5", "wolfJCE");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
/* add empty array on failure, will error out below */
results.add(new byte[] {0});
}
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
md5.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = md5.digest();
results.add(hash.clone());
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -26,6 +26,14 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
import java.security.MessageDigest;
@ -262,5 +270,66 @@ public class WolfCryptMessageDigestSha256Test {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256", "wolfJCE");
assertEquals(Sha256.DIGEST_SIZE, sha256.getDigestLength());
}
@Test
public void testSha256Threaded()
throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance(
"SHA-256", "wolfJCE");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
/* add empty array on failure, will error out below */
results.add(new byte[] {0});
}
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -26,6 +26,14 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
import java.security.MessageDigest;
@ -319,5 +327,66 @@ public class WolfCryptMessageDigestSha384Test {
MessageDigest sha384 = MessageDigest.getInstance("SHA-384", "wolfJCE");
assertEquals(Sha384.DIGEST_SIZE, sha384.getDigestLength());
}
@Test
public void testSha384Threaded()
throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance(
"SHA-384", "wolfJCE");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
/* add empty array on failure, will error out below */
results.add(new byte[] {0});
}
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -26,6 +26,14 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
import java.security.MessageDigest;
@ -347,5 +355,66 @@ public class WolfCryptMessageDigestSha512Test {
MessageDigest sha512 = MessageDigest.getInstance("SHA-512", "wolfJCE");
assertEquals(Sha512.DIGEST_SIZE, sha512.getDigestLength());
}
@Test
public void testSha512Threaded()
throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance(
"SHA-512", "wolfJCE");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
/* add empty array on failure, will error out below */
results.add(new byte[] {0});
}
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -26,6 +26,14 @@ import org.junit.Test;
import org.junit.Assume;
import org.junit.BeforeClass;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
import java.security.MessageDigest;
@ -276,5 +284,66 @@ public class WolfCryptMessageDigestShaTest {
MessageDigest sha = MessageDigest.getInstance("SHA-1", "wolfJCE");
assertEquals(Sha.DIGEST_SIZE, sha.getDigestLength());
}
@Test
public void testShaThreaded()
throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance(
"SHA-1", "wolfJCE");
} catch (NoSuchAlgorithmException |
NoSuchProviderException e) {
/* add empty array on failure, will error out below */
results.add(new byte[] {0});
}
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -27,6 +27,12 @@ import org.junit.BeforeClass;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.Security;
import java.security.Provider;
@ -62,6 +68,9 @@ public class WolfCryptSignatureTest {
private static ArrayList<String> enabledAlgos =
new ArrayList<String>();
/* One static SecureRandom to share */
private static SecureRandom secureRandom = new SecureRandom();
@BeforeClass
public static void testProviderInstallationAtRuntime()
throws NoSuchProviderException {
@ -125,12 +134,8 @@ public class WolfCryptSignatureTest {
assertNotNull(signer);
assertNotNull(verifier);
SecureRandom rand =
SecureRandom.getInstance("HashDRBG", "wolfJCE");
assertNotNull(rand);
/* generate key pair */
KeyPair pair = generateKeyPair(enabledAlgos.get(i), rand);
KeyPair pair = generateKeyPair(enabledAlgos.get(i), secureRandom);
assertNotNull(pair);
PrivateKey priv = pair.getPrivate();
@ -174,12 +179,8 @@ public class WolfCryptSignatureTest {
assertNotNull(signer);
assertNotNull(verifier);
SecureRandom rand =
SecureRandom.getInstance("HashDRBG", "wolfJCE");
assertNotNull(rand);
/* generate key pair */
KeyPair pair = generateKeyPair(enabledAlgos.get(i), rand);
KeyPair pair = generateKeyPair(enabledAlgos.get(i), secureRandom);
assertNotNull(pair);
PrivateKey priv = pair.getPrivate();
@ -235,12 +236,8 @@ public class WolfCryptSignatureTest {
return;
}
SecureRandom rand =
SecureRandom.getInstance("HashDRBG", "wolfJCE");
assertNotNull(rand);
/* generate key pair */
KeyPair pair = generateKeyPair(enabledAlgos.get(i), rand);
KeyPair pair = generateKeyPair(enabledAlgos.get(i), secureRandom);
assertNotNull(pair);
PrivateKey priv = pair.getPrivate();
@ -291,12 +288,8 @@ public class WolfCryptSignatureTest {
return;
}
SecureRandom rand =
SecureRandom.getInstance("HashDRBG", "wolfJCE");
assertNotNull(rand);
/* generate key pair */
KeyPair pair = generateKeyPair(enabledAlgos.get(i), rand);
KeyPair pair = generateKeyPair(enabledAlgos.get(i), secureRandom);
assertNotNull(pair);
PrivateKey priv = pair.getPrivate();
@ -349,5 +342,125 @@ public class WolfCryptSignatureTest {
return pair;
}
private void threadRunnerSignVerify(byte[] inBuf, String algo)
throws InterruptedException {
int numThreads = 10;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final String currentAlgo = algo;
final byte[] toSignBuf = inBuf;
/* Do encrypt/decrypt and sign/verify in parallel across numThreads
* threads, all operations should pass */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
KeyPair pair = null;
KeyPairGenerator keyGen = null;
PrivateKey priv = null;
PublicKey pub = null;
Signature signer = null;
Signature verifier = null;
byte[] signature = null;
try {
signer = Signature.getInstance(
currentAlgo, "wolfJCE");
verifier = Signature.getInstance(
currentAlgo, "wolfJCE");
if (signer == null || verifier == null) {
failed = 1;
}
/* generate key pair */
if (failed == 0) {
if (currentAlgo.contains("RSA")) {
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, secureRandom);
pair = keyGen.generateKeyPair();
} else if (currentAlgo.contains("ECDSA")) {
keyGen = KeyPairGenerator.getInstance("EC",
"wolfJCE");
ECGenParameterSpec ecSpec =
new ECGenParameterSpec("secp521r1");
keyGen.initialize(ecSpec);
pair = keyGen.generateKeyPair();
}
if (pair == null) {
failed = 1;
}
else {
priv = pair.getPrivate();
pub = pair.getPublic();
}
}
if (failed == 0) {
/* generate signature */
signer.initSign(priv);
signer.update(toSignBuf, 0, toSignBuf.length);
signature = signer.sign();
/* verify signature */
verifier.initVerify(pub);
verifier.update(toSignBuf, 0, toSignBuf.length);
boolean verified = verifier.verify(signature);
if (verified == false) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in RSA sign/verify thread test");
}
}
}
@Test
public void testThreadedWolfSignWolfVerify() throws InterruptedException {
final String toSign = "Hello World";
final byte[] toSignBuf = toSign.getBytes();
/* run threaded test for each enabled Signature algorithm */
for (int i = 0; i < enabledAlgos.size(); i++) {
threadRunnerSignVerify(toSignBuf, enabledAlgos.get(i));
}
}
}

View File

@ -24,6 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import java.nio.ByteBuffer;
import javax.crypto.ShortBufferException;
@ -516,5 +523,86 @@ public class AesTest {
/* expected */
}
}
@Test
public void threadedAesTest() throws InterruptedException {
int numThreads = 50;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] rand2kBuf = new byte[2048];
final byte[] key = Util.h2b("2b7e151628aed2a6abf7158809cf4f3c");
final byte[] iv = Util.h2b("000102030405060708090A0B0C0D0E0F");
/* fill large input buffer with random bytes */
new Random().nextBytes(rand2kBuf);
/* encrypt / decrypt input data, make sure decrypted matches original */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int ret = 0;
Aes enc = new Aes(key, iv, Aes.ENCRYPT_MODE);
Aes dec = new Aes(key, iv, Aes.DECRYPT_MODE);
byte[] encrypted = new byte[2048];
byte[] plaintext = new byte[2048];
try {
/* encrypt in 128-byte chunks */
Arrays.fill(encrypted, (byte)0);
for (int j = 0; j < rand2kBuf.length; j+= 128) {
ret = enc.update(rand2kBuf, j, 128, encrypted, j);
if (ret != 128) {
throw new Exception(
"Aes.update(ENCRYPT_MODE) returned " + ret);
}
}
/* decrypt in 128-byte chunks */
Arrays.fill(plaintext, (byte)0);
for (int j = 0; j < encrypted.length; j+= 128) {
ret = dec.update(encrypted, j, 128, plaintext, j);
if (ret != 128) {
throw new Exception(
"Aes.update(DECRYPT_MODE) returned " + ret);
}
}
/* make sure decrypted is same as input */
if (Arrays.equals(rand2kBuf, plaintext)) {
results.add(0);
}
else {
/* not equal, error case */
results.add(1);
}
} catch (Exception e) {
e.printStackTrace();
results.add(1);
} finally {
enc.releaseNativeStruct();
dec.releaseNativeStruct();
latch.countDown();
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in AES thread test");
}
}
}
}

View File

@ -23,6 +23,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.nio.ByteBuffer;
import javax.crypto.ShortBufferException;
@ -236,5 +243,87 @@ public class Des3Test {
enc.releaseNativeStruct();
dec.releaseNativeStruct();
}
@Test
public void threadedDes3Test() throws InterruptedException {
int numThreads = 50;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] rand2kBuf = new byte[2048];
final byte[] key = Util.h2b("e61a38548694f1fd8cef251c518" +
"cc70bb613751c1ce52aa8");
final byte[] iv = Util.h2b("48a8ceb8551fd4ad");
/* fill large input buffer with random bytes */
new Random().nextBytes(rand2kBuf);
/* encrypt / decrypt input data, make sure decrypted matches original */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int ret = 0;
Des3 enc = new Des3(key, iv, Des3.ENCRYPT_MODE);
Des3 dec = new Des3(key, iv, Des3.DECRYPT_MODE);
byte[] encrypted = new byte[2048];
byte[] plaintext = new byte[2048];
try {
/* encrypt in 128-byte chunks */
Arrays.fill(encrypted, (byte)0);
for (int j = 0; j < rand2kBuf.length; j+= 128) {
ret = enc.update(rand2kBuf, j, 128, encrypted, j);
if (ret != 128) {
throw new Exception(
"Des3.update(ENCRYPT_MODE) returned " + ret);
}
}
/* decrypt in 128-byte chunks */
Arrays.fill(plaintext, (byte)0);
for (int j = 0; j < encrypted.length; j+= 128) {
ret = dec.update(encrypted, j, 128, plaintext, j);
if (ret != 128) {
throw new Exception(
"Des3.update(DECRYPT_MODE) returned " + ret);
}
}
/* make sure decrypted is same as input */
if (Arrays.equals(rand2kBuf, plaintext)) {
results.add(0);
}
else {
/* not equal, error case */
results.add(1);
}
} catch (Exception e) {
e.printStackTrace();
results.add(1);
} finally {
enc.releaseNativeStruct();
dec.releaseNativeStruct();
latch.countDown();
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in 3DES thread test");
}
}
}
}

View File

@ -27,6 +27,14 @@ import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import com.wolfssl.wolfcrypt.Dh;
import com.wolfssl.wolfcrypt.Rng;
import com.wolfssl.wolfcrypt.WolfCryptError;
@ -35,6 +43,7 @@ import com.wolfssl.wolfcrypt.Fips;
public class DhTest {
private static Rng rng = new Rng();
private final Object rngLock = new Rng();
@BeforeClass
public static void setUpRng() {
@ -74,8 +83,10 @@ public class DhTest {
assertNull(alice.getPublicKey());
assertNull(bob.getPublicKey());
alice.makeKey(rng);
bob.makeKey(rng);
synchronized (rngLock) {
alice.makeKey(rng);
bob.makeKey(rng);
}
assertNotNull(alice.getPublicKey());
assertNotNull(bob.getPublicKey());
@ -87,4 +98,102 @@ public class DhTest {
assertNotNull(sharedSecretB);
assertArrayEquals(sharedSecretA, sharedSecretB);
}
@Test
public void threadedDhSharedSecretTest() throws InterruptedException {
int numThreads = 10;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] p = Util.h2b(
"E6969D3D495BE32C7CF180C3BDD4798E91B7818251BB055E"
+ "2A2064904A79A770FA15A259CBD523A6A6EF09C43048D5A22F971F3C20"
+ "129B48000E6EDD061CBC053E371D794E5327DF611EBBBE1BAC9B5C6044"
+ "CF023D76E05EEA9BAD991B13A63C974E9EF1839EB5DB125136F7262E56"
+ "A8871538DFD823C6505085E21F0DD5C86B");
final byte[] g = Util.h2b("02");
/* make sure alice and bob shared secret generation matches when done
* in parallel over numThreads threads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
Dh alice = null;
Dh bob = null;
try {
alice = new Dh(p, g);
bob = new Dh();
bob.setParams(p, g);
/* keys should be null before generation */
if (alice.getPublicKey() != null ||
bob.getPublicKey() != null) {
failed = 1;
}
/* generate Dh keys */
if (failed == 0) {
synchronized (rngLock) {
alice.makeKey(rng);
bob.makeKey(rng);
}
}
/* keys should not be null after generation */
if (failed == 0) {
if (alice.getPublicKey() == null ||
bob.getPublicKey() == null) {
failed = 1;
}
}
if (failed == 0) {
byte[] sharedSecretA = alice.makeSharedSecret(bob);
byte[] sharedSecretB = bob.makeSharedSecret(alice);
if (sharedSecretA == null ||
sharedSecretB == null ||
!Arrays.equals(sharedSecretA, sharedSecretB)) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
alice.releaseNativeStruct();
bob.releaseNativeStruct();
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in DH shared secret thread test");
}
}
}
}

View File

@ -27,6 +27,14 @@ import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.spec.ECGenParameterSpec;
@ -43,10 +51,13 @@ import com.wolfssl.wolfcrypt.WolfCryptException;
public class EccTest {
private static Rng rng = new Rng();
private static final Object rngLock = new Rng();
@BeforeClass
public static void setUpRng() {
rng.init();
synchronized (rngLock) {
rng.init();
}
}
@BeforeClass
@ -71,8 +82,10 @@ public class EccTest {
Ecc bob = new Ecc();
Ecc aliceX963 = new Ecc();
alice.makeKey(rng, 66);
bob.makeKey(rng, 66);
synchronized (rngLock) {
alice.makeKey(rng, 66);
bob.makeKey(rng, 66);
}
aliceX963.importX963(alice.exportX963());
byte[] sharedSecretA = alice.makeSharedSecret(bob);
@ -112,7 +125,10 @@ public class EccTest {
byte[] hash = "Everyone gets Friday off. ecc p".getBytes();
byte[] signature = alice.sign(hash, rng);
byte[] signature = null;
synchronized (rngLock) {
signature = alice.sign(hash, rng);
}
assertTrue(bob.verify(hash, signature));
@ -157,11 +173,15 @@ public class EccTest {
@Test
public void eccMakeKeyOnCurve() {
Ecc alice = new Ecc();
alice.makeKeyOnCurve(rng, 32, "secp256r1");
synchronized (rngLock) {
alice.makeKeyOnCurve(rng, 32, "secp256r1");
}
try {
alice = new Ecc();
alice.makeKeyOnCurve(rng, 32, "BADCURVE");
synchronized (rngLock) {
alice.makeKeyOnCurve(rng, 32, "BADCURVE");
}
fail("Creating ECC key on bad curve should fail with exception");
} catch (WolfCryptException e) {
/* should throw exception here */
@ -300,5 +320,199 @@ public class EccTest {
assertEquals(curveName, "SECP256R1");
}
@Test
public void threadedEccSharedSecretTest() throws InterruptedException {
int numThreads = 20;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
/* make sure alice and bob shared secret generation matches when done
* in parallel over numThreads threads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
Ecc alice = null;
Ecc bob = null;
Ecc aliceX963 = null;
Ecc alice2 = null;
try {
alice = new Ecc();
bob = new Ecc();
aliceX963 = new Ecc();
synchronized (rngLock) {
alice.makeKey(rng, 66);
bob.makeKey(rng, 66);
}
aliceX963.importX963(alice.exportX963());
byte[] sharedSecretA = alice.makeSharedSecret(bob);
byte[] sharedSecretB = bob.makeSharedSecret(aliceX963);
if (!Arrays.equals(sharedSecretA, sharedSecretB)) {
failed = 1;
}
if (failed == 0) {
alice2 = new Ecc();
alice2.importPrivate(alice.exportPrivate(),
alice.exportX963());
if (!Arrays.equals(sharedSecretA,
alice2.makeSharedSecret(bob))) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
alice.releaseNativeStruct();
alice2.releaseNativeStruct();
aliceX963.releaseNativeStruct();
bob.releaseNativeStruct();
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in ECC shared secret thread test");
}
}
}
@Test
public void threadedEccSignVerifyTest() throws InterruptedException {
int numThreads = 10;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] prvKey = Util.h2b("30770201010420F8CF92"
+ "6BBD1E28F1A8ABA1234F3274188850AD7EC7EC92"
+ "F88F974DAF568965C7A00A06082A8648CE3D0301"
+ "07A1440342000455BFF40F44509A3DCE9BB7F0C5"
+ "4DF5707BD4EC248E1980EC5A4CA22403622C9BDA"
+ "EFA2351243847616C6569506CC01A9BDF6751A42"
+ "F7BDA9B236225FC75D7FB4");
final byte[] pubKey = Util.h2b("3059301306072A8648CE"
+ "3D020106082A8648CE3D0301070342000455BFF4"
+ "0F44509A3DCE9BB7F0C54DF5707BD4EC248E1980"
+ "EC5A4CA22403622C9BDAEFA2351243847616C656"
+ "9506CC01A9BDF6751A42F7BDA9B236225FC75D7FB4");
final byte[] hash = "Everyone gets Friday off. ecc p".getBytes();
/* Do sign/verify in each thread, in parallel across numThreads threads,
* all operations should pass */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
Ecc alice = null;
Ecc bob = null;
Ecc aliceX963 = null;
Ecc alice2 = null;
try {
alice = new Ecc();
bob = new Ecc();
aliceX963 = new Ecc();
/* import keys */
alice.privateKeyDecode(prvKey);
bob.publicKeyDecode(pubKey);
/* alice sign */
byte[] signature = null;
synchronized (rngLock) {
signature = alice.sign(hash, rng);
}
/* bob verify */
if (bob.verify(hash, signature) != true) {
failed = 1;
}
/* test alice verify with export/import pub key */
if (failed == 0) {
aliceX963.importX963(alice.exportX963());
if (aliceX963.verify(hash, signature) != true) {
failed = 1;
}
}
/* test alice verify with export/import priv key */
if (failed == 0) {
alice2 = new Ecc();
alice2.importPrivate(alice.exportPrivate(),
alice.exportX963());
if (alice2.verify(hash, signature) != true) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
alice.releaseNativeStruct();
alice2.releaseNativeStruct();
aliceX963.releaseNativeStruct();
bob.releaseNativeStruct();
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in ECC sign/verify thread test");
}
}
}
}

View File

@ -29,6 +29,15 @@ import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import com.wolfssl.wolfcrypt.Hmac;
import com.wolfssl.wolfcrypt.NativeStruct;
import com.wolfssl.wolfcrypt.WolfCryptError;
@ -253,4 +262,153 @@ public class HmacTest {
}
}
}
private void threadRunnerHmacTest(int hmacType, byte[] inKey,
byte[] inData, byte[] inExpected)
throws InterruptedException {
int numThreads = 20;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final int type = hmacType;
final byte[] key = inKey;
final byte[] data = inData;
final byte[] expected = inExpected;
/* Do HMAC across numThread threads, all should be successful */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
Hmac hmac = null;
try {
hmac = new Hmac();
hmac.setKey(type, key);
hmac.update(data);
if (!Arrays.equals(expected, hmac.doFinal())) {
failed = 1;
}
if (failed == 0) {
hmac.reset();
hmac.update(data);
if (!Arrays.equals(expected, hmac.doFinal())) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in HMAC thread test");
}
}
}
@Test
public void testThreadedHmac() throws InterruptedException {
if (Hmac.SHA != -1) {
threadRunnerHmacTest(Hmac.SHA,
Util.h2b("fd42f5044e3f70825102017f8521"), /* key */
Util.h2b("c9995cad63f60f7c7c552ac12c08" + /* data */
"0a7262cec4636d47c460c2abb47a" +
"f9bca09e18f9576c1415144595a7" +
"5da6fa232cb59d094d1a585c0710" +
"4856febcd05a58bde12a1f04795a" +
"e6e66a05b06f5dbe0dfa16c986fe" +
"fa8c3b2bce40cbb6c1ec74f1ad94" +
"7c1e9aadcf8584d5e9c45ec1f667" +
"567738b85bbdaad8dcd1e30fd35a" +
"3c61"),
Util.h2b("8865eb9df41dcc2e74360f0c97ae" + /* expected */
"567cb2377022")
);
}
if (Hmac.SHA256 != -1) {
threadRunnerHmacTest(Hmac.SHA256,
Util.h2b("26afdd2445b1f3cecbd4a797fed8"), /* key */
Util.h2b("bd74f8646cdd9b217927b04ef4ee" + /* data */
"ef0b8ef0b78fafcabb11c202f8e8" +
"d44aeaf15d03ff315d014cbbab8e" +
"7ed48ab114567eb0cc525ed35bf9" +
"a96b61bd1d139cb386365c3cd5d1" +
"37e4717afd8ad2a2efc24b172b77" +
"27cc6bd5f8ddef652cceb87ae114" +
"f7cdfbd6c56473f414b8f149e616" +
"9e2dbd46333e526b5761892a2703" +
"a50e"),
Util.h2b("208661dd6bdeab1c2843dfb8226c" + /* expected */
"be0a69db31aa183004e12025039f" +
"9fc2446a")
);
}
if (Hmac.SHA384 != -1) {
threadRunnerHmacTest(Hmac.SHA384,
Util.h2b("d35d6a733af2947fbdb4a67f5b3d"), /* key */
Util.h2b("44a8e36ec9b42a94a9627bd391f7" + /* data */
"114dad4296d31c3639a8a1d80188" +
"9b5c61e9378a0c81e4670a080712" +
"0c3ff0ecfd310dfbd9b95e91c244" +
"292851d8ef912a569e4ed3fc083c" +
"c62d9475c47534746dc8977a0e0a" +
"9f31bad5158f9c769cfe8b38e3ba" +
"dfe61f7a838bb9524c7c43d88998" +
"b186dccfc65f48e1ccd58a6888eb" +
"ad19"),
Util.h2b("346ff5f9b77866d72154b6b6965f" + /* expected */
"1f56e7c21ddf3392bdbe12e5dffb" +
"1d75e2f0d919c1e133c83b9b56d3" +
"17c3db1364de")
);
}
if (Hmac.SHA512 != -1) {
threadRunnerHmacTest(Hmac.SHA512,
Util.h2b("c3ec1135bb477eb81ca421deb9e0"), /* key */
Util.h2b("837dbbb0371bf60082c788c8f16f" + /* data */
"f883dd9216d235f7decf7ea09f9e" +
"17fa5d46c25673bf609c7c4dfc3e" +
"740c0b6c1bcbf2879a1dc9d769ae" +
"5f8070d47eb26d66702195d1c1b5" +
"7e6847823cfc60facbad7b61adff" +
"da82d33196a1c1cae3b0ee7495c6" +
"690de3ccc2fc6b7a28c17782cfd0" +
"7f0a95a0ef60e4ff29e9daa8ce5b" +
"a717"),
Util.h2b("517bd0146fe52cb464a0d555a7c2" + /* expected */
"9b5f9a604b07f32ff255f139156e" +
"214b6eb3836aa089987a5aca585e" +
"3cb10af8cb19c12a89628e8f59b6" +
"952ac4b7da7131f0")
);
}
}
}

View File

@ -24,6 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import org.junit.Test;
@ -202,5 +209,55 @@ public class Md5Test {
md5.releaseNativeStruct();
md5Copy.releaseNativeStruct();
}
@Test
public void threadedHashTest() throws InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
Md5 md5 = new Md5();
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
md5.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = md5.digest();
results.add(hash.clone());
md5.releaseNativeStruct();
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -29,6 +29,14 @@ import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import com.wolfssl.wolfcrypt.Rsa;
import com.wolfssl.wolfcrypt.Rng;
import com.wolfssl.wolfcrypt.Fips;
@ -367,4 +375,136 @@ public class RsaTest {
assertArrayEquals(plaintext, pub.verify(signature));
}
@Test
public void threadedRsaSignVerifyTest() throws InterruptedException {
int numThreads = 20;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<Integer> results = new LinkedBlockingQueue<>();
final byte[] prvKey = Util
.h2b("308204a40201000282010100c303d12bfe39a432453b53c8842b2a7c"
+ "749abdaa2a520747d6a636b207328ed0ba697bc6c3449ed48148"
+ "fd2d68a28b67bba175c8362c4ad21bf78bbacf0df9efecf1811e"
+ "7b9b03479abf65cc7f652469a6e814895be434f7c5b01493f567"
+ "7b3a7a78e101565691a613428dd23c409c4cefd186df37511b0c"
+ "a13bf5f1a34a35e4e1ce96df1b7ebf4e97d010e8a8083081af20"
+ "0b4314c57467b432826f8d86c28840993683ba1e40722217d752"
+ "652473b0ceef19cdaeff786c7bc01203d44e720d506d3ba33ba3"
+ "995e9dc8d90c85b3d98ad95426db6dfaacbbff254cc4d179f471"
+ "d386401813b063b5724e30c49784862d562fd715f77fc0aef5fc"
+ "5be5fba1bad302030100010282010100a2e6d85f107164089e2e"
+ "6dd16d1e85d20ab18c47ce2c516aa0129e53de914c1d6dea597b"
+ "f277aad9c6d98aabd8e116e46326ffb56c1359b8e3a5c872172e"
+ "0c9f6fe5593f766f49b111c25a2e16290ddeb78edc40d5a2eee0"
+ "1ea1f4be97db86639614cd9809602d30769c3ccde688ee479279"
+ "0b5a00e25e5f117c7df908b72006892a5dfd00ab22e1f0b3bc24"
+ "a95e260e1f002dfe219a535b6dd32bab9482684336d8f62fc622"
+ "fcb5415d0d3360eaa47d7ee84b559156d35c578f1f94172faade"
+ "e99ea8f4cf8a4c8ea0e45673b2cf4f86c5693cf324208b5c960c"
+ "fa6b123b9a67c1dfc696b2a5d5920d9b094268241045d450e417"
+ "3948d0358b946d11de8fca5902818100ea24a7f96933e971dc52"
+ "7d8821282f49deba7216e9cc477a880d94578458163a81b03fa2"
+ "cfa66c1eb00629008fe77776acdbcac7d95e9b3f269052aefc38"
+ "900014bbb40f5894e72f6a7e1c4f4121d431591f4e8a1a8da757"
+ "6c22d8e5f47e32a610cb64a5550387a627058cc3d7b627b24dba"
+ "30da478f54d33d8b848d949858a502818100d5381bc38fc5930c"
+ "470b6f3592c5b08d46c892188ff5800af7efa1fe80b9b52abaca"
+ "18b05da507d0938dd89c041cd4628ea6268101ffce8a2a633435"
+ "40aa6d80de89236a574d9e6ead934e56900b6d9d738b0cae273d"
+ "de4ef0aac56c78676c94529c37676c2defbbafdfa6903cc447cf"
+ "8d969e98a9b49fc5a650dcb3f0fb74170281805e830962bdba7c"
+ "a2bf4274f57c1cd269c9040d857e3e3d2412c3187bf329f35f0e"
+ "766c5975e44184699d32f3cd22abb035ba4ab23ce5d958b6624f"
+ "5ddee59e0aca53b22cf79eb36b0a5b7965ec6e914e9220f6fcfc"
+ "16edd3760ce2ec7fb269136b780e5a4664b45eb725a05a753a4b"
+ "efc73c3ef7fd26b820c4990a9a73bec31902818100ba449314ac"
+ "34193b5f9160acf7b4d681053651533de865dcaf2edc613ec97d"
+ "b87f87f03b9b03822937ce724e11d5b1c10c07a099914a8d7fec"
+ "79cff139b5e985ec62f7da7dbc644d223c0ef2d651f587d899c0"
+ "11205d0f29fd5be2aed91cd921566dfc84d05fed10151c1821e7"
+ "c43d4bd7d09e6a95cf22c9037b9ee36001fc2f02818011d04bcf"
+ "1b67b99f1075478665ae31c2c630ac590650d90fb57006f7f0d3"
+ "c8627ca8da6ef6213fd37f5fea8aab3fd92a5ef351d2c23037e3"
+ "2da3750d1e4d2134d557705c89bf72ec4a6e68d5cd1874334e8c"
+ "3a458fe69640eb63f919863a51dd894bb0f3f99f5d289538be35"
+ "abca5ce7935334a1455d1339654246a19fcdf5bf");
final byte[] plaintext = "Now is the time for all".getBytes();
/* Do encrypt/decrypt and sign/verify in parallel across numThreads
* threads, all operations should pass */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
int failed = 0;
Rsa priv = null;
Rsa pub = null;
byte[] n_out = new byte[256];
byte[] e_out = new byte[3];
long[] n_len = new long[1];
long[] e_len = new long[1];
n_len[0] = n_out.length;
e_len[0] = e_out.length;
try {
priv = new Rsa(prvKey);
priv.exportRawPublicKey(n_out, n_len, e_out, e_len);
priv.setRng(rng);
pub = new Rsa(n_out, e_out);
byte[] ciphertext = pub.encrypt(plaintext, rng);
if (!Arrays.equals(plaintext,
priv.decrypt(ciphertext))) {
failed = 1;
}
if (failed == 0) {
byte[] signature = priv.sign(plaintext, rng);
if (!Arrays.equals(plaintext,
pub.verify(signature))) {
failed = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
failed = 1;
} finally {
priv.releaseNativeStruct();
pub.releaseNativeStruct();
latch.countDown();
}
if (failed == 1) {
results.add(1);
}
else {
results.add(0);
}
}
});
}
/* wait for all threads to complete */
latch.await();
/* Look for any failures that happened */
Iterator<Integer> listIterator = results.iterator();
while (listIterator.hasNext()) {
Integer cur = listIterator.next();
if (cur == 1) {
fail("Threading error in RSA sign/verify thread test");
}
}
}
}

View File

@ -24,7 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import org.junit.Test;
@ -187,4 +193,55 @@ public class Sha256Test {
sha.releaseNativeStruct();
shaCopy.releaseNativeStruct();
}
@Test
public void threadedHashTest() throws InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
Sha256 sha = new Sha256();
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
sha.releaseNativeStruct();
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -24,7 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import org.junit.Test;
@ -199,4 +205,54 @@ public class Sha384Test {
sha.releaseNativeStruct();
shaCopy.releaseNativeStruct();
}
@Test
public void threadedHashTest() throws InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
Sha384 sha = new Sha384();
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
sha.releaseNativeStruct();
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -24,7 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import org.junit.Test;
@ -203,4 +209,54 @@ public class Sha512Test {
sha.releaseNativeStruct();
shaCopy.releaseNativeStruct();
}
@Test
public void threadedHashTest() throws InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
Sha512 sha = new Sha512();
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
sha.releaseNativeStruct();
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}

View File

@ -24,6 +24,13 @@ package com.wolfssl.wolfcrypt.test;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import javax.crypto.ShortBufferException;
import org.junit.Test;
@ -184,5 +191,55 @@ public class ShaTest {
sha.releaseNativeStruct();
shaCopy.releaseNativeStruct();
}
@Test
public void threadedHashTest() throws InterruptedException {
int numThreads = 100;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
final LinkedBlockingQueue<byte[]> results = new LinkedBlockingQueue<>();
final byte[] rand10kBuf = new byte[10240];
/* fill large input buffer with random bytes */
new Random().nextBytes(rand10kBuf);
/* generate hash over input data concurrently across numThreads */
for (int i = 0; i < numThreads; i++) {
service.submit(new Runnable() {
@Override public void run() {
Sha sha = new Sha();
/* process/update in 1024-byte chunks */
for (int j = 0; j < rand10kBuf.length; j+= 1024) {
sha.update(rand10kBuf, j, 1024);
}
/* get final hash */
byte[] hash = sha.digest();
results.add(hash.clone());
sha.releaseNativeStruct();
latch.countDown();
}
});
}
/* wait for all threads to complete */
latch.await();
/* compare all digests, all should be the same across threads */
Iterator<byte[]> listIterator = results.iterator();
byte[] current = listIterator.next();
while (listIterator.hasNext()) {
byte[] next = listIterator.next();
if (!Arrays.equals(current, next)) {
fail("Found two non-identical digests in thread test");
}
if (listIterator.hasNext()) {
current = listIterator.next();
}
}
}
}