Пример #1
2
int rsa_test()
{
    byte   tmp[1024], tmp2[2048];
    size_t bytes, bytes2;
    RsaKey key;
    RNG    rng;
    word32 idx = 0;
    int    ret;
    byte   in[] = "Everyone gets Friday off.";
    word32 inLen = (word32)strlen((char*)in);
    byte   out[64];
    byte   plain[64];
    DecodedCert cert;

    FILE*  file = fopen(clientKey, "rb"), * file2;

    if (!file)
        return -40;

    bytes = fread(tmp, 1, 1024, file);
  
    InitRsaKey(&key, 0);  
    ret = RsaPrivateKeyDecode(tmp, &idx, &key, (word32)bytes);
    if (ret != 0) return -41;

    ret = InitRng(&rng);
    if (ret != 0) return -42;

    ret = RsaPublicEncrypt(in, inLen, out, sizeof(out), &key, &rng);  

    ret = RsaPrivateDecrypt(out, 64, plain, sizeof(plain), &key);

    if (memcmp(plain, in, inLen)) return -45;

    ret = RsaSSL_Sign(in, inLen, out, sizeof(out), &key, &rng);
    memset(plain, 0, sizeof(plain));
    ret = RsaSSL_Verify(out, 64, plain, sizeof(plain), &key);

    if (memcmp(plain, in, ret)) return -46;

    file2 = fopen(clientCert, "rb");
    if (!file2)
        return -47;

    bytes2 = fread(tmp2, 1, 2048, file2);

    InitDecodedCert(&cert, (byte*)&tmp2, 0);

    ret = ParseCert(&cert, (word32)bytes2, CERT_TYPE, NO_VERIFY, 0);
    if (ret != 0) return -48;

    FreeDecodedCert(&cert);
    FreeRsaKey(&key);

    fclose(file2);
    fclose(file);

    return 0;
}
Пример #2
0
void bench_ecc25519KeyGen(void)
{
    ecc25519_key genKey;
    double start, total, each, milliEach;
    int    i, ret;

    ret = InitRng(&rng);
    if (ret < 0) {
        printf("InitRNG failed\n");
        return;
    }
    /* 256 bit */
    start = current_time(1);

    for(i = 0; i < genTimes; i++) {
        ecc25519_make_key(&rng, 32, &genKey);
        ecc25519_free(&genKey);
    }

    total = current_time(0) - start;
    each  = total / genTimes;  /* per second  */
    milliEach = each * 1000;   /* millisconds */
    printf("\n");
    printf("ECC25519 256 key generation %6.3f milliseconds, avg over %d"
           " iterations\n", milliEach, genTimes);
}
Пример #3
0
int dh_test()
{
    int    ret;
    word32 bytes;
    word32 idx = 0, privSz, pubSz, privSz2, pubSz2, agreeSz, agreeSz2;
    byte   tmp[1024];
    byte   priv[128];
    byte   pub[128];
    byte   priv2[128];
    byte   pub2[128];
    byte   agree[128];
    byte   agree2[128];
    DhKey  key;
    DhKey  key2;
    RNG    rng;
    FILE*  file = fopen(dhKey, "rb");

    if (!file)
        return -50;

    bytes = (word32) fread(tmp, 1, 1024, file);

    InitDhKey(&key);  
    InitDhKey(&key2);  
    ret = DhKeyDecode(tmp, &idx, &key, bytes);
    if (ret != 0)
        return -51;

    idx = 0;
    ret = DhKeyDecode(tmp, &idx, &key2, bytes);
    if (ret != 0)
        return -52;

    ret = InitRng(&rng);
    if (ret != 0)
        return -53;
    
    ret = DhGenerateKeyPair(&key, &rng, priv, &privSz, pub, &pubSz);
    ret = DhGenerateKeyPair(&key2, &rng, priv2, &privSz2, pub2, &pubSz2);
    if (ret != 0)
        return -54;

    ret = DhAgree(&key, agree, &agreeSz, priv, privSz, pub2, pubSz2);
    ret = DhAgree(&key2, agree2, &agreeSz2, priv2, privSz2, pub, pubSz);
    if (ret != 0)
        return -55;

    if (memcmp(agree, agree2, agreeSz))
        return -56;

    FreeDhKey(&key);
    FreeDhKey(&key2);
    fclose(file);

    return 0;
}
Пример #4
0
/* RNG Initialize, < 0 on error */
int CRYPT_RNG_Initialize(CRYPT_RNG_CTX* rng)
{
    typedef char rng_test[sizeof(CRYPT_RNG_CTX) >= sizeof(WC_RNG) ? 1 : -1];
    (void)sizeof(rng_test);

    if (rng == NULL)
        return BAD_FUNC_ARG;

    return InitRng((WC_RNG*)rng);
}
Пример #5
0
void bench_rsa(void)
{
    int    i;
    byte   tmp[3072];
    size_t bytes;
    word32 idx = 0;

    byte      message[] = "Everyone gets Friday off.";
    byte      enc[512];  /* for up to 4096 bit */
    byte*     output;
    const int len = (int)strlen((char*)message);
    double    start, total, each, milliEach;

    RsaKey rsaKey;
    FILE*  file = fopen("./certs/rsa2048.der", "rb");

    if (!file) {
        printf("can't find ./certs/rsa2048.der, "
               "Please run from CyaSSL home dir\n");
        return;
    }

    InitRng(&rng);
    bytes = fread(tmp, 1, sizeof(tmp), file);
    InitRsaKey(&rsaKey, 0);
    bytes = RsaPrivateKeyDecode(tmp, &idx, &rsaKey, (word32)bytes);

    start = current_time();

    for (i = 0; i < times; i++)
        bytes = RsaPublicEncrypt(message,len,enc,sizeof(enc), &rsaKey, &rng);

    total = current_time() - start;
    each  = total / times;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("RSA 2048 encryption took %6.2f milliseconds, avg over %d"
           " iterations\n", milliEach, times);

    start = current_time();

    for (i = 0; i < times; i++)
        RsaPrivateDecryptInline(enc, (word32)bytes, &output, &rsaKey);

    total = current_time() - start;
    each  = total / times;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("RSA 2048 decryption took %6.2f milliseconds, avg over %d"
           " iterations\n", milliEach, times);

    fclose(file);
    FreeRsaKey(&rsaKey);
}
Пример #6
0
int random_test()
{
    RNG  rng;
    byte block[32];
    int ret = InitRng(&rng);
    if (ret != 0) return -39;

    RNG_GenerateBlock(&rng, block, sizeof(block));

    return 0;
}
Пример #7
0
int Curl_cyassl_random(struct SessionHandle *data,
                       unsigned char *entropy,
                       size_t length)
{
  RNG rng;
  (void)data;
  if(InitRng(&rng))
    return 1;
  if(RNG_GenerateBlock(&rng, entropy, length))
    return 1;
  return 0;
}
Пример #8
0
static CURLcode Curl_cyassl_random(struct Curl_easy *data,
                                   unsigned char *entropy, size_t length)
{
  RNG rng;
  (void)data;
  if(InitRng(&rng))
    return CURLE_FAILED_INIT;
  if(length > UINT_MAX)
    return CURLE_FAILED_INIT;
  if(RNG_GenerateBlock(&rng, entropy, (unsigned)length))
    return CURLE_FAILED_INIT;
  return CURLE_OK;
}
Пример #9
0
void bench_ecc25519KeyAgree(void)
{
    ecc25519_key genKey, genKey2;
    double start, total, each, milliEach;
    int    i, ret;
    byte   shared[1024];
    word32 x = 0;

    ecc25519_init(&genKey);
    ecc25519_init(&genKey2);

    ret = InitRng(&rng);
    if (ret < 0) {
        printf("InitRNG failed\n");
        return;
    }

    ret = ecc25519_make_key(&rng, 32, &genKey);
    if (ret != 0) {
        printf("ecc25519_make_key failed\n");
        return;
    }
    ret = ecc25519_make_key(&rng, 32, &genKey2);
    if (ret != 0) {
        printf("ecc25519_make_key failed\n");
        return;
    }

    /* 256 bit */
    start = current_time(1);

    for(i = 0; i < agreeTimes; i++) {
        x = sizeof(shared);
        ret = ecc25519_shared_secret(&genKey, &genKey2, shared, &x);
        if (ret != 0) {
            printf("ecc25519_shared_secret failed\n");
            return;
        }
    }

    total = current_time(0) - start;
    each  = total / agreeTimes;  /* per second  */
    milliEach = each * 1000;   /* millisconds */
    printf("ECC25519-DHE key agreement  %6.3f milliseconds, avg over %d"
           " iterations\n", milliEach, agreeTimes);

    ecc25519_free(&genKey2);
    ecc25519_free(&genKey);
}
Пример #10
0
static RNG *
get_rng (void)
{
  static RNG rng;
  static bool rng_initialized = false;

  if (!rng_initialized)
    {
      if (!check_result (InitRng (&rng)))
        return NULL;
      rng_initialized = true;
    }

  return &rng;
}
Пример #11
0
/* 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 = 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;
}
Пример #12
0
byte GetEntropy(ENTROPY_CMD cmd, byte* out)
{
    if (cmd == INIT)
        return (InitRng(&rng) == 0) ? 1 : 0;

    if (out == NULL)
        return 0;

    if (cmd == GET_BYTE_OF_ENTROPY)
        return (RNG_GenerateBlock(&rng, out, 1) == 0) ? 1 : 0;

    if (cmd == GET_NUM_BYTES_PER_BYTE_OF_ENTROPY) {
        *out = 1;
        return 1;
    }

    return 0;
}
Пример #13
0
int dsa_test()
{
    int    ret, answer;
    word32 bytes;
    word32 idx = 0;
    byte   tmp[1024];
    DsaKey key;
    RNG    rng;
    FILE*  file = fopen(dsaKey, "rb");
    Sha    sha;
    byte   hash[SHA_DIGEST_SIZE];
    byte   signature[40];

    if (!file)
        return -60;

    bytes = (word32) fread(tmp, 1, sizeof(tmp), file);
  
    InitSha(&sha);
    ShaUpdate(&sha, tmp, bytes);
    ShaFinal(&sha, hash);

    InitDsaKey(&key);
    ret = DsaPrivateKeyDecode(tmp, &idx, &key, bytes);
    if (ret != 0) return -61;

    ret = InitRng(&rng);
    if (ret != 0) return -62;

    ret = DsaSign(hash, signature, &key, &rng);
    if (ret != 0) return -63;

    ret = DsaVerify(hash, signature, &key, &answer);
    if (ret != 0) return -64;
    if (answer != 1) return -65;
    
    FreeDsaKey(&key);
    fclose(file);
    
    return 0;
}
Пример #14
0
/*
 * Decrypts a file using Camellia 
 */
