JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_RSA_doSign (JNIEnv* jenv, jobject jcl, jobject in, jlong inSz, jobject out, jintArray outSz, jobject keyDer, jlong keySz) { int ret; RNG rng; RsaKey myKey; unsigned int idx; unsigned int tmpOut; /* check in and key sz */ if ((inSz < 0) || (keySz < 0)) { return -1; } /* get pointers to our buffers */ unsigned char* inBuf = (*jenv)->GetDirectBufferAddress(jenv, in); if (inBuf == NULL) { printf("problem getting in buffer address\n"); return -1; } unsigned char* outBuf = (*jenv)->GetDirectBufferAddress(jenv, out); if (outBuf == NULL) { printf("problem getting out buffer address\n"); return -1; } unsigned char* keyBuf = (*jenv)->GetDirectBufferAddress(jenv, keyDer); if (keyBuf == NULL) { printf("problem getting key buffer address\n"); return -1; } /* get output buffer size */ (*jenv)->GetIntArrayRegion(jenv, outSz, 0, 1, (jint*)&tmpOut); wc_InitRng(&rng); wc_InitRsaKey(&myKey, NULL); idx = 0; ret = wc_RsaPrivateKeyDecode(keyBuf, &idx, &myKey, (unsigned int)keySz); if (ret == 0) { ret = wc_RsaSSL_Sign(inBuf, (unsigned int)inSz, outBuf, tmpOut, &myKey, &rng); if (ret > 0) { /* save and convert to 0 for success */ (*jenv)->SetIntArrayRegion(jenv, outSz, 0, 1, (jint*)&tmpOut); ret = 0; } } else { printf("wc_RsaPrivateKeyDecode failed, ret = %d\n", ret); } wc_FreeRsaKey(&myKey); return ret; }
int init_trng() { PRINTF("- initializing random number generator\r\n"); trng_config_t trngConfig; TRNG_GetDefaultConfig(&trngConfig); trngConfig.sampleMode = kTRNG_SampleModeVonNeumann; int r = TRNG_Init(TRNG0, &trngConfig); return r == kStatus_Success ? wc_InitRng(&rng) : r; }
/* check mcapi rng */ static int check_rng(void) { int ret; int i; byte in[RANDOM_BYTE_SZ]; byte out[RANDOM_BYTE_SZ]; for (i = 0; i < RANDOM_BYTE_SZ; i++) in[i] = (byte)i; for (i = 0; i < RANDOM_BYTE_SZ; i++) out[i] = (byte)i; ret = wc_InitRng(&defRng); if (ret != 0) { printf("default rng init failed\n"); return -1; } ret = CRYPT_RNG_Initialize(&mcRng); if (ret != 0) { printf("mcapi rng init failed\n"); return -1; } ret = CRYPT_RNG_Get(&mcRng, &out[0]); if (ret != 0) { printf("mcapi rng get failed\n"); return -1; } ret = CRYPT_RNG_BlockGenerate(&mcRng, out, RANDOM_BYTE_SZ); if (ret != 0) { printf("mcapi rng block gen failed\n"); return -1; } if (memcmp(in, out, RANDOM_BYTE_SZ) == 0) { printf("mcapi rng block gen output failed\n"); return -1; } printf("rng mcapi test passed\n"); return 0; }
bool uc_init() { if (initialized) return true; trng_config_t trngConfig; TRNG_GetDefaultConfig(&trngConfig); trngConfig.sampleMode = kTRNG_SampleModeVonNeumann; if (TRNG_Init(TRNG0, &trngConfig) != kStatus_Success) return false; if (wc_InitRng(&uc_random)) return false; #if !FSL_FEATURE_SOC_LTC_COUNT PRINTF("- no LTC available\r\n"); #else LTC_Init(LTC0); #endif initialized = true; return true; }
/* Create a random reply. * * reply The buffer to put the random data into. * replyLen The amount of data to generate. */ static void RandomReply(char* reply, int replyLen) { int ret; WC_RNG rng; ret = wc_InitRng(&rng); if (ret != 0) { fprintf(stderr, "Error: initialize random\n"); exit(EXIT_FAILURE); } ret = wc_RNG_GenerateBlock(&rng, (byte*)reply, replyLen); wc_FreeRng(&rng); if (ret != 0) { fprintf(stderr, "Error: initialize random\n"); exit(EXIT_FAILURE); } }
int main() { int ret; wolfCrypt_Init(); ret = wc_InitRng(&mRng); if (ret != 0) { printf("Init RNG failed %d\n", ret); } StackSizeCheck(NULL, do_it); printf("sizeof RNG = %lu\n", sizeof(WC_RNG)); printf("sizeof ecc_key = %lu\n", sizeof(ecc_key)); ret = wc_FreeRng(&mRng); if (ret != 0) { printf("Free RNG failed %d\n", ret); } wolfCrypt_Cleanup(); return 0; }
/* * Decrypts a file using AES */ int AesDecrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { RNG rng; byte iv[AES_BLOCK_SIZE]; byte* input; byte* output; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int length; int aSize; fseek(inFile, 0, SEEK_END); length = ftell(inFile); fseek(inFile, 0, SEEK_SET); aSize = length; input = malloc(aSize); output = malloc(aSize); wc_InitRng(&rng); /* reads from inFile and writes whatever is there to the input array */ ret = fread(input, 1, length, inFile); if (ret == 0) { printf("Input file does not exist.\n"); return -1010; } for (i = 0; i < SALT_SIZE; i++) { /* finds salt from input message */ salt[i] = input[i]; } for (i = SALT_SIZE; i < AES_BLOCK_SIZE + SALT_SIZE; i++) { /* finds iv from input message */ iv[i - SALT_SIZE] = input[i]; } /* replicates old key if keys match */ ret = wc_PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, size, WC_SHA256); if (ret != 0) return -1050; /* sets key */ ret = wc_AesSetKey(aes, key, AES_BLOCK_SIZE, iv, AES_DECRYPTION); if (ret != 0) return -1002; /* change length to remove salt/iv block from being decrypted */ length -= (AES_BLOCK_SIZE + SALT_SIZE); for (i = 0; i < length; i++) { /* shifts message: ignores salt/iv on message*/ input[i] = input[i + (AES_BLOCK_SIZE + SALT_SIZE)]; } /* decrypts the message to output based on input length + padding*/ ret = wc_AesCbcDecrypt(aes, output, input, length); if (ret != 0) return -1006; if (salt[0] != 0) { /* reduces length based on number of padded elements */ length -= output[length-1]; } /* writes output to the outFile based on shortened length */ fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ memset(input, 0, aSize); memset(output, 0, aSize); memset(key, 0, size); free(input); free(output); free(key); fclose(inFile); fclose(outFile); wc_FreeRng(&rng); return 0; }
/* * benchmarking funciton */ int wolfCLU_benchmark(int timer, int* option) { int i = 0; /* A looping variable */ int loop = 1; /* benchmarking loop */ int64_t blocks = 0; /* blocks used during benchmarking */ #ifndef NO_AES Aes aes; /* aes declaration */ #endif #ifndef NO_DES3 Des3 des3; /* 3des declaration */ #endif RNG rng; /* random number generator */ int ret = 0; /* return variable */ double stop = 0.0; /* stop breaks loop */ double start; /* start time */ double currTime; /* current time*/ ALIGN16 byte* plain; /* plain text */ ALIGN16 byte* cipher; /* cipher */ ALIGN16 byte* key; /* key for testing */ ALIGN16 byte* iv; /* iv for initial encoding */ byte* digest; /* message digest */ wc_InitRng(&rng); signal(SIGALRM, wolfCLU_stop); i = 0; #ifndef NO_AES /* aes test */ if (option[i] == 1) { plain = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { return MEMORY_E; } cipher = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (cipher == NULL) { wolfCLU_freeBins(plain, NULL, NULL, NULL, NULL); return MEMORY_E; } key = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (key == NULL) { wolfCLU_freeBins(plain, cipher, NULL, NULL, NULL); return MEMORY_E; } iv = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (iv == NULL) { wolfCLU_freeBins(plain, cipher, key, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, cipher, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, key, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); start = wolfCLU_getTime(); alarm(timer); wc_AesSetKey(&aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION); while (loop) { wc_AesCbcEncrypt(&aes, cipher, plain, AES_BLOCK_SIZE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } printf("\n"); printf("AES-CBC "); wolfCLU_stats(start, AES_BLOCK_SIZE, blocks); XMEMSET(plain, 0, AES_BLOCK_SIZE); XMEMSET(cipher, 0, AES_BLOCK_SIZE); XMEMSET(key, 0, AES_BLOCK_SIZE); XMEMSET(iv, 0, AES_BLOCK_SIZE); wolfCLU_freeBins(plain, cipher, key, iv, NULL); blocks = 0; loop = 1; } i++; #endif #ifdef WOLFSSL_AES_COUNTER /* aes-ctr test */ if (option[i] == 1) { plain = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { return MEMORY_E; } cipher = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (cipher == NULL) { wolfCLU_freeBins(plain, NULL, NULL, NULL, NULL); return MEMORY_E; } key = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (key == NULL) { wolfCLU_freeBins(plain, cipher, NULL, NULL, NULL); return MEMORY_E; } iv = XMALLOC(AES_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (iv == NULL) { wolfCLU_freeBins(plain, cipher, key, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, cipher, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, key, AES_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); start = wolfCLU_getTime(); alarm(timer); wc_AesSetKeyDirect(&aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION); while (loop) { wc_AesCtrEncrypt(&aes, cipher, plain, AES_BLOCK_SIZE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } printf("AES-CTR "); wolfCLU_stats(start, AES_BLOCK_SIZE, blocks); XMEMSET(plain, 0, AES_BLOCK_SIZE); XMEMSET(cipher, 0, AES_BLOCK_SIZE); XMEMSET(key, 0, AES_BLOCK_SIZE); XMEMSET(iv, 0, AES_BLOCK_SIZE); wolfCLU_freeBins(plain, cipher, key, iv, NULL); blocks = 0; loop = 1; } i++; #endif #ifndef NO_DES3 /* 3des test */ if (option[i] == 1) { plain = XMALLOC(DES3_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { return MEMORY_E; } cipher = XMALLOC(DES3_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (cipher == NULL) { wolfCLU_freeBins(plain, NULL, NULL, NULL, NULL); return MEMORY_E; } key = XMALLOC(DES3_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (key == NULL) { wolfCLU_freeBins(plain, cipher, NULL, NULL, NULL); return MEMORY_E; } iv = XMALLOC(DES3_BLOCK_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (iv == NULL) { wolfCLU_freeBins(plain, cipher, key, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, DES3_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, cipher, DES3_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, key, DES3_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, iv, DES3_BLOCK_SIZE); start = wolfCLU_getTime(); alarm(timer); wc_Des3_SetKey(&des3, key, iv, DES_ENCRYPTION); while (loop) { wc_Des3_CbcEncrypt(&des3, cipher, plain, DES3_BLOCK_SIZE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } printf("3DES "); wolfCLU_stats(start, DES3_BLOCK_SIZE, blocks); XMEMSET(plain, 0, DES3_BLOCK_SIZE); XMEMSET(cipher, 0, DES3_BLOCK_SIZE); XMEMSET(key, 0, DES3_BLOCK_SIZE); XMEMSET(iv, 0, DES3_BLOCK_SIZE); wolfCLU_freeBins(plain, cipher, key, iv, NULL); blocks = 0; loop = 1; } i++; #endif #ifdef HAVE_CAMELLIA #define CAM_SZ CAMELLIA_BLOCK_SIZE /* camellia test */ if (option[i] == 1) { Camellia camellia; plain = XMALLOC(CAM_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { return MEMORY_E; } cipher = XMALLOC(CAM_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (cipher == NULL) { wolfCLU_freeBins(plain, NULL, NULL, NULL, NULL); return MEMORY_E; } key = XMALLOC(CAM_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (key == NULL) { wolfCLU_freeBins(plain, cipher, NULL, NULL, NULL); return MEMORY_E; } iv = XMALLOC(CAM_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (iv == NULL) { wolfCLU_freeBins(plain, cipher, key, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, CAMELLIA_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, cipher, CAMELLIA_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, key, CAMELLIA_BLOCK_SIZE); wc_RNG_GenerateBlock(&rng, iv, CAMELLIA_BLOCK_SIZE); start = wolfCLU_getTime(); alarm(timer); wc_CamelliaSetKey(&camellia, key, CAMELLIA_BLOCK_SIZE, iv); while (loop) { wc_CamelliaCbcEncrypt(&camellia, cipher, plain, CAMELLIA_BLOCK_SIZE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } printf("Camellia "); wolfCLU_stats(start, CAMELLIA_BLOCK_SIZE, blocks); XMEMSET(plain, 0, CAMELLIA_BLOCK_SIZE); XMEMSET(cipher, 0, CAMELLIA_BLOCK_SIZE); XMEMSET(key, 0, CAMELLIA_BLOCK_SIZE); XMEMSET(iv, 0, CAMELLIA_BLOCK_SIZE); wolfCLU_freeBins(plain, cipher, key, iv, NULL); blocks = 0; loop = 1; } i++; #endif #ifndef NO_MD5 /* md5 test */ if (option[i] == 1) { Md5 md5; digest = XMALLOC(MD5_DIGEST_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitMd5(&md5); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_Md5Update(&md5, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_Md5Final(&md5, digest); printf("MD5 "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, MD5_DIGEST_SIZE); wolfCLU_freeBins(digest, plain, NULL, NULL, NULL); blocks = 0; loop = 1; } i++; #endif #ifndef NO_SHA /* sha test */ if (option[i] == 1) { Sha sha; digest = XMALLOC(SHA_DIGEST_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitSha(&sha); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_ShaUpdate(&sha, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_ShaFinal(&sha, digest); printf("Sha "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, SHA_DIGEST_SIZE); wolfCLU_freeBins(plain, digest, NULL, NULL, NULL); blocks = 0; loop = 1; } i++; #endif #ifndef NO_SHA256 #define SHA256_SZ SHA256_DIGEST_SIZE /* sha256 test */ if (option[i] == 1) { Sha256 sha256; digest = XMALLOC(SHA256_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitSha256(&sha256); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_Sha256Update(&sha256, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_Sha256Final(&sha256, digest); printf("Sha256 "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, SHA256_DIGEST_SIZE); wolfCLU_freeBins(plain, digest, NULL, NULL, NULL); /* resets used for debug, uncomment if needed */ blocks = 0; loop = 1; } i++; #endif #ifdef WOLFSSL_SHA384 #define SHA384_SZ SHA384_DIGEST_SIZE /* sha384 test */ if (option[i] == 1) { Sha384 sha384; digest = XMALLOC(SHA384_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitSha384(&sha384); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_Sha384Update(&sha384, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_Sha384Final(&sha384, digest); printf("Sha384 "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, SHA384_DIGEST_SIZE); wolfCLU_freeBins(plain, digest, NULL, NULL, NULL); blocks = 0; loop = 1; } i++; #endif #ifdef WOLFSSL_SHA512 #define SHA512_SZ SHA512_DIGEST_SIZE /* sha512 test */ if (option[i] == 1) { Sha512 sha512; digest = XMALLOC(SHA512_SZ, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitSha512(&sha512); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_Sha512Update(&sha512, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_Sha512Final(&sha512, digest); printf("Sha512 "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, SHA512_DIGEST_SIZE); wolfCLU_freeBins(plain, digest, NULL, NULL, NULL); blocks = 0; loop = 1; } i++; #endif #ifdef HAVE_BLAKE2 /* blake2b test */ if (option[i] == 1) { Blake2b b2b; digest = XMALLOC(BLAKE_DIGEST_SIZE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (digest == NULL) return MEMORY_E; plain = XMALLOC(MEGABYTE, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (plain == NULL) { wolfCLU_freeBins(digest, NULL, NULL, NULL, NULL); return MEMORY_E; } wc_RNG_GenerateBlock(&rng, plain, MEGABYTE); wc_InitBlake2b(&b2b, BLAKE_DIGEST_SIZE); start = wolfCLU_getTime(); alarm(timer); while (loop) { wc_Blake2bUpdate(&b2b, plain, MEGABYTE); blocks++; currTime = wolfCLU_getTime(); stop = currTime - start; /* if stop >= timer, loop = 0 */ loop = (stop >= timer) ? 0 : 1; } wc_Blake2bFinal(&b2b, digest, BLAKE_DIGEST_SIZE); printf("Blake2b "); wolfCLU_stats(start, MEGABYTE, blocks); XMEMSET(plain, 0, MEGABYTE); XMEMSET(digest, 0, BLAKE_DIGEST_SIZE); wolfCLU_freeBins(digest, plain, NULL, NULL, NULL); } #endif return ret; }
static int signedData_sign_noattrs(byte* cert, word32 certSz, byte* key, word32 keySz, byte* out, word32 outSz, int devId) { int ret; PKCS7* pkcs7; WC_RNG rng; /* init rng */ ret = wc_InitRng(&rng); if (ret != 0) { printf("ERROR: wc_InitRng() failed, ret = %d\n", ret); return -1; } /* init PKCS7 */ pkcs7 = wc_PKCS7_New(NULL, devId); if (pkcs7 == NULL) { wc_FreeRng(&rng); return -1; } ret = wc_PKCS7_InitWithCert(pkcs7, cert, certSz); if (ret != 0) { printf("ERROR: wc_PKCS7_InitWithCert() failed, ret = %d\n", ret); wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return -1; } pkcs7->rng = &rng; pkcs7->content = (byte*)data; pkcs7->contentSz = sizeof(data); pkcs7->contentOID = DATA; pkcs7->hashOID = SHA256h; pkcs7->encryptOID = RSAk; pkcs7->privateKey = key; pkcs7->privateKeySz = keySz; pkcs7->signedAttribs = NULL; pkcs7->signedAttribsSz = 0; /* encode signedData, returns size */ ret = wc_PKCS7_EncodeSignedData(pkcs7, out, outSz); if (ret <= 0) { printf("ERROR: wc_PKCS7_EncodeSignedData() failed, ret = %d\n", ret); wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return -1; } else { printf("Successfully encoded SignedData bundle (%s)\n", encodedFileNoAttrs); #ifdef DEBUG_WOLFSSL printf("Encoded DER (%d bytes):\n", ret); WOLFSSL_BUFFER(out, ret); #endif if (write_file_buffer(encodedFileNoAttrs, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); return -1; } } wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return ret; }
static int signedData_sign_attrs(byte* cert, word32 certSz, byte* key, word32 keySz, byte* out, word32 outSz, int devId) { int ret; PKCS7* pkcs7; WC_RNG rng; static byte messageTypeOid[] = { 0x06, 0x0a, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x45, 0x01, 0x09, 0x02 }; static byte messageType[] = { 0x13, 2, '1', '9' }; PKCS7Attrib attribs[] = { { messageTypeOid, sizeof(messageTypeOid), messageType, sizeof(messageType) } }; /* init rng */ ret = wc_InitRng(&rng); if (ret != 0) { printf("ERROR: wc_InitRng() failed, ret = %d\n", ret); return -1; } /* init PKCS7 */ pkcs7 = wc_PKCS7_New(NULL, devId); if (pkcs7 == NULL) { wc_FreeRng(&rng); return -1; } ret = wc_PKCS7_InitWithCert(pkcs7, cert, certSz); if (ret != 0) { printf("ERROR: wc_PKCS7_InitWithCert() failed, ret = %d\n", ret); wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return -1; } pkcs7->rng = &rng; pkcs7->content = (byte*)data; pkcs7->contentSz = sizeof(data); pkcs7->contentOID = DATA; pkcs7->hashOID = SHA256h; pkcs7->encryptOID = RSAk; pkcs7->privateKey = key; pkcs7->privateKeySz = keySz; pkcs7->signedAttribs = attribs; pkcs7->signedAttribsSz = sizeof(attribs)/sizeof(PKCS7Attrib); /* encode signedData, returns size */ ret = wc_PKCS7_EncodeSignedData(pkcs7, out, outSz); if (ret <= 0) { printf("ERROR: wc_PKCS7_EncodeSignedData() failed, ret = %d\n", ret); wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return -1; } else { printf("Successfully encoded SignedData bundle (%s)\n", encodedFileAttrs); #ifdef DEBUG_WOLFSSL printf("Encoded DER (%d bytes):\n", ret); WOLFSSL_BUFFER(out, ret); #endif if (write_file_buffer(encodedFileAttrs, out, ret) != 0) { printf("ERROR: error writing encoded to output file\n"); return -1; } } wc_PKCS7_Free(pkcs7); wc_FreeRng(&rng); return ret; }
JNIEXPORT jint JNICALL Java_com_wolfssl_wolfcrypt_ECC_doSign (JNIEnv* jenv, jobject jcl, jobject in, jlong inSz, jobject out, jlongArray outSz, jobject keyDer, jlong keySz) { int ret; RNG rng; ecc_key myKey; unsigned int tmpOut; unsigned int idx = 0; /* check in and key sz */ if ((inSz < 0) || (keySz < 0)) { return -1; } /* get pointers to our buffers */ unsigned char* inBuf = (*jenv)->GetDirectBufferAddress(jenv, in); if (inBuf == NULL) { printf("problem getting in buffer address\n"); return -1; } unsigned char* outBuf = (*jenv)->GetDirectBufferAddress(jenv, out); if (outBuf == NULL) { printf("problem getting out buffer address\n"); return -1; } unsigned char* keyBuf = (*jenv)->GetDirectBufferAddress(jenv, keyDer); if (keyBuf == NULL) { printf("problem getting key buffer address\n"); return -1; } /* set previous value of outSz */ jlong tmp; (*jenv)->GetLongArrayRegion(jenv, outSz, 0, 1, &tmp); tmpOut = (unsigned int)tmp; wc_InitRng(&rng); wc_ecc_init(&myKey); ret = wc_EccPrivateKeyDecode(keyBuf, &idx, &myKey, keySz); if (ret == 0) { ret = wc_ecc_sign_hash(inBuf, (unsigned int)inSz, outBuf, &tmpOut, &rng, &myKey); if (ret != 0) { printf("wc_ecc_sign_hash failed, ret = %d\n", ret); wc_ecc_free(&myKey); return -1; } } else { printf("wc_EccPrivateKeyDecode failed, ret = %d\n", ret); return -1; } wc_ecc_free(&myKey); (*jenv)->SetLongArrayRegion(jenv, outSz, 0, 1, (jlong*)&tmpOut); return ret; }
int ClientBenchmarkThroughput(WOLFSSL_CTX* ctx, char* host, word16 port, int doDTLS, int throughput) { double start, conn_time = 0, tx_time = 0, rx_time = 0; SOCKET_T sockfd; WOLFSSL* ssl; int ret; start = current_time(); ssl = wolfSSL_new(ctx); if (ssl == NULL) err_sys("unable to get SSL object"); tcp_connect(&sockfd, host, port, doDTLS, ssl); wolfSSL_set_fd(ssl, sockfd); if (wolfSSL_connect(ssl) == SSL_SUCCESS) { /* Perform throughput test */ char *tx_buffer, *rx_buffer; /* Record connection time */ conn_time = current_time() - start; /* Allocate TX/RX buffers */ tx_buffer = (char*)malloc(TEST_BUFFER_SIZE); rx_buffer = (char*)malloc(TEST_BUFFER_SIZE); if(tx_buffer && rx_buffer) { WC_RNG rng; /* Startup the RNG */ ret = wc_InitRng(&rng); if(ret == 0) { int xfer_bytes; /* Generate random data to send */ ret = wc_RNG_GenerateBlock(&rng, (byte*)tx_buffer, TEST_BUFFER_SIZE); wc_FreeRng(&rng); if(ret != 0) { err_sys("wc_RNG_GenerateBlock failed"); } /* Perform TX and RX of bytes */ xfer_bytes = 0; while(throughput > xfer_bytes) { int len, rx_pos, select_ret; /* Determine packet size */ len = min(TEST_BUFFER_SIZE, throughput - xfer_bytes); /* Perform TX */ start = current_time(); if (wolfSSL_write(ssl, tx_buffer, len) != len) { int writeErr = wolfSSL_get_error(ssl, 0); printf("wolfSSL_write error %d!\n", writeErr); err_sys("wolfSSL_write failed"); } tx_time += current_time() - start; /* Perform RX */ select_ret = tcp_select(sockfd, 1); /* Timeout=1 second */ if (select_ret == TEST_RECV_READY) { start = current_time(); rx_pos = 0; while(rx_pos < len) { ret = wolfSSL_read(ssl, &rx_buffer[rx_pos], len - rx_pos); if(ret <= 0) { int readErr = wolfSSL_get_error(ssl, 0); if (readErr != SSL_ERROR_WANT_READ) { printf("wolfSSL_read error %d!\n", readErr); err_sys("wolfSSL_read failed"); } } else { rx_pos += ret; } } rx_time += current_time() - start; } /* Compare TX and RX buffers */ if(XMEMCMP(tx_buffer, rx_buffer, len) != 0) { err_sys("Compare TX and RX buffers failed"); } /* Update overall position */ xfer_bytes += len; } } else { err_sys("wc_InitRng failed"); } } else { err_sys("Client buffer malloc failed"); } if(tx_buffer) free(tx_buffer); if(rx_buffer) free(rx_buffer); } else { err_sys("wolfSSL_connect failed"); } wolfSSL_shutdown(ssl); wolfSSL_free(ssl); CloseSocket(sockfd); printf("wolfSSL Client Benchmark %d bytes\n" "\tConnect %8.3f ms\n" "\tTX %8.3f ms (%8.3f MBps)\n" "\tRX %8.3f ms (%8.3f MBps)\n", throughput, conn_time * 1000, tx_time * 1000, throughput / tx_time / 1024 / 1024, rx_time * 1000, throughput / rx_time / 1024 / 1024 ); return EXIT_SUCCESS; }
int rsa_test(void) { byte* tmp = NULL; size_t bytes; RsaKey key; WC_RNG rng; word32 idx = 0; int ret; byte in[] = "Everyone gets Friday off."; word32 inLen = (word32)XSTRLEN((char*)in); byte out[256]; byte plain[256]; byte* outPtr = NULL; tmp = (byte*)XMALLOC(FOURK_BUF, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { ret = MEMORY_E; goto exit; } XMEMCPY(tmp, privkey_der_2048, sizeof(privkey_der_2048)); bytes = sizeof(privkey_der_2048); ret = wc_InitRsaKey_ex(&key, HEAP_HINT, INVALID_DEVID); if (ret < 0) { goto exit; } ret = wc_RsaPrivateKeyDecode(tmp, &idx, &key, (word32)bytes); if (ret < 0) { goto exit; } printf("Key Size: %d\n", wc_RsaEncryptSize(&key)); ret = wc_InitRng(&rng); if (ret < 0) { goto exit; } #ifdef WC_RSA_BLINDING ret = wc_RsaSetRNG(&key, &rng); if (ret < 0) { goto exit; } #endif ret = wc_RsaPublicEncrypt(in, inLen, out, sizeof(out), &key, &rng); printf("wc_RsaPublicEncrypt: %d\n", ret); if (ret < 0) { goto exit; } idx = ret; /* save off encrypted length */ ret = wc_RsaPrivateDecrypt(out, idx, plain, sizeof(plain), &key); printf("wc_RsaPrivateDecrypt: %d\n", ret); printf("\n%d", ret); if (ret < 0) { goto exit; } if (XMEMCMP(plain, in, ret)) { printf("Compare failed!\n"); goto exit; } ret = wc_RsaSSL_Sign(in, inLen, out, sizeof(out), &key, &rng); printf("wc_RsaSSL_Sign: %d\n", ret); if (ret < 0) { goto exit; } idx = ret; XMEMSET(plain, 0, sizeof(plain)); ret = wc_RsaSSL_VerifyInline(out, idx, &outPtr, &key); printf("wc_RsaSSL_Verify: %d\n", ret); if (ret < 0) { goto exit; } if (XMEMCMP(in, outPtr, ret)) { printf("Compare failed!\n"); goto exit; } ret = 0; /* success */ exit: wc_FreeRsaKey(&key); XFREE(tmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); wc_FreeRng(&rng); return ret; }
int wolfsslEncrypt(char* alg, char* mode, byte* pwdKey, byte* key, int size, char* in, char* out, byte* iv, int block, int ivCheck, int inputHex) { #ifndef NO_AES Aes aes; /* aes declaration */ #endif #ifndef NO_DES3 Des3 des3; /* 3des declaration */ #endif #ifdef HAVE_CAMELLIA Camellia camellia; /* camellia declaration */ #endif FILE* tempInFile = NULL; /* if user not provide a file */ FILE* inFile = NULL; /* input file */ FILE* outFile = NULL; /* output file */ RNG rng; /* random number generator declaration */ byte* input = NULL; /* input buffer */ byte* output = NULL; /* output buffer */ byte salt[SALT_SIZE] = {0}; /* salt variable */ int ret = 0; /* return variable */ int inputLength = 0; /* length of input */ int length = 0; /* total length */ int padCounter = 0; /* number of padded bytes */ int i = 0; /* loop variable */ int hexRet = 0; /* hex -> bin return*/ word32 tempInputL = 0; /* temporary input Length */ word32 tempMax = MAX; /* controls encryption amount */ char inputString[MAX]; /* the input string */ char* userInputBuffer = NULL; /* buffer when input is not a file */ if (access (in, F_OK) == -1) { printf("file did not exist, encrypting string following \"-i\"" "instead.\n"); /* use user entered data to encrypt */ inputLength = (int) strlen(in); userInputBuffer = (char*) malloc(inputLength); /* writes the entered text to the input buffer */ XMEMCPY(userInputBuffer, in, inputLength); /* open the file to write */ tempInFile = fopen(in, "wb"); fwrite(userInputBuffer, 1, inputLength, tempInFile); fclose(tempInFile); /* free buffer */ free(userInputBuffer); } /* open the inFile in read mode */ inFile = fopen(in, "rb"); /* find length */ fseek(inFile, 0, SEEK_END); inputLength = (int) ftell(inFile); fseek(inFile, 0, SEEK_SET); length = inputLength; /* Start up the random number generator */ ret = (int) wc_InitRng(&rng); if (ret != 0) { printf("Random Number Generator failed to start.\n"); return ret; } /* pads the length until it matches a block, * and increases pad number */ while (length % block != 0) { length++; padCounter++; } /* if the iv was not explicitly set, * generate an iv and use the pwdKey */ if (ivCheck == 0) { /* IV not set, generate it */ ret = wc_RNG_GenerateBlock(&rng, iv, block); if (ret != 0) { return ret; } /* stretches pwdKey to fit size based on wolfsslGetAlgo() */ ret = wolfsslGenKey(&rng, pwdKey, size, salt, padCounter); if (ret != 0) { printf("failed to set pwdKey.\n"); return ret; } /* move the generated pwdKey to "key" for encrypting */ for (i = 0; i < size; i++) { key[i] = pwdKey[i]; } } /* open the outFile in write mode */ outFile = fopen(out, "wb"); fwrite(salt, 1, SALT_SIZE, outFile); fwrite(iv, 1, block, outFile); fclose(outFile); /* malloc 1kB buffers */ input = (byte*) malloc(MAX); output = (byte*) malloc(MAX); /* loop, encrypt 1kB at a time till length <= 0 */ while (length > 0) { /* Read in 1kB to input[] */ if (inputHex == 1) ret = (int) fread(inputString, 1, MAX, inFile); else ret = (int) fread(input, 1, MAX, inFile); if (ret != MAX) { /* check for end of file */ if (feof(inFile)) { /* hex or ascii */ if (inputHex == 1) { hexRet = wolfsslHexToBin(inputString, &input, &tempInputL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (hexRet != 0) { printf("failed during conversion of input," " ret = %d\n", hexRet); return hexRet; } }/* end hex or ascii */ /* pad to end of block */ for (i = ret ; i < (ret + padCounter); i++) { input[i] = padCounter; } /* adjust tempMax for less than 1kB encryption */ tempMax = ret + padCounter; } else { /* otherwise we got a file read error */ wolfsslFreeBins(input, output, NULL, NULL, NULL); return FREAD_ERROR; }/* End feof check */ }/* End fread check */ /* sets key encrypts the message to ouput from input */ #ifndef NO_AES if (XSTRNCMP(alg, "aes", 3) == 0) { if (XSTRNCMP(mode, "cbc", 3) == 0) { ret = wc_AesSetKey(&aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION); if (ret != 0) { printf("wc_AesSetKey failed.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return ret; } ret = wc_AesCbcEncrypt(&aes, output, input, tempMax); if (ret != 0) { printf("wc_AesCbcEncrypt failed.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return ENCRYPT_ERROR; } } #ifdef WOLFSSL_AES_COUNTER else if (XSTRNCMP(mode, "ctr", 3) == 0) { /* if mode is ctr */ wc_AesSetKeyDirect(&aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION); wc_AesCtrEncrypt(&aes, output, input, tempMax); } #endif } #endif #ifndef NO_DES3 if (XSTRNCMP(alg, "3des", 4) == 0) { ret = wc_Des3_SetKey(&des3, key, iv, DES_ENCRYPTION); if (ret != 0) { printf("wc_Des3_SetKey failed.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return ret; } ret = wc_Des3_CbcEncrypt(&des3, output, input, tempMax); if (ret != 0) { printf("wc_Des3_cbcEncrypt failed.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return ENCRYPT_ERROR; } } #endif #ifdef HAVE_CAMELLIA if (XSTRNCMP(alg, "camellia", 8) == 0) { ret = wc_CamelliaSetKey(&camellia, key, block, iv); if (ret != 0) { printf("CamelliaSetKey failed.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return ret; } if (XSTRNCMP(mode, "cbc", 3) == 0) { wc_CamelliaCbcEncrypt(&camellia, output, input, tempMax); } else { printf("Incompatible mode while using Camellia.\n"); wolfsslFreeBins(input, output, NULL, NULL, NULL); return FATAL_ERROR; } } #endif /* HAVE_CAMELLIA */ /* this method added for visual confirmation of nist test vectors, * automated tests to come soon */ /* something in the output buffer and using hex */ if (output != NULL && inputHex == 1) { int tempi; printf("\nUser specified hex input this is a representation of " "what\nis being written to file in hex form.\n\n[ "); for (tempi = 0; tempi < block; tempi++ ) { printf("%02x", output[tempi]); } printf(" ]\n\n"); } /* end visual confirmation */ /* Open the outFile in append mode */ outFile = fopen(out, "ab"); ret = (int) fwrite(output, 1, tempMax, outFile); if (ferror(outFile)) { printf("failed to write to file.\n"); if (input != NULL) XMEMSET(input, 0, tempMax); if (output != NULL) XMEMSET(output, 0, tempMax); wolfsslFreeBins(input, output, NULL, NULL, NULL); return FWRITE_ERROR; } if (ret > MAX) { printf("Wrote too much to file.\n"); if (input != NULL) XMEMSET(input, 0, tempMax); if (output != NULL) XMEMSET(output, 0, tempMax); wolfsslFreeBins(input, output, NULL, NULL, NULL); return FWRITE_ERROR; } /* close the outFile */ fclose(outFile); length -= tempMax; if (length < 0) printf("length went past zero.\n"); if (input != NULL) XMEMSET(input, 0, tempMax); if (output != NULL) XMEMSET(output, 0, tempMax); } /* closes the opened files and frees the memory */ fclose(inFile); XMEMSET(key, 0, size); XMEMSET(iv, 0 , block); XMEMSET(alg, 0, size); XMEMSET(mode, 0 , block); /* Use the wolfssl free for rng */ wc_FreeRng(&rng); wolfsslFreeBins(input, output, NULL, NULL, NULL); return 0; }
/* * Encrypts a file using AES */ int AesEncrypt(Aes* aes, byte* key, int size, FILE* inFile, FILE* outFile) { RNG rng; byte iv[AES_BLOCK_SIZE]; byte* input; byte* output; byte salt[SALT_SIZE] = {0}; int i = 0; int ret = 0; int inputLength; int length; int padCounter = 0; fseek(inFile, 0, SEEK_END); inputLength = ftell(inFile); fseek(inFile, 0, SEEK_SET); length = inputLength; /* pads the length until it evenly matches a block / increases pad number*/ while (length % AES_BLOCK_SIZE != 0) { length++; padCounter++; } input = malloc(length); output = malloc(length); ret = wc_InitRng(&rng); if (ret != 0) { printf("Failed to initialize random number generator\n"); return -1030; } /* reads from inFile and writes whatever is there to the input array */ ret = fread(input, 1, inputLength, inFile); if (ret == 0) { printf("Input file does not exist.\n"); return -1010; } for (i = inputLength; i < length; i++) { /* pads the added characters with the number of pads */ input[i] = padCounter; } ret = wc_RNG_GenerateBlock(&rng, iv, AES_BLOCK_SIZE); if (ret != 0) return -1020; /* stretches key to fit size */ ret = GenerateKey(&rng, key, size, salt, padCounter); if (ret != 0) return -1040; /* sets key */ ret = wc_AesSetKey(aes, key, AES_BLOCK_SIZE, iv, AES_ENCRYPTION); if (ret != 0) return -1001; /* encrypts the message to the output based on input length + padding */ ret = wc_AesCbcEncrypt(aes, output, input, length); if (ret != 0) return -1005; /* writes to outFile */ fwrite(salt, 1, SALT_SIZE, outFile); fwrite(iv, 1, AES_BLOCK_SIZE, outFile); fwrite(output, 1, length, outFile); /* closes the opened files and frees the memory*/ memset(input, 0, length); memset(output, 0, length); memset(key, 0, size); free(input); free(output); free(key); fclose(inFile); fclose(outFile); wc_FreeRng(&rng); return ret; }
int ecc_sign_verify_test(enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* fileBuf, int fileLen, byte* verifyFileBuf, int* verifyFileLen, int* pmaxSigSz, int* pmaxCurveSigSz, int curveId, int keySz) { int ret; ecc_key eccKey; RNG rng; byte* sigBuf = NULL; word32 sigLen; byte eccPubKeyBuf[ECC_BUFSIZE], eccPrivKeyBuf[ECC_BUFSIZE]; word32 eccPubKeyLen, eccPrivKeyLen; word32 maxCurveSigSz; #ifdef DEBUG_SIG_TEST printf("ECC Signature: Curve %s, Size %d\n", wc_ecc_get_name(curveId), keySz); #endif /* Init */ wc_InitRng(&rng); /* Generate key */ wc_ecc_init(&eccKey); ret = wc_ecc_make_key_ex(&rng, keySz, &eccKey, curveId); if(ret != 0) { printf("ECC Make Key Failed! %d\n", ret); goto exit; } ret = wc_ecc_sig_size(&eccKey); if (ret < 0) { printf("ECC Sig SizeFailed! %d\n", ret); goto exit; } maxCurveSigSz = ret; /* Display public key data */ eccPubKeyLen = ECC_BUFSIZE; ret = wc_ecc_export_x963(&eccKey, eccPubKeyBuf, &eccPubKeyLen); if (ret != 0) { printf("ECC public key x963 export failed! %d\n", ret); ret = EXIT_FAILURE; goto exit; } #ifdef DEBUG_SIG_TEST printf("ECC Public Key: Len %d\n", eccPubKeyLen); hexdump(eccPubKeyBuf, eccPubKeyLen, 16); #endif /* Display private key data */ eccPrivKeyLen = ECC_BUFSIZE; ret = wc_ecc_export_private_only(&eccKey, eccPrivKeyBuf, &eccPrivKeyLen); if (ret != 0) { printf("ECC private key export failed! %d\n", ret); ret = EXIT_FAILURE; goto exit; } #ifdef DEBUG_SIG_TEST printf("ECC Private Key: Len %d\n", eccPrivKeyLen); hexdump(eccPrivKeyBuf, eccPrivKeyLen, 16); #endif if (verifyFileBuf) { sigLen = *verifyFileLen; sigBuf = verifyFileBuf; } else { /* Get signature length and allocate buffer */ sigLen = wc_SignatureGetSize(sig_type, &eccKey, sizeof(eccKey)); if(sigLen <= 0) { printf("ECC Signature type %d not supported!\n", sig_type); ret = EXIT_FAILURE; goto exit; } sigBuf = malloc(sigLen); if(!sigBuf) { printf("ECC Signature malloc failed!\n"); ret = EXIT_FAILURE; goto exit; } #ifdef DEBUG_SIG_TEST printf("ECC Signature Len: %d\n", sigLen); #endif /* Perform hash and sign to create signature */ ret = wc_SignatureGenerate( hash_type, sig_type, fileBuf, fileLen, sigBuf, &sigLen, &eccKey, sizeof(eccKey), &rng); *verifyFileLen = sigLen; #ifdef DEBUG_SIG_TEST printf("ECC Signature Generation: %s (%d)\n", (ret == 0) ? "Pass" : "Fail", ret); #endif if(ret < 0) { ret = EXIT_FAILURE; goto exit; } } #ifdef DEBUG_SIG_TEST printf("Signature Data:\n"); hexdump(sigBuf, sigLen, 16); #endif /* Perform signature verification */ /* Release and init new key */ wc_ecc_free(&eccKey); wc_ecc_init(&eccKey); /* Import the public key */ ret = wc_ecc_import_x963_ex(eccPubKeyBuf, eccPubKeyLen, &eccKey, curveId); if (ret != 0) { printf("ECC public key import failed! %d\n", ret); ret = EXIT_FAILURE; goto exit; } /* Perform signature verification using public key */ ret = wc_SignatureVerify( hash_type, sig_type, fileBuf, fileLen, sigBuf, sigLen, &eccKey, sizeof(eccKey)); #ifdef DEBUG_SIG_TEST printf("ECC Signature Verification: %s (%d)\n", (ret == 0) ? "Pass" : "Fail", ret); #endif if (ret < 0) { ret = EXIT_FAILURE; } if (pmaxSigSz && *pmaxSigSz < sigLen) { #ifdef DEBUG_SIG_TEST_MAX printf("Curve: Max %d->%d\n", *pmaxSigSz, sigLen); hexdump(sigBuf, sigLen, 16); #endif *pmaxSigSz = sigLen; } if (pmaxCurveSigSz && *pmaxCurveSigSz < maxCurveSigSz) { *pmaxCurveSigSz = maxCurveSigSz; } exit: /* Free */ if(sigBuf) { free(sigBuf); } wc_ecc_free(&eccKey); wc_FreeRng(&rng); return ret; }
// Temporary fix till crypto library is upgraded to recent wolfssl versions. int InitRng(RNG* rng) { return wc_InitRng(rng); }
int main() { ecc_key key; byte der[4096]; byte buf[4096]; word32 idx = 0; FILE* derFile; size_t sz; RNG rng; wc_InitRng(&rng); wc_ecc_init(&key); if (wc_ecc_make_key(&rng, 32, &key) != 0) { printf("error making ecc key\n"); return -1; } /* write private key */ if (wc_EccKeyToDer(&key, der, sizeof(der)) < 0) { printf("error in ecc to der\n"); return -1; } printf("writing private key to ecc-key.der\n"); derFile = fopen("ecc-key.der", "w"); if (!derFile) { printf("error loading file\n"); return -1; } sz = fwrite(der, 1, 4096, derFile); fclose(derFile); wc_ecc_free(&key); /* open and read from der file */ printf("reading in private key\n"); derFile = fopen("ecc-key.der", "rb"); if (!derFile) { printf("error reading from file\n"); return -1; } sz = fread(buf, 1, 4096, derFile); fclose(derFile); /* load private ecc key */ printf("storing private key in ecc struct\n"); wc_ecc_init(&key); if (wc_EccPrivateKeyDecode(buf, &idx, &key, (word32)sz) != 0) { printf("error decoding private key\n"); return -1; } wc_ecc_free(&key); /* Or the der file can be loaded into a TLS connection using something like int wc_DerToPem(der, sizeof(der), pemOut, sizeof(pemOut), ECC_PRIVATEKEY_TYPE); int wolfSSL_use_PrivateKey_file(&ssl, pemOut, SSL_FILETYPE_PEM); */ /* to store a public key */ wc_ecc_init(&key); if (wc_ecc_make_key(&rng, 32, &key) != 0) { printf("error making ecc key\n"); return -1; } printf("storing public key into ecc-public.x963\n"); memset(buf, 0, sizeof(buf)); idx = sizeof(buf); if (wc_ecc_export_x963(&key, buf, &idx) != 0) { printf("error exporting public ecc key\n"); return -1; } derFile = fopen("ecc-public.x963", "w"); /* reused the derFile pointer */ if (!derFile) { printf("error loading file\n"); return -1; } sz = fwrite(buf, 1, idx, derFile); /* close stuff up */ fclose(derFile); wc_ecc_free(&key); wc_FreeRng(&rng); return 0; }
int main(int argc, char** argv) { int ret; WC_RNG rng; ecEncCtx* srvCtx = NULL; void* devCtx = NULL; const byte* mySalt; byte peerSalt[EXCHANGE_SALT_SZ]; byte buffer[BTLE_MSG_MAX_SIZE]; word32 bufferSz; byte plain[BTLE_MSG_MAX_SIZE]; word32 plainSz; ecc_key myKey, peerKey; int type; wolfSSL_Init(); #ifdef DEBUG_WOLFSSL wolfSSL_Debugging_ON(); #endif /* make my session key */ ret = wc_ecc_init(&myKey); ret |= wc_ecc_init(&peerKey); if (ret != 0) { printf("wc_ecc_init failed!\n"); goto cleanup; } /* open BTLE */ ret = btle_open(&devCtx, BTLE_ROLE_SERVER); if (ret != 0) { printf("btle_open failed %d! errno %d\n", ret, errno); goto cleanup; } ret = wc_InitRng(&rng); if (ret != 0) { printf("wc_InitRng failed! %d\n", ret); goto cleanup; } ret = wc_ecc_make_key(&rng, 32, &myKey); if (ret != 0) { printf("wc_ecc_make_key failed %d\n", ret); goto cleanup; } srvCtx = wc_ecc_ctx_new(REQ_RESP_SERVER, &rng); if (srvCtx == NULL) { printf("wc_ecc_ctx_new failed!\n"); ret = -1; goto cleanup; } /* exchange public keys */ /* Get peer key */ ret = btle_recv(buffer, sizeof(buffer), &type, devCtx); if (ret < 0) { printf("btle_recv key failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_KEY) { printf("btle_recv expected key!\n"); ret = -1; goto cleanup; } bufferSz = ret; ret = wc_ecc_import_x963(buffer, bufferSz, &peerKey); if (ret != 0) { printf("wc_ecc_import_x963 failed %d!\n", ret); goto cleanup; } /* send my public key */ /* export my public key */ bufferSz = sizeof(buffer); ret = wc_ecc_export_x963(&myKey, buffer, &bufferSz); if (ret != 0) { printf("wc_ecc_export_x963 failed %d\n", ret); goto cleanup; } /* TODO: Server should hash and sign this public key with a trust ceritifcate (already exchanged) */ /* ECC signature is about 65 bytes */ ret = btle_send(buffer, bufferSz, BTLE_PKT_TYPE_KEY, devCtx); if (ret != bufferSz) { printf("btle_send key failed %d!\n", ret); goto cleanup; } while (1) { mySalt = wc_ecc_ctx_get_own_salt(srvCtx); if (mySalt == NULL) { printf("wc_ecc_ctx_get_own_salt failed!\n"); ret = -1; goto cleanup; } /* Get peer salt */ ret = btle_recv(peerSalt, EXCHANGE_SALT_SZ, &type, devCtx); if (ret <= 0) { printf("btle_recv salt failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_SALT) { printf("btle_recv expected salt!\n"); ret = -1; goto cleanup; } /* Send my salt */ /* You must send mySalt before set_peer_salt, because buffer changes */ ret = btle_send(mySalt, EXCHANGE_SALT_SZ, BTLE_PKT_TYPE_SALT, devCtx); if (ret != EXCHANGE_SALT_SZ) { printf("btle_send salt failed %d!\n", ret); goto cleanup; } ret = wc_ecc_ctx_set_peer_salt(srvCtx, peerSalt); if (ret != 0) { printf("wc_ecc_ctx_set_peer_salt failed %d\n", ret); goto cleanup; } /* Get message */ bufferSz = sizeof(buffer); ret = btle_recv(buffer, bufferSz, &type, devCtx); if (ret <= 0) { printf("btle_recv msg failed %d! errno %d\n", ret, errno); goto cleanup; } if (type != BTLE_PKT_TYPE_MSG) { printf("btle_recv expected msg!\n"); ret = -1; goto cleanup; } /* Decrypt message */ bufferSz = ret; plainSz = sizeof(plain); ret = wc_ecc_decrypt(&myKey, &peerKey, buffer, bufferSz, plain, &plainSz, srvCtx); if (ret != 0) { printf("wc_ecc_decrypt failed %d!\n", ret); goto cleanup; } printf("Recv %d: %s\n", plainSz, plain); /* Encrypt message */ bufferSz = sizeof(buffer); ret = wc_ecc_encrypt(&myKey, &peerKey, plain, plainSz, buffer, &bufferSz, srvCtx); if (ret != 0) { printf("wc_ecc_encrypt failed %d!\n", ret); goto cleanup; } /* Send message */ ret = btle_send(buffer, bufferSz, BTLE_PKT_TYPE_MSG, devCtx); if (ret != bufferSz) { printf("btle_send failed %d!\n", ret); goto cleanup; } /* check for exit flag */ if (strstr((char*)plain, "EXIT")) break; /* reset context (reset my salt) */ ret = wc_ecc_ctx_reset(srvCtx, &rng); if (ret != 0) { printf("wc_ecc_ctx_reset failed %d\n", ret); goto cleanup; } } cleanup: if (devCtx != NULL) btle_close(devCtx); wolfSSL_Cleanup(); return ret; }