int CamelliaDecrypt(Camellia* cam, byte* key, int size, FILE* inFile, 
    FILE* outFile)
{
    RNG     rng;
    byte    iv[CAMELLIA_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);

    InitRng(&rng);

    /* reads from inFile and wrties 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 < CAMELLIA_BLOCK_SIZE + SALT_SIZE; i++) {
        /* finds iv from input message */
        iv[i - SALT_SIZE] = input[i];
    }

    /* replicates old key if keys match */
    ret = PBKDF2(key, key, strlen((const char*)key), salt, SALT_SIZE, 4096, 
        size, SHA256);
    if (ret != 0)
        return -1050;

    /* sets key */
    ret = CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv);
    if (ret != 0)
        return -1002;

    /* change length to remove salt/iv block from being decrypted */
    length -= (CAMELLIA_BLOCK_SIZE + SALT_SIZE);
    for (i = 0; i < length; i++) {
        /* shifts message: ignores salt/iv on message*/
        input[i] = input[i + (CAMELLIA_BLOCK_SIZE + SALT_SIZE)];
    }
    /* decrypts the message to output based on input length + padding */
    CamelliaCbcDecrypt(cam, output, input, length);

    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);

    return 0;
}
Пример #15
0
void bench_rsa(void)
{
    int    i;
    int    ret;
    byte   tmp[3072];
    size_t bytes;
    word32 idx = 0;

    byte      message[] = "Everyone gets Friday off.";
    byte      enc[512];  /* for up to 4096 bit */
    const int len = (int)strlen((char*)message);
    double    start, total, each, milliEach;
    
    RsaKey rsaKey;
    int    rsaKeySz = 2048; /* used in printf */

#ifdef USE_CERT_BUFFERS_1024
    XMEMCPY(tmp, rsa_key_der_1024, sizeof_rsa_key_der_1024);
    bytes = sizeof_rsa_key_der_1024;
    rsaKeySz = 1024;
#elif defined(USE_CERT_BUFFERS_2048)
    XMEMCPY(tmp, rsa_key_der_2048, sizeof_rsa_key_der_2048);
    bytes = sizeof_rsa_key_der_2048;
#else
    FILE*  file = fopen(certRSAname, "rb");

    if (!file) {
        printf("can't find %s, Please run from CyaSSL home dir\n", certRSAname);
        return;
    }
    
    bytes = fread(tmp, 1, sizeof(tmp), file);
    fclose(file);
#endif /* USE_CERT_BUFFERS */

		
#ifdef HAVE_CAVIUM
    if (RsaInitCavium(&rsaKey, CAVIUM_DEV_ID) != 0)
        printf("RSA init cavium failed\n");
#endif
    ret = InitRng(&rng);
    if (ret < 0) {
        printf("InitRNG failed\n");
        return;
    }
    ret = InitRsaKey(&rsaKey, 0);
    if (ret < 0) {
        printf("InitRsaKey failed\n");
        return;
    }
    ret = RsaPrivateKeyDecode(tmp, &idx, &rsaKey, (word32)bytes);
    
    start = current_time(1);

    for (i = 0; i < ntimes; i++)
        ret = RsaPublicEncrypt(message,len,enc,sizeof(enc), &rsaKey, &rng);

    total = current_time(0) - start;
    each  = total / ntimes;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("RSA %d encryption took %6.3f milliseconds, avg over %d"
           " iterations\n", rsaKeySz, milliEach, ntimes);

    if (ret < 0) {
        printf("Rsa Public Encrypt failed\n");
        return;
    }

    start = current_time(1);

    for (i = 0; i < ntimes; i++) {
         byte  out[512];  /* for up to 4096 bit */
         RsaPrivateDecrypt(enc, (word32)ret, out, sizeof(out), &rsaKey);
    }

    total = current_time(0) - start;
    each  = total / ntimes;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("RSA %d decryption took %6.3f milliseconds, avg over %d"
           " iterations\n", rsaKeySz, milliEach, ntimes);

    FreeRsaKey(&rsaKey);
#ifdef HAVE_CAVIUM
    RsaFreeCavium(&rsaKey);
#endif
}
Пример #16
0
/* build PKCS#7 envelopedData content type, return enveloped size */
int PKCS7_EncodeEnvelopedData(PKCS7* pkcs7, byte* output, word32 outputSz)
{
    int i, ret = 0, idx = 0;
    int totalSz = 0, padSz = 0, desOutSz = 0;

    int contentInfoSeqSz, outerContentTypeSz, outerContentSz;
    byte contentInfoSeq[MAX_SEQ_SZ];
    byte outerContentType[MAX_ALGO_SZ];
    byte outerContent[MAX_SEQ_SZ];

    int envDataSeqSz, verSz;
    byte envDataSeq[MAX_SEQ_SZ];
    byte ver[MAX_VERSION_SZ];

    RNG rng;
    int contentKeyEncSz, blockKeySz;
    int dynamicFlag = 0;
    byte contentKeyPlain[MAX_CONTENT_KEY_LEN];
    byte contentKeyEnc[MAX_ENCRYPTED_KEY_SZ];
    byte* plain;
    byte* encryptedContent;

    int recipSz, recipSetSz;
    byte recip[MAX_RECIP_SZ];
    byte recipSet[MAX_SET_SZ];

    int encContentOctetSz, encContentSeqSz, contentTypeSz;
    int contentEncAlgoSz, ivOctetStringSz;
    byte encContentSeq[MAX_SEQ_SZ];
    byte contentType[MAX_ALGO_SZ];
    byte contentEncAlgo[MAX_ALGO_SZ];
    byte tmpIv[DES_BLOCK_SIZE];
    byte ivOctetString[MAX_OCTET_STR_SZ];
    byte encContentOctet[MAX_OCTET_STR_SZ];

    if (pkcs7 == NULL || pkcs7->content == NULL || pkcs7->contentSz == 0 ||
        pkcs7->encryptOID == 0 || pkcs7->singleCert == NULL)
        return BAD_FUNC_ARG;

    if (output == NULL || outputSz == 0)
        return BAD_FUNC_ARG;

    /* PKCS#7 only supports DES, 3DES for now */
    switch (pkcs7->encryptOID) {
        case DESb:
            blockKeySz = DES_KEYLEN;
            break;

        case DES3b:
            blockKeySz = DES3_KEYLEN;
            break;

        default:
            CYASSL_MSG("Unsupported content cipher type");
            return ALGO_ID_E;
    };

    /* outer content type */
    outerContentTypeSz = SetContentType(ENVELOPED_DATA, outerContentType);

    /* version, defined as 0 in RFC 2315 */
    verSz = SetMyVersion(0, ver, 0);

    /* generate random content encryption key */
    ret = InitRng(&rng);
    if (ret != 0)
        return ret;

    ret = RNG_GenerateBlock(&rng, contentKeyPlain, blockKeySz);
    if (ret != 0)
        return ret;

    /* build RecipientInfo, only handle 1 for now */
    recipSz = CreateRecipientInfo(pkcs7->singleCert, pkcs7->singleCertSz, RSAk,
                                  blockKeySz, &rng, contentKeyPlain,
                                  contentKeyEnc, &contentKeyEncSz, recip,
                                  MAX_RECIP_SZ);

    if (recipSz < 0) {
        CYASSL_MSG("Failed to create RecipientInfo");
        return recipSz;
    }
    recipSetSz = SetSet(recipSz, recipSet);

    /* generate IV for block cipher */
    ret = RNG_GenerateBlock(&rng, tmpIv, DES_BLOCK_SIZE);
    if (ret != 0)
        return ret;

    /* EncryptedContentInfo */
    contentTypeSz = SetContentType(pkcs7->contentOID, contentType);
    if (contentTypeSz == 0)
        return BAD_FUNC_ARG;

    /* allocate encrypted content buffer, pad if necessary, PKCS#7 padding */
    padSz = DES_BLOCK_SIZE - (pkcs7->contentSz % DES_BLOCK_SIZE);
    desOutSz = pkcs7->contentSz + padSz;

    if (padSz != 0) {
        plain = XMALLOC(desOutSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        if (plain == NULL) {
            return MEMORY_E;
        }
        XMEMCPY(plain, pkcs7->content, pkcs7->contentSz);
        dynamicFlag = 1;

        for (i = 0; i < padSz; i++) {
            plain[pkcs7->contentSz + i] = padSz;
        }

    } else {
        plain = pkcs7->content;
        desOutSz = pkcs7->contentSz;
    }

    encryptedContent = XMALLOC(desOutSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (encryptedContent == NULL) {
        if (dynamicFlag)
            XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }

    /* put together IV OCTET STRING */
    ivOctetStringSz = SetOctetString(DES_BLOCK_SIZE, ivOctetString);

    /* build up our ContentEncryptionAlgorithmIdentifier sequence,
     * adding (ivOctetStringSz + DES_BLOCK_SIZE) for IV OCTET STRING */
    contentEncAlgoSz = SetAlgoID(pkcs7->encryptOID, contentEncAlgo,
                                 blkType, ivOctetStringSz + DES_BLOCK_SIZE);
    if (contentEncAlgoSz == 0)
        return BAD_FUNC_ARG;

    /* encrypt content */
    if (pkcs7->encryptOID == DESb) {
        Des des;

        ret = Des_SetKey(&des, contentKeyPlain, tmpIv, DES_ENCRYPTION);

        if (ret == 0)
            Des_CbcEncrypt(&des, encryptedContent, plain, desOutSz);

        if (ret != 0) {
            XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            if (dynamicFlag)
                XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            return ret;
        }
    }
    else if (pkcs7->encryptOID == DES3b) {
        Des3 des3;

        ret = Des3_SetKey(&des3, contentKeyPlain, tmpIv, DES_ENCRYPTION);

        if (ret == 0)
            ret = Des3_CbcEncrypt(&des3, encryptedContent, plain, desOutSz);

        if (ret != 0) {
            XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            if (dynamicFlag)
                XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            return ret;
        }
    }

    encContentOctetSz = SetImplicit(ASN_OCTET_STRING, 0,
                                    desOutSz, encContentOctet);

    encContentSeqSz = SetSequence(contentTypeSz + contentEncAlgoSz +
                                  ivOctetStringSz + DES_BLOCK_SIZE +
                                  encContentOctetSz + desOutSz, encContentSeq);

    /* keep track of sizes for outer wrapper layering */
    totalSz = verSz + recipSetSz + recipSz + encContentSeqSz + contentTypeSz +
              contentEncAlgoSz + ivOctetStringSz + DES_BLOCK_SIZE +
              encContentOctetSz + desOutSz;

    /* EnvelopedData */
    envDataSeqSz = SetSequence(totalSz, envDataSeq);
    totalSz += envDataSeqSz;

    /* outer content */
    outerContentSz = SetExplicit(0, totalSz, outerContent);
    totalSz += outerContentTypeSz;
    totalSz += outerContentSz;

    /* ContentInfo */
    contentInfoSeqSz = SetSequence(totalSz, contentInfoSeq);
    totalSz += contentInfoSeqSz;

    if (totalSz > (int)outputSz) {
        CYASSL_MSG("Pkcs7_encrypt output buffer too small");
        XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        if (dynamicFlag)
            XFREE(plain, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return BUFFER_E;
    }

    XMEMCPY(output + idx, contentInfoSeq, contentInfoSeqSz);
    idx += contentInfoSeqSz;
    XMEMCPY(output + idx, outerContentType, outerContentTypeSz);
    idx += outerContentTypeSz;
    XMEMCPY(output + idx, outerContent, outerContentSz);
    idx += outerContentSz;
    XMEMCPY(output + idx, envDataSeq, envDataSeqSz);
    idx += envDataSeqSz;
    XMEMCPY(output + idx, ver, verSz);
    idx += verSz;
    XMEMCPY(output + idx, recipSet, recipSetSz);
    idx += recipSetSz;
    XMEMCPY(output + idx, recip, recipSz);
    idx += recipSz;
    XMEMCPY(output + idx, encContentSeq, encContentSeqSz);
    idx += encContentSeqSz;
    XMEMCPY(output + idx, contentType, contentTypeSz);
    idx += contentTypeSz;
    XMEMCPY(output + idx, contentEncAlgo, contentEncAlgoSz);
    idx += contentEncAlgoSz;
    XMEMCPY(output + idx, ivOctetString, ivOctetStringSz);
    idx += ivOctetStringSz;
    XMEMCPY(output + idx, tmpIv, DES_BLOCK_SIZE);
    idx += DES_BLOCK_SIZE;
    XMEMCPY(output + idx, encContentOctet, encContentOctetSz);
    idx += encContentOctetSz;
    XMEMCPY(output + idx, encryptedContent, desOutSz);
    idx += desOutSz;

#ifdef NO_RC4
    FreeRng(&rng);
#endif

    XMEMSET(contentKeyPlain, 0, MAX_CONTENT_KEY_LEN);
    XMEMSET(contentKeyEnc,   0, MAX_ENCRYPTED_KEY_SZ);

    if (dynamicFlag)
        XFREE(plain, NULL, DYNAMMIC_TYPE_TMP_BUFFER);
    XFREE(encryptedContent, NULL, DYNAMIC_TYPE_TMP_BUFFER);

    return idx;
}
Пример #17
0
void bench_eccKeyAgree(void)
{
    ecc_key genKey, genKey2;
    double start, total, each, milliEach;
    int    i, ret;
    byte   shared[1024];
    byte   sig[1024];
    byte   digest[32];
    word32 x = 0;
 
    ecc_init(&genKey);
    ecc_init(&genKey2);

    ret = InitRng(&rng);
    if (ret < 0) {
        printf("InitRNG failed\n");
        return;
    }

    ret = ecc_make_key(&rng, 32, &genKey);
    if (ret != 0) {
        printf("ecc_make_key failed\n");
        return;
    }
    ret = ecc_make_key(&rng, 32, &genKey2);
    if (ret != 0) {
        printf("ecc_make_key failed\n");
        return;
    }

    /* 256 bit */ 
    start = current_time(1);

    for(i = 0; i < agreeTimes; i++) {
        x = sizeof(shared);
        ret = ecc_shared_secret(&genKey, &genKey2, shared, &x);
        if (ret != 0) {
            printf("ecc_shared_secret failed\n");
            return; 
        }
    }

    total = current_time(0) - start;
    each  = total / agreeTimes;  /* per second  */
    milliEach = each * 1000;   /* millisconds */
    printf("EC-DHE   key agreement   %6.3f milliseconds, avg over %d"
           " iterations\n", milliEach, agreeTimes);

    /* make dummy digest */
    for (i = 0; i < (int)sizeof(digest); i++)
        digest[i] = (byte)i;


    start = current_time(1);

    for(i = 0; i < agreeTimes; i++) {
        x = sizeof(sig);
        ret = ecc_sign_hash(digest, sizeof(digest), sig, &x, &rng, &genKey);
        if (ret != 0) {
            printf("ecc_sign_hash failed\n");
            return; 
        }
    }

    total = current_time(0) - start;
    each  = total / agreeTimes;  /* per second  */
    milliEach = each * 1000;   /* millisconds */
    printf("EC-DSA   sign   time     %6.3f milliseconds, avg over %d"
           " iterations\n", milliEach, agreeTimes);

    start = current_time(1);

    for(i = 0; i < agreeTimes; i++) {
        int verify = 0;
        ret = ecc_verify_hash(sig, x, digest, sizeof(digest), &verify, &genKey);
        if (ret != 0) {
            printf("ecc_verify_hash failed\n");
            return; 
        }
    }

    total = current_time(0) - start;
    each  = total / agreeTimes;  /* per second  */
    milliEach = each * 1000;     /* millisconds */
    printf("EC-DSA   verify time     %6.3f milliseconds, avg over %d"
           " iterations\n", milliEach, agreeTimes);

    ecc_free(&genKey2);
    ecc_free(&genKey);
}
Пример #18
0
void bench_dh(void)
{
#if !defined(USE_CERT_BUFFERS_1024) && !defined(USE_CERT_BUFFERS_2048)
    int    ret;
#endif
    int    i ;
    byte   tmp[1024];
    size_t bytes;
    word32 idx = 0, pubSz, privSz = 0, pubSz2, privSz2, agreeSz;

    byte   pub[256];    /* for 2048 bit */
    byte   priv[256];   /* for 2048 bit */
    byte   pub2[256];   /* for 2048 bit */
    byte   priv2[256];  /* for 2048 bit */
    byte   agree[256];  /* for 2048 bit */
    
    double start, total, each, milliEach;
    DhKey  dhKey;
    int    dhKeySz = 2048; /* used in printf */

	
#ifdef USE_CERT_BUFFERS_1024
    XMEMCPY(tmp, dh_key_der_1024, sizeof_dh_key_der_1024);
    bytes = sizeof_dh_key_der_1024;
    dhKeySz = 1024;
#elif defined(USE_CERT_BUFFERS_2048)
    XMEMCPY(tmp, dh_key_der_2048, sizeof_dh_key_der_2048);
    bytes = sizeof_dh_key_der_2048;
#else
    FILE*  file = fopen(certDHname, "rb");

    if (!file) {
        printf("can't find %s,  Please run from CyaSSL home dir\n", certDHname);
        return;
    }

    ret = InitRng(&rng);
    if (ret < 0) {
        printf("InitRNG failed\n");
        return;
    }
    bytes = fread(tmp, 1, sizeof(tmp), file);
#endif /* USE_CERT_BUFFERS */

		
    InitDhKey(&dhKey);
    bytes = DhKeyDecode(tmp, &idx, &dhKey, (word32)bytes);
    if (bytes != 0) {
        printf("dhekydecode failed, can't benchmark\n");
        #if !defined(USE_CERT_BUFFERS_1024) && !defined(USE_CERT_BUFFERS_2048)
            fclose(file);
        #endif
        return;
    }

    start = current_time(1);

    for (i = 0; i < ntimes; i++)
        DhGenerateKeyPair(&dhKey, &rng, priv, &privSz, pub, &pubSz);

    total = current_time(0) - start;
    each  = total / ntimes;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("DH  %d key generation  %6.3f milliseconds, avg over %d"
           " iterations\n", dhKeySz, milliEach, ntimes);

    DhGenerateKeyPair(&dhKey, &rng, priv2, &privSz2, pub2, &pubSz2);
    start = current_time(1);

    for (i = 0; i < ntimes; i++)
        DhAgree(&dhKey, agree, &agreeSz, priv, privSz, pub2, pubSz2);

    total = current_time(0) - start;
    each  = total / ntimes;   /* per second   */
    milliEach = each * 1000; /* milliseconds */

    printf("DH  %d key agreement   %6.3f milliseconds, avg over %d"
           " iterations\n", dhKeySz, milliEach, ntimes);

#if !defined(USE_CERT_BUFFERS_1024) && !defined(USE_CERT_BUFFERS_2048)
    fclose(file);
#endif
    FreeDhKey(&dhKey);
}
Пример #19
0
/*
 * Encrypts a file using Camellia 
 */
int CamelliaEncrypt(Camellia* cam, byte* key, int size, FILE* inFile, 
    FILE* outFile)
{
    RNG     rng;
    byte    iv[CAMELLIA_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 % CAMELLIA_BLOCK_SIZE != 0) {
        length++;
        padCounter++;
    }

    input = malloc(length);
    output = malloc(length);

    ret = InitRng(&rng);
    if (ret != 0) {
        printf("Failed to initialize random number generator\n");
        return -1030;
    }

    /* reads from inFile and wrties 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++) {
        /* padds the added characters with the number of pads */
        input[i] = padCounter;
    }

    ret = RNG_GenerateBlock(&rng, iv, CAMELLIA_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 = CamelliaSetKey(cam, key, CAMELLIA_BLOCK_SIZE, iv);
    if (ret != 0)
        return -1001;

    /* encrypts the message to the ouput based on input length + padding */
    CamelliaCbcEncrypt(cam, output, input, length);

    /* writes to outFile */
    fwrite(salt, 1, SALT_SIZE, outFile);
    fwrite(iv, 1, CAMELLIA_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);

    return 0;
}
Пример #20
0
int rsa_test()
{
    byte   tmp[1024], tmp2[2048];
    size_t bytes, bytes2;
    RsaKey key;
    RNG    rng;
    word32 idx = 0;
    int    ret;
    byte   in[] = "Everyone gets Friday off.";
    word32 inLen = (word32)strlen((char*)in);
    byte   out[64];
    byte   plain[64];
    DecodedCert cert;

    FILE*  file = fopen(clientKey, "rb"), * file2;

    if (!file)
        return -40;

    bytes = fread(tmp, 1, 1024, file);
  
    InitRsaKey(&key, 0);  
    ret = RsaPrivateKeyDecode(tmp, &idx, &key, (word32)bytes);
    if (ret != 0) return -41;

    ret = InitRng(&rng);
    if (ret != 0) return -42;

    ret = RsaPublicEncrypt(in, inLen, out, sizeof(out), &key, &rng);  

    ret = RsaPrivateDecrypt(out, 64, plain, sizeof(plain), &key);

    if (memcmp(plain, in, inLen)) return -45;

    ret = RsaSSL_Sign(in, inLen, out, sizeof(out), &key, &rng);
    memset(plain, 0, sizeof(plain));
    ret = RsaSSL_Verify(out, 64, plain, sizeof(plain), &key);

    if (memcmp(plain, in, ret)) return -46;

    file2 = fopen(clientCert, "rb");
    if (!file2)
        return -47;

    bytes2 = fread(tmp2, 1, 2048, file2);

    InitDecodedCert(&cert, (byte*)&tmp2, 0);

    ret = ParseCert(&cert, (word32)bytes2, CERT_TYPE, NO_VERIFY, 0);
    if (ret != 0) return -48;

    FreeDecodedCert(&cert);

    fclose(file2);
    fclose(file);

#ifdef CYASSL_KEY_GEN
    {
        byte   der[4096];
        byte   pem[4096];
        word32 derSz = 0;
        word32 pemSz = 0;
        RsaKey derIn;
        RsaKey genKey;
        FILE* keyFile;
        FILE* pemFile;

        InitRsaKey(&genKey, 0);
        ret = MakeRsaKey(&genKey, 1024, 65537, &rng);
        if (ret != 0)
            return -301;

        derSz = RsaKeyToDer(&genKey, der, sizeof(der));
        if (derSz < 0)
            return -302;

        keyFile = fopen("./ker.der", "wb");
        if (!keyFile)
            return -303;
        ret = fwrite(der, derSz, 1, keyFile);
        fclose(keyFile);

        pemSz = DerToPem(der, derSz, pem, sizeof(pem), PRIVATEKEY_TYPE);
        if (pemSz < 0)
            return -304;

        pemFile = fopen("./key.pem", "wb");
        if (!pemFile) 
            return -305;
        ret = fwrite(pem, pemSz, 1, pemFile);
        fclose(pemFile);

        InitRsaKey(&derIn, 0);
        idx = 0;
        ret = RsaPrivateKeyDecode(der, &idx, &derIn, derSz);
        if (ret != 0)
            return -306;
    }
#endif /* CYASSL_KEY_GEN */


#ifdef CYASSL_CERT_GEN
    {
        Cert        myCert;
        byte        derCert[4096];
        byte        pem[4096];
        DecodedCert decode;
        FILE*       derFile;
        FILE*       pemFile;
        int         certSz;
        int         pemSz;

        InitCert(&myCert);

        strncpy(myCert.subject.country, "US", NAME_SIZE);
        strncpy(myCert.subject.state, "OR", NAME_SIZE);
        strncpy(myCert.subject.locality, "Portland", NAME_SIZE);
        strncpy(myCert.subject.org, "yaSSL", NAME_SIZE);
        strncpy(myCert.subject.unit, "Development", NAME_SIZE);
        strncpy(myCert.subject.commonName, "www.yassl.com", NAME_SIZE);
        strncpy(myCert.subject.email, "*****@*****.**", NAME_SIZE);

        certSz = MakeCert(&myCert, derCert, sizeof(derCert), &key, &rng); 
        if (certSz < 0)
            return -401;

        InitDecodedCert(&decode, derCert, 0);
        ret = ParseCert(&decode, certSz, CERT_TYPE, NO_VERIFY, 0);
        if (ret != 0)
            return -402;

        derFile = fopen("./cert.der", "wb");
        if (!derFile)
            return -403;
        ret = fwrite(derCert, certSz, 1, derFile);
        fclose(derFile);

        pemSz = DerToPem(derCert, certSz, pem, sizeof(pem), CERT_TYPE);
        if (pemSz < 0)
            return -404;

        pemFile = fopen("./cert.pem", "wb");
        if (!pemFile)
            return -405;
        ret = fwrite(pem, pemSz, 1, pemFile);
        fclose(pemFile);

        FreeDecodedCert(&decode);

    }
#endif /* CYASSL_CERT_GEN */

    FreeRsaKey(&key);

    return 0;
}