void cpCreate(void *arg)
{
	CE_CertPolicies *cp = (CE_CertPolicies *)arg;
	cp->numPolicies = genRand(1,3);
	//cp->numPolicies = 1;
	unsigned len = sizeof(CE_PolicyInformation) * cp->numPolicies;
	cp->policies = (CE_PolicyInformation *)malloc(len);
	memset(cp->policies, 0, len);
	
	for(unsigned polDex=0; polDex<cp->numPolicies; polDex++) {
		CE_PolicyInformation *pi = &cp->policies[polDex];
		unsigned die = genRand(1, NUM_CP_OIDS);
		pi->certPolicyId = cpOids[die - 1];
		unsigned numQual = genRand(1,3);
		pi->numPolicyQualifiers = numQual;
		len = sizeof(CE_PolicyQualifierInfo) * numQual;
		pi->policyQualifiers = (CE_PolicyQualifierInfo *)
			malloc(len);
		memset(pi->policyQualifiers, 0, len);
		for(unsigned cpiDex=0; cpiDex<numQual; cpiDex++) {
			CE_PolicyQualifierInfo *qi = 
				&pi->policyQualifiers[cpiDex];
			if(randBool()) {
				qi->policyQualifierId = CSSMOID_QT_CPS;
				die = genRand(1, NUM_CPS_STR);
				qi->qualifier.Data = (uint8 *)someCPSs[die - 1];
				qi->qualifier.Length = strlen((char *)qi->qualifier.Data);
			}
			else {
				qi->policyQualifierId = CSSMOID_QT_UNOTICE;
				if(randBool()) {
					qi->qualifier.Data = someUnotice;
					qi->qualifier.Length = 5;
				}
				else {
					qi->qualifier.Data = someOtherData;
					qi->qualifier.Length = 4;
				}
			}
		}
	}
}
void AlGenetico::generar(Bola* pPoblacionInicial){
	int posBB[dos]={genRand(cero,posXPista),genRand(cero,posYPista)};
	for(int i=cero; i<poblacionI;i++){
		unsigned short direcc=(unsigned short)genRand(uno,anguloMax);
		unsigned short fuerza=(unsigned short)genRand(cero,fuerzaMax);
		int pos[dos]={genRand(cero,posXPista),genRand(cero,posYPista)};
		pPoblacionInicial= new Bola(posBB);
		pPoblacionInicial->setAttr(direcc,fuerza,pos);
		pPoblacionInicial++;
	}
	pPoblacionInicial-=10;
	/**
	 * for para encliclar hasta alcazar objetivo o maximas generaciones
	 */
	for (int i=cero; i<CantGeneraciones; i++){
		for(int i=cero; i<poblacionI;i++){
			pPoblacionInicial->correr();
			_poblacion[i]=pPoblacionInicial;
			pPoblacionInicial++;
		}
		//condicion para detener el generico por objetivo alcanzado
		if(find())
			break;
		//si no, hacemos una nueva especie y volvemos a iterar
		reproducir();
	}
}
int main()
{
	int hp = 100, dragonHp = 1000;
	printf("You are sent out of the kingdom ");
	printf("by the King to slay a dragon.\n");
	while (dragonHp > 0 && hp > 0)
	{
		int dmg, ddmg;
		char *str = 3000;
		char *cstr = 3081;
		printf("The dragon is unpredictable. What are you going to do?\n");
		printf("Your hp: %d, Dragon hp: %d\n", hp, dragonHp);
		printf("(Attack: 1 | Heal: 2): ");
		dmg = genRand(hp);
		ddmg = genRand(100);
		gets(str,1);
		cstr = to_c_str(str,cstr)
		if (cstr[0] - '0' == 1)
		{
			printf("You deal %d damage to the dragon!\n",dmg);
			printf("The dragon also attacks you for %d damage\n",ddmg);
			hp -= ddmg;
			dragonHp -= dmg;
		} else {
			printf("The dragon attacks you while you heal!\n");
			printf("You heal for %d\n",dmg);
			printf("You take %d damage\n",ddmg);
			hp += dmg;
			hp -= ddmg;
		}
	}
	if (dragonHp < 1)
	{
		printf("You have slain the dragon!\n");
	} else {
		printf("Whelp, that didn't end well did it?\n");
	}
	return 0;
}
void rdnCreate(
	CSSM_X509_RDN_PTR rdn)
{
	unsigned numPairs = genRand(1,4);
	rdn->numberOfPairs = numPairs;
	unsigned len = numPairs * sizeof(CSSM_X509_TYPE_VALUE_PAIR);
	rdn->AttributeTypeAndValue = 
		(CSSM_X509_TYPE_VALUE_PAIR_PTR)malloc(len);
	memset(rdn->AttributeTypeAndValue, 0, len);
	
	for(unsigned atvDex=0; atvDex<numPairs; atvDex++) {
		CSSM_X509_TYPE_VALUE_PAIR &pair = 
			rdn->AttributeTypeAndValue[atvDex];
		unsigned die = genRand(1, NUM_ATTR_TYPES);
		pair.type = attrTypes[die - 1];
		die = genRand(1, NUM_ATTR_STRINGS);
		char *str = attrStrings[die - 1];
		pair.value.Data = (uint8 *)str;
		pair.value.Length = strlen(str);
		die = genRand(1, NUM_ATTR_TAGS);
		pair.valueType = attrTags[die - 1];
	}
}
示例#5
0
文件: Util.cpp 项目: gnishida/VHCMCMC
/**
 * Normal distributionを使用して乱数を生成する。
 */
float Util::genRandNormal(float mean, float variance) {
	/*
	static std::default_random_engine generator;

	std::normal_distribution<float> distribution(mean, sqrtf(variance));
	return distribution(generator);
	*/

#if 1
	float m = mean;
	float s = sqrt(variance);

	/* mean m, standard deviation s */
	float x1, x2, w, y1;
	static float y2;
	static int use_last = 0;

	if (use_last) {	/* use value from previous call */
		y1 = y2;
		use_last = 0;
	} else {
		do {
			x1 = 2.0 * genRand(0.0f, 1.0f) - 1.0;
			x2 = 2.0 * genRand(0.0f, 1.0f) - 1.0;
			w = x1 * x1 + x2 * x2;
		} while ( w >= 1.0 );

		w = sqrt( (-2.0 * log( w ) ) / w );
		y1 = x1 * w;
		y2 = x2 * w;
		use_last = 1;
	}

	return m + y1 * s;
#endif
}
void x509NameCreate(
	CSSM_X509_NAME_PTR x509Name)
{
	memset(x509Name, 0, sizeof(*x509Name));
	unsigned numRdns = genRand(1,4);
	x509Name->numberOfRDNs = numRdns;
	unsigned len = numRdns * sizeof(CSSM_X509_RDN);
	x509Name->RelativeDistinguishedName = (CSSM_X509_RDN_PTR)malloc(len);
	memset(x509Name->RelativeDistinguishedName, 0, len);
	
	for(unsigned rdnDex=0; rdnDex<numRdns; rdnDex++) {
		CSSM_X509_RDN &rdn = x509Name->RelativeDistinguishedName[rdnDex];
		rdnCreate(&rdn);
	}
}
示例#7
0
void Chunk::update()
{
	if (shouldUpdate)
	{
		switch (m_genMethod)
		{
		case RANDOM:
			genRand(randBand(randEngine));
			break;
		case SPHERE:
			genSphere();
			break;
		case ALL:
			genAll();
			break;
		default:
			Debug_Log(" ERROR? : genMethod = NONE");
			break;
		}
	}
	shouldUpdate = false;
}
CSSM_BOOL randBool()
{
	unsigned r = genRand(1, 0x10000000);
	return (r & 0x1) ? CSSM_TRUE : CSSM_FALSE;
}
示例#9
0
文件: Util.cpp 项目: gnishida/VHCMCMC
/**
 * 指定された範囲[a, b)のUniform乱数を生成する
 */
float Util::genRand(float a, float b) {
	return genRand() * (b - a) + a;
}
static int doTest(CSSM_CSP_HANDLE cspHand,
	CSSM_DATA_PTR ptext,
	uint32 keyAlg,						// CSSM_ALGID_xxx of the key
	uint32 encrAlg,						// encrypt/decrypt
	uint32 mode,
	uint32 padding,
	uint32 effectiveKeySizeInBits,
	CSSM_BOOL refKey,
	CSSM_DATA_PTR pwd,				// password- NULL means use a random key data
	CSSM_BOOL stagedEncr,
	CSSM_BOOL stagedDecr,
	CSSM_BOOL mallocPtext,			// only meaningful if !stagedDecr
	CSSM_BOOL mallocCtext,			// only meaningful if !stagedEncr
	CSSM_BOOL quiet,
	CSSM_BOOL keyGenOnly,
	CSSM_BOOL expectEqualText)		// ptext size must == ctext size
{
	CSSM_KEY_PTR	symKey = NULL;
	CSSM_DATA 		ctext = {0, NULL};
	CSSM_DATA		rptext = {0, NULL};
	CSSM_RETURN		crtn;
	int				rtn = 0;
	uint32			keySizeInBits;
	CSSM_DATA 		initVector;
	uint32			rounds = 0;
	
	/* generate keys with well aligned sizes; effectiveKeySize specified in encrypt
	 * only if not well aligned */
	keySizeInBits = (effectiveKeySizeInBits + 7) & ~7;
	if(keySizeInBits == effectiveKeySizeInBits) {
		effectiveKeySizeInBits = 0;
	}
	
	if(encrAlg == CSSM_ALGID_RC5) {
		/* roll the dice, pick one of three values for rounds */
		unsigned die = genRand(1,3);
		switch(die) {
			case 1:
				rounds = 8;
				break;
			case 2:
				rounds = 12;
				break;
			case 3:
				rounds = 16;
				break;
		}
	}

	if(pwd == NULL) {
		/* random key */
		symKey = cspGenSymKey(cspHand,
				keyAlg,
				"noLabel",
				7,
				CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
				keySizeInBits,
				refKey);
	}
	else {
		/* this code isn't tested */
		uint32	  pbeAlg;
		initVector.Data = NULL;		// we're going to ignore this
		initVector.Length = 0;
		/* one of two random PBE algs */
		if(ptext->Data[0] & 1) {
			pbeAlg = PBE_DERIVE_ALG_ODD;
		}
		else {
			pbeAlg = PBE_DERIVE_ALG_EVEN;
		}
		symKey = cspDeriveKey(cspHand,
			pbeAlg,
			keyAlg,
			"noLabel",
			7,
			CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT,
			keySizeInBits,
			refKey, 
			pwd,
			&seedData,
			1,			// iteration count
			&initVector);
		if(initVector.Data != NULL) {
			CSSM_FREE(initVector.Data);
		}
	}
	if(symKey == NULL) {
		rtn = testError(quiet);
		goto abort;
	}
	if(keyGenOnly) {
		rtn = 0;
		goto abort;
	}
	
	/* not all algs need this, pass it in anyway */
	initVector.Data = (uint8 *)"someStrangeInitVect";
	switch(encrAlg) {
		case CSSM_ALGID_AES:
		case CSSM_ALGID_NONE:
			initVector.Length = 16;
			break;
		default:
			initVector.Length = 8;
			break;
	}
	if(stagedEncr) {
		crtn = cspStagedEncrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			0,			// cipherBlockSize
			rounds,
			&initVector,
			ptext,
			&ctext,
			CSSM_TRUE);	// multi
	}
	else {
		const CSSM_DATA *ptextPtr = ptext;
		if(expectEqualText && mallocCtext && CSPDL_NOPAD_ENFORCE_SIZE) {
			/* 
			 * !pad test: ensure this works when ctextlen == ptextlen by 
			 * mallocing ourself right now (instead of cspEncrypt doing it 
			 * after doing a CSSM_QuerySize())
			 */
			ctext.Data = (uint8 *)appMalloc(ptext->Length, NULL);
			if(ctext.Data == NULL) {
				printf("memmory failure\n");
				rtn = testError(quiet);
				goto abort;
			}
			ctext.Length = ptext->Length;
			#if	EQUAL_TEXT_IN_PLACE
			/* encrypt in place */
			memmove(ctext.Data, ptext->Data, ptext->Length);
			ptextPtr = &ctext;
			#endif
		}
		crtn = cspEncrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			rounds,
			&initVector,
			ptextPtr,
			&ctext,
			mallocCtext);
	}
	if(crtn) {
		rtn = testError(quiet);
		goto abort;
	}
	if(expectEqualText && (ptext->Length != ctext.Length)) {
		printf("***ctext/ptext length mismatch: ptextLen %lu  ctextLen %lu\n",
			ptext->Length, ctext.Length);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	logSize(("###ctext len %lu\n", ctext.Length)); 
	if(stagedDecr) {
		crtn = cspStagedDecrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			0,			// cipherBlockSize
			rounds,
			&initVector,
			&ctext,
			&rptext,
			CSSM_TRUE);	// multi
	}
	else {
		const CSSM_DATA *ctextPtr = &ctext;
		if(expectEqualText && mallocPtext && CSPDL_NOPAD_ENFORCE_SIZE) {
			/* 
			 * !pad test: ensure this works when ctextlen == ptextlen by 
			 * mallocing ourself right now (instead of cspDecrypt doing it 
			 * after doing a CSSM_QuerySize())
			 */
			rptext.Data = (uint8 *)appMalloc(ctext.Length, NULL);
			if(rptext.Data == NULL) {
				printf("memmory failure\n");
				rtn = testError(quiet);
				goto abort;
			}
			rptext.Length = ctext.Length;
			#if	EQUAL_TEXT_IN_PLACE
			/* decrypt in place */
			memmove(rptext.Data, ctext.Data, ctext.Length);
			ctextPtr = &rptext;
			#endif
		}
		crtn = cspDecrypt(cspHand,
			encrAlg,
			mode,
			padding,
			symKey,
			NULL,		// second key unused
			effectiveKeySizeInBits,
			rounds,
			&initVector,
			ctextPtr,
			&rptext,
			mallocPtext);
	}
	if(crtn) {
		rtn = testError(quiet);
		goto abort;
	}
	logSize(("###rptext len %lu\n", rptext.Length)); 
	/* compare ptext, rptext */
	if(ptext->Length != rptext.Length) {
		printf("Ptext length mismatch: expect %lu, got %lu\n", ptext->Length, rptext.Length);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(ptext->Data, rptext.Data, ptext->Length)) {
		printf("***data miscompare\n");
		rtn = testError(quiet);
	}
abort:
	/* free key if we have it*/
	if(symKey != NULL) {
		if(cspFreeKey(cspHand, symKey)) {
			printf("Error freeing privKey\n");
			rtn = 1;
		}
		CSSM_FREE(symKey);
	}
	/* free rptext, ctext */
	appFreeCssmData(&rptext, CSSM_FALSE);
	appFreeCssmData(&ctext, CSSM_FALSE);
	return rtn;
}
示例#11
0
int main(int argc, char **argv)
{
	int					arg;
	char				*argp;
	unsigned			loop;
	uint8				*ptext;
	size_t				ptextLen;
	bool				stagedEncr = false;
	bool				stagedDecr = false;
	bool				doPadding;
	bool				doCbc = false;
	bool				nullIV;
	const char			*algStr;
	CCAlgorithm			encrAlg;	
	int					i;
	int					currAlg;		// ALG_xxx
	uint32				minKeySizeInBytes;
	uint32				maxKeySizeInBytes;
	uint32				keySizeInBytes = 0;
	int					rtn = 0;
	uint32				blockSize;		// for noPadding case
	size_t				ctxSize;		// always set per alg
	size_t				ctxSizeUsed;	// passed to doTest
	bool				askOutSize;		// inquire output size each op
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	SymAlg		minAlg = ALG_FIRST;
	SymAlg		maxAlg = ALG_LAST;
	unsigned	loops = LOOPS_DEF;
	bool		verbose = false;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = false;
	unsigned	pauseInterval = 0;
	bool		paddingSpec = false;		// true: user calls doPadding, const
	bool		cbcSpec = false;			// ditto for doCbc
	bool		stagedSpec = false;			// ditto for stagedEncr and stagedDecr
	bool		inPlace = false;			// en/decrypt in place for ECB
	bool		allocCtxSpec = false;		// use allocCtx
	bool		allocCtx = false;			// allocate context ourself
	
	for(arg=1; arg<argc; arg++) {
		argp = argv[arg];
		switch(argp[0]) {
			case 'a':
				if(argp[1] != '=') {
					usage(argv);
				}
				switch(argp[2]) {
					case 's':
						minAlg = maxAlg = ALG_ASC;
						break;
					case 'd':
						minAlg = maxAlg = ALG_DES;
						break;
					case '3':
						minAlg = maxAlg = ALG_3DES;
						break;
					case '2':
						minAlg = maxAlg = ALG_RC2;
						break;
					case '4':
						minAlg = maxAlg = ALG_RC4;
						break;
					case '5':
						minAlg = maxAlg = ALG_RC5;
						break;
					case 'a':
						minAlg = maxAlg = ALG_AES_128;
						break;
					case 'n':
						minAlg = maxAlg = ALG_AES_192;
						break;
					case 'A':
						minAlg = maxAlg = ALG_AES_256;
						break;
					case 'b':
						minAlg = maxAlg = ALG_BFISH;
						break;
					case 'c':
						minAlg = maxAlg = ALG_CAST;
						break;
					default:
						usage(argv);
				}
				if(maxAlg > ALG_LAST) {
					/* we left them in the switch but we can't use them */
					usage(argv);
				}
				break;
		    case 'l':
				loops = atoi(&argp[2]);
				break;
		    case 'n':
				minPtextSize = atoi(&argp[2]);
				break;
		    case 'm':
				maxPtextSize = atoi(&argp[2]);
				break;
		    case 'k':
		    	minKeySizeInBytes = maxKeySizeInBytes = atoi(&argp[2]);
		    	keySizeSpec = true;
				break;
			case 'x':
				allocCtxSpec = true;
				allocCtx = true;
				break;
			case 'X':
				allocCtxSpec = true;
				allocCtx = false;
				break;
		    case 'v':
		    	verbose = true;
				break;
		    case 'q':
		    	quiet = true;
				break;
		    case 'p':
		    	pauseInterval = atoi(&argp[2]);;
				break;
			case 'o':
				doPadding = false;
				paddingSpec = true;
				break;
			case 'e':
				doCbc = false;
				cbcSpec = true;
				break;
			case 'E':
				doCbc = true;
				cbcSpec = true;
				break;
		    case 'u':
		    	stagedEncr = false;
		    	stagedDecr = false;
				stagedSpec = true;
				break;
		    case 'U':
		    	stagedEncr = true;
		    	stagedDecr = true;
				stagedSpec = true;
				break;
		    case 'h':
		    default:
				usage(argv);
		}
	}
	ptext = (uint8 *)malloc(maxPtextSize);
	if(ptext == NULL) {
		printf("Insufficient heap space\n");
		exit(1);
	}
	/* ptext length set in test loop */
	
	printf("Starting ccSymTest; args: ");
	for(i=1; i<argc; i++) {
		printf("%s ", argv[i]);
	}
	printf("\n");
	
	if(pauseInterval) {
		fpurge(stdin);
		printf("Top of test; hit CR to proceed: ");
		getchar();
	}

	for(currAlg=minAlg; currAlg<=maxAlg; currAlg++) {
		switch(currAlg) {
			case ALG_DES:
				encrAlg = kCCAlgorithmDES;
				blockSize = kCCBlockSizeDES;
				minKeySizeInBytes = kCCKeySizeDES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeDES;
				algStr = "DES";
				break;
			case ALG_3DES:
				encrAlg = kCCAlgorithm3DES;
				blockSize = kCCBlockSize3DES;
				minKeySizeInBytes = kCCKeySize3DES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSize3DES;
				
				algStr = "3DES";
				break;
			case ALG_AES_128:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES128;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES128";
				break;
			case ALG_AES_192:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES192;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES192";
				break;
			case ALG_AES_256:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES256;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES256";
				break;
			case ALG_CAST:
				encrAlg = kCCAlgorithmCAST;
				blockSize = kCCBlockSizeCAST;
				minKeySizeInBytes = kCCKeySizeMinCAST;
				maxKeySizeInBytes = kCCKeySizeMaxCAST;
				ctxSize = kCCContextSizeCAST;
				algStr = "CAST";
				break;
			case ALG_RC4:
				encrAlg = kCCAlgorithmRC4;
				blockSize = 0;
				minKeySizeInBytes = kCCKeySizeMinRC4;
				maxKeySizeInBytes = kCCKeySizeMaxRC4;
				ctxSize = kCCContextSizeRC4;
				algStr = "RC4";
				break;
			default:
				printf("***BRRZAP!\n");
				exit(1);
		}
		if(!quiet || verbose) {
			printf("Testing alg %s\n", algStr);
		}
		for(loop=1; ; loop++) {
			ptextLen = genRand(minPtextSize, maxPtextSize);
			appGetRandomBytes(ptext, ptextLen);
			
			/* per-loop settings */
			if(!keySizeSpec) {
				if(minKeySizeInBytes == maxKeySizeInBytes) {
					keySizeInBytes = minKeySizeInBytes;
				}
				else {
					keySizeInBytes = genRand(minKeySizeInBytes, maxKeySizeInBytes);
				}
			}
			if(blockSize == 0) {
				/* stream cipher */
				doCbc = false;
				doPadding = false;
			}
			else {
				if(!cbcSpec) {
					doCbc = isBitSet(0, loop);
				}
				if(!paddingSpec) {
					doPadding = isBitSet(1, loop);
				}
			}
			if(!doPadding && (blockSize != 0)) {
				/* align plaintext */
				ptextLen = (ptextLen / blockSize) * blockSize;
				if(ptextLen == 0) {
					ptextLen = blockSize;
				}
			}
			if(!stagedSpec) {
				stagedEncr = isBitSet(2, loop);
				stagedDecr = isBitSet(3, loop);
			}
			if(doCbc) {
				nullIV = isBitSet(4, loop);
			}
			else {
				nullIV = false;
			}
			inPlace = isBitSet(5, loop);
			if(allocCtxSpec) {
				ctxSizeUsed = allocCtx ? ctxSize : 0;
			}
			else if(isBitSet(6, loop)) {
				ctxSizeUsed = ctxSize;
			}
			else {
				ctxSizeUsed = 0;
			}
			askOutSize = isBitSet(7, loop);
			if(!quiet) {
			   	if(verbose || ((loop % LOOP_NOTIFY) == 0)) {
					printf("..loop %3d ptextLen %lu keyLen %d cbc=%d padding=%d stagedEncr=%d "
							"stagedDecr=%d\n",
						loop, (unsigned long)ptextLen, (int)keySizeInBytes, 
						(int)doCbc, (int)doPadding,
					 	(int)stagedEncr, (int)stagedDecr);
					printf("           nullIV %d inPlace %d ctxSize %d askOutSize %d\n",
						(int)nullIV, (int)inPlace, (int)ctxSizeUsed, (int)askOutSize);
				}
			}
			
			if(doTest(ptext, ptextLen,
					encrAlg, doCbc, doPadding, nullIV,
					keySizeInBytes,
					stagedEncr,	stagedDecr, inPlace, ctxSizeUsed, askOutSize,
					quiet)) {
				rtn = 1;
				break;
			}
			if(pauseInterval && ((loop % pauseInterval) == 0)) {
				char c;
				fpurge(stdin);
				printf("Hit CR to proceed, q to abort: ");
				c = getchar();
				if(c == 'q') {
					goto testDone;
				}
			}
			if(loops && (loop == loops)) {
				break;
			}
		}	/* main loop */
		if(rtn) {
			break;
		}
		
	}	/* for algs */
	
testDone:
	if(pauseInterval) {
		fpurge(stdin);
		printf("ModuleDetach/Unload complete; hit CR to exit: ");
		getchar();
	}
	if((rtn == 0) && !quiet) {
		printf("%s test complete\n", argv[0]);
	}
	free(ptext);
	return rtn;
}
示例#12
0
static int doTest(const uint8_t *ptext,
	size_t ptextLen,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	bool nullIV,			/* if CBC, use NULL IV */
	uint32 keySizeInBytes,
	bool stagedEncr,
	bool stagedDecr,
	bool inPlace,	
	size_t ctxSize,		
	bool askOutSize,
	bool quiet)
{
	uint8_t			keyBytes[MAX_KEY_SIZE];
	uint8_t			iv[MAX_BLOCK_SIZE];
	uint8_t			*ivPtrEncrypt;
	uint8_t			*ivPtrDecrypt;
	uint8_t			*ctext = NULL;		/* mallocd by doCCCrypt */
	size_t			ctextLen = 0;
	uint8_t			*rptext = NULL;		/* mallocd by doCCCrypt */
	size_t			rptextLen;
	CCCryptorStatus	crtn;
	int				rtn = 0;
	
	/* random key */
	appGetRandomBytes(keyBytes, keySizeInBytes);
	
	/* random IV if needed */
	if(doCbc) {
		if(nullIV) {
			memset(iv, 0, MAX_BLOCK_SIZE);
			
			/* flip a coin, give one side NULL, the other size zeroes */
			if(genRand(1,2) == 1) {
				ivPtrEncrypt = NULL;
				ivPtrDecrypt = iv;
			}
			else {
				ivPtrEncrypt = iv;
				ivPtrDecrypt = NULL;
			}
		}
		else {
			appGetRandomBytes(iv, MAX_BLOCK_SIZE);
			ivPtrEncrypt = iv;
			ivPtrDecrypt = iv;
		}
	}	
	else {
		ivPtrEncrypt = NULL;
		ivPtrDecrypt = NULL;
	}

	crtn = doCCCrypt(true, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrEncrypt,
		stagedEncr, inPlace, ctxSize, askOutSize,
		ptext, ptextLen,
		&ctext, &ctextLen);
	if(crtn) {
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	
	logSize(("###ctext len %lu\n", ctextLen)); 
	
	crtn = doCCCrypt(false, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrDecrypt,
		stagedDecr, inPlace, ctxSize, askOutSize,
		ctext, ctextLen,
		&rptext, &rptextLen);
	if(crtn) {
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}

	logSize(("###rptext len %lu\n", rptextLen)); 
	
	/* compare ptext, rptext */
	if(ptextLen != rptextLen) {
		printf("Ptext length mismatch: expect %lu, got %lu\n", ptextLen, rptextLen);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(ptext, rptext, ptextLen)) {
		printf("***data miscompare\n");
		rtn = testError(quiet);
	}
abort:
	if(ctext) {
		free(ctext);
	}
	if(rptext) {
		free(rptext);
	}
	return rtn;
}
static int doTest(CSSM_CSP_HANDLE cspHand,
	CSSM_ALGORITHMS alg,
	const char *algStr,
	CSSM_DATA_PTR ptext,
	CSSM_BOOL verbose,
	CSSM_BOOL quiet)
{
	CSSM_CC_HANDLE		digHand1 = 0;	// reference
	CSSM_CC_HANDLE		digHand2 = 0;	// to be cloned
	CSSM_CC_HANDLE		digHand3 = 0;	// cloned from digHand2
	CSSM_DATA 			dig1 = {0, NULL};
	CSSM_DATA 			dig2 = {0, NULL};
	CSSM_DATA 			dig3 = {0, NULL};
	CSSM_RETURN			crtn;
	unsigned			thisMove;		// this update
	unsigned			toMove;			// total to go
	unsigned			totalRequest;	// originally requested
	CSSM_DATA			thisText;		// actually passed to update
		
	/* cook up two digest contexts */
	crtn = CSSM_CSP_CreateDigestContext(cspHand,
		alg,
		&digHand1);
	if(crtn) {
		printError("CSSM_CSP_CreateDigestContext (1)", crtn);
		return testError(quiet);
	}
	crtn = CSSM_CSP_CreateDigestContext(cspHand,
		alg,
		&digHand2);
	if(crtn) {
		printError("CSSM_CSP_CreateDigestContext (2)", crtn);
		return testError(quiet);
	}
	crtn = CSSM_DigestDataInit(digHand1);
	if(crtn) {
		printError("CSSM_DigestDataInit (1)", crtn);
		return testError(quiet);
	}
	crtn = CSSM_DigestDataInit(digHand2);
	if(crtn) {
		printError("CSSM_DigestDataInit (2)", crtn);
		return testError(quiet);
	}
	
	/* do some random updates to first two digests, until we've digested
	 * at least half of the requested data */
	totalRequest = ptext->Length;
	toMove = ptext->Length;
	thisText.Data = ptext->Data;
	while(toMove > (totalRequest / 2)) {
		thisMove = genRand((MIN_PTEXT / 2), toMove);
		thisText.Length = thisMove;
		if(verbose) {
			printf("  ..updating digest1, digest2 with %d bytes\n", thisMove);
		}
		crtn = CSSM_DigestDataUpdate(digHand1, &thisText, 1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate (1)", crtn);
			return testError(quiet);
		}
		crtn = CSSM_DigestDataUpdate(digHand2, &thisText, 1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate (2)", crtn);
			return testError(quiet);
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	
	/* digest3 := clone(digest2) */
	crtn = CSSM_DigestDataClone(digHand2, &digHand3);
	if(crtn) {
		printError("CSSM_DigestDataClone", crtn);
		return testError(quiet);
	}
	
	/* finish off remaining ptext, updating all 3 digests identically */
	while(toMove) {
		thisMove = genRand(1, toMove);
		thisText.Length = thisMove;
		if(verbose) {
			printf("  ..updating all three digests with %d bytes\n", thisMove);
		}
		crtn = CSSM_DigestDataUpdate(digHand1, &thisText, 1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate (3)", crtn);
			return testError(quiet);
		}
		crtn = CSSM_DigestDataUpdate(digHand2, &thisText, 1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate (4)", crtn);
			return testError(quiet);
		}
		crtn = CSSM_DigestDataUpdate(digHand3, &thisText, 1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate (5)", crtn);
			return testError(quiet);
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	
	/* obtain all three digests */
	crtn = CSSM_DigestDataFinal(digHand1, &dig1);
	if(crtn) {
		printError("CSSM_DigestDataFinal (1)", crtn);
		return testError(quiet);
	}
	crtn = CSSM_DigestDataFinal(digHand2, &dig2);
	if(crtn) {
		printError("CSSM_DigestDataFinal (2)", crtn);
		return testError(quiet);
	}
	crtn = CSSM_DigestDataFinal(digHand3, &dig3);
	if(crtn) {
		printError("CSSM_DigestDataFinal (3)", crtn);
		return testError(quiet);
	}
	
	/* ensure all three digests identical */
	if(!appCompareCssmData(&dig1, &dig2)) {
		printf("***Digest miscompare(dig1, dig2)***\n");
		if(testError(quiet)) {
			return 1;
		}
	}
	if(!appCompareCssmData(&dig2, &dig3)) {
		printf("***Digest miscompare(dig2, dig3)***\n");
		if(testError(quiet)) {
			return 1;
		}
	}
	
	/* free resources */
	appFreeCssmData(&dig1, CSSM_FALSE);
	appFreeCssmData(&dig2, CSSM_FALSE);
	appFreeCssmData(&dig3, CSSM_FALSE);
	CSSM_DeleteContext(digHand1);
	CSSM_DeleteContext(digHand2);
	CSSM_DeleteContext(digHand3);
	return 0;
}
/*
	The main function called by each thread.  Manage entering, crossing, and
	exiting the bridge for each vehicle.

	Includes the locks, conditional variables, etc.  Exlained in more detail
	within.
*/
void *oneVehicle(void *vargp)
{
	int rc;

	int car_number = (int) vargp;
	int direction = genRand(1);

// ArriveBridge
// Here, based on the direction, the thread gets a lock.  If there are no
// cars on the bridge going the opposite direction AND there's still room
// on the bridge for another car, it waits for its conditional variable
// (basically a green light).

	rc = pthread_mutex_lock(&lock);

	if (rc)
		{
			printf("Lock failed!\n");
			exit(-1);
		}
	
	if(direction == TO_NORWICH)
	{
// Until the signal has been acquired, this vehicle is waiting.  It's saved
// in the waiting array and counted among the waiting cars.
		norwich_wait++;		
		norwich_waiting[car_number] = car_number;

// If there's no traffic going the other way on the bridge, and still room
// (under the max_load), then wait for the green light and acquire the lock.
		while(hanover_count > 0 || norwich_count >= max_load)
		{
		pthread_cond_wait(&toward_norwich, &lock);
		}

// Now that it's received the green light, it's no longer waiting.
		norwich_waiting[car_number] = -1;	
		hanover_waiting[car_number] = -1;
		norwich_wait--;

// It's on the bridge, so now it's counted in that array.
		norwich_count++;	
		bridge[car_number] = car_number;			

// And it's consecutive count is maintained to switch directions later.
		norwich_lim++;

// The state of the bridge has changed, so print its new state.
		printf("%d is on the bridge:\n", car_number);
		printStatus(TO_NORWICH);

// If there are no more norwich-bound cars OR max_load*2 norwich-bound cars
// have already crossed, stop traffic and signal traffic for the other direction.
// Otherwise, keep them coming this way.
		if((norwich_count == 0 || norwich_lim >= (max_load*2)) && hanover_wait > 0)
			pthread_cond_signal(&toward_hanover);
		else
			pthread_cond_signal(&toward_norwich);
	}
	else
	{
// Until the signal has been acquired, this vehicle is waiting.  It's saved
// in the waiting array and counted among the waiting cars.
		hanover_wait++;	
		hanover_waiting[car_number] = car_number;	

// If there's no traffic going the other way on the bridge, and still room
// (under the max_load), then wait for the green light and acquire the lock.
		while(norwich_count > 0 || hanover_count >= max_load)
		{
		pthread_cond_wait(&toward_hanover, &lock);
		}

// Now that it's received the green light, it's no longer waiting.
		norwich_waiting[car_number] = -1;	
		hanover_waiting[car_number] = -1;	
		hanover_wait--;

// It's on the bridge, so now it's counted in that array.
		hanover_count++;
		bridge[car_number] = car_number;

// And it's consecutive count is maintained to switch directions later.
		hanover_lim++;

// The state of the bridge has changed, so print its new state.
		printf("%d is on the bridge:\n", car_number);
		printStatus(TO_HANOVER);

// If there are no more hanover-bound cars OR max_load*2 hanover-bound cars
// have already crossed, stop traffic and signal traffic for the other direction.
// Otherwise, keep them coming this way.
		if((hanover_count == 0 || hanover_lim >= (max_load*2)) && norwich_wait > 0)
			pthread_cond_signal(&toward_norwich);
		else
			pthread_cond_signal(&toward_hanover);
	}

	rc = pthread_mutex_unlock(&lock);

	if (rc)
		{
			printf("Unlock failed!\n");
			exit(-1);
		}

// OnBridge
// Simply a sleep, to make the simulation more meaningful.	
	sleep(1);	// takes 1 seconds to get off the bridge

// ExitBridge
// Here, the threads acquire locks and simulate exiting the bridge.
// If there's still traffic going in the same direction AND it hasn't
// reached max_load*2 cars consecutively, it signals for another car
// of the same direction on.  Else, it singals for a car from the different
// direction to come on.
	rc = pthread_mutex_lock(&lock);

	if (rc)
		{
			printf("Lock failed!\n");
			exit(-1);
		}
	
	if(direction == TO_NORWICH)
	{	
// Car has left the bridge (record it in arrays)
		norwich_count--;
		bridge[car_number] = -1;	

// The opposite direction's consecutive travel meter can be reset
		hanover_lim = 0;

// If there are no more norwich-bound cars OR max_load*2 norwich-bound cars
// have already crossed, stop traffic and signal traffic for the other direction.
// Otherwise, keep them coming this way.
		if((norwich_count == 0 || norwich_lim >= (max_load*2)) && hanover_wait > 0)
			pthread_cond_signal(&toward_hanover);
		else
			pthread_cond_signal(&toward_norwich);

// The status of the bridge has changed, so print it again.
		printf("%d is off the bridge:\n", car_number);
		printStatus(TO_NORWICH);
	}
	else
	{
// Car has left the bridge (record it in arrays)
		hanover_count--;
		bridge[car_number] = -1;		

// The opposite direction's consecutive travel meter can be reset
		norwich_lim = 0;

// If there are no more hanover-bound cars OR max_load*2 hanover-bound cars
// have already crossed, stop traffic and signal traffic for the other direction.
// Otherwise, keep them coming this way.
		if((hanover_count == 0 || hanover_lim >= (max_load*2)) && norwich_wait > 0)
			pthread_cond_signal(&toward_norwich);
		else
			pthread_cond_signal(&toward_hanover);

// The status of the bridge has changed, so print it again.
		printf("%d is off the bridge:\n", car_number);
		printStatus(TO_HANOVER);
	}

	rc = pthread_mutex_unlock(&lock);

	if (rc)
		{
			printf("Unlock failed!\n");
			exit(-1);
		}

	return NULL;
}
pistaVillar::pistaVillar() {
	_bordes[cero]=posXPista;
	_bordes[uno]=posYPista;
	_bolaBlanca[cero]=genRand(cero, _bordes[cero]);
	_bolaBlanca[uno]=genRand(cero, _bordes[uno]);
}
static int doTest(CSSM_CSP_HANDLE cspHand,
	const CSSM_DATA		*ptext,
	const CSSM_DATA		*keyData,
	const CSSM_DATA		*iv,
	uint32 				keyAlg,						// CSSM_ALGID_xxx of the key
	uint32 				encrAlg,						// encrypt/decrypt
	uint32 				encrMode,
	uint32 				padding,
	uint32				keySizeInBits,
	uint32 				efectiveKeySizeInBits,
	uint32				cipherBlockSize,
	CSSM_BOOL			useEvp,					// AES only 
	CSSM_BOOL 			stagedEncr,
	CSSM_BOOL 			stagedDecr,
	CSSM_BOOL 			quiet,
	CSSM_BOOL			encryptOnly,
	CSSM_BOOL			genRaw)					// first generate raw key (CSPDL)
{
	CSSM_DATA 		ctextRef = {0, NULL};		// ciphertext, reference
	CSSM_DATA		ctextTest = {0, NULL};		// ciphertext, test
	CSSM_DATA		rptext = {0, NULL};			// recovered plaintext
	int				rtn = 0;
	CSSM_RETURN		crtn;
	uint32			rounds = 0;
	
	if(encrAlg == CSSM_ALGID_RC5) {
		/* roll the dice, pick one of three values for rounds */
		unsigned die = genRand(1,3);
		switch(die) {
			case 1:
				rounds = 8;
				break;
			case 2:
				rounds = 12;
				break;
			case 3:
				rounds = 16;
				break;
		}
	}
	
	/*
	 * encrypt with each method;
	 * verify ciphertexts compare;
	 * decrypt with test code;
	 * verify recovered plaintext and incoming plaintext compare;
	 */
	crtn = encryptDecryptRef(CSSM_TRUE,
		encrAlg,
		encrMode,
		iv,
		keySizeInBits,
		efectiveKeySizeInBits, 
		cipherBlockSize,
		rounds,
		useEvp,
		keyData,
		ptext,
		&ctextRef);
	if(crtn) {
		return testError(quiet);
	}
	crtn = encryptDecryptCSSM(cspHand,
		CSSM_TRUE,
		keyAlg,
		encrAlg,
		encrMode,
		padding,
		stagedEncr,
		iv,
		keySizeInBits,
		efectiveKeySizeInBits, 
		cipherBlockSize,
		rounds,
		keyData,
		ptext,
		genRaw,
		&ctextTest);
	if(crtn) {
		return testError(quiet);
	}

	/* ensure both methods resulted in same ciphertext */
	if(ctextRef.Length != ctextTest.Length) {
		printf("Ctext length mismatch (1)\n");
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(ctextRef.Data, ctextTest.Data, ctextTest.Length)) {
		printf("Ctext miscompare\n");
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	
	if(encryptOnly) {
		rtn = 0;
		goto abort;
	}
	
	/* decrypt with the test method */
	crtn = encryptDecryptCSSM(cspHand,
		CSSM_FALSE,
		keyAlg,
		encrAlg,
		encrMode,
		padding,
		stagedDecr,
		iv,
		keySizeInBits,
		efectiveKeySizeInBits, 
		cipherBlockSize,
		rounds,
		keyData,
		&ctextTest,
		genRaw,
		&rptext);
	if(crtn) {
		return testError(quiet);
	}
	if(rptext.Length != ptext->Length) {
		printf("ptext length mismatch (1)\n");
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(rptext.Data, ptext->Data, ptext->Length)) {
		printf("ptext miscompare\n");
		rtn = testError(quiet);
	}
	else {
		rtn = 0;
	}
abort:
	if(ctextTest.Length) {
		CSSM_FREE(ctextTest.Data);
	}
	if(ctextRef.Length) {
		CSSM_FREE(ctextRef.Data);
	}
	if(rptext.Length) {
		CSSM_FREE(rptext.Data);
	}
	return rtn;
}
int main(void){         
		int n,m,x,y,z;    /*rows, columns, loop index, loop index, range*/
		char name[25], na[5], attr1[8], attr2[8], attr3[8];  /*file name, response, attribute names*/
		FILE *outp;     
		/*Seed random*/
		unsigned int iseed = (unsigned int)time(NULL);
		srand(iseed);
		/*Input name and size*/
		printf("Name the file (25 character limit): ");
		scanf("%s", name);
		printf("What is the number of rows(entries)?: ");
		scanf("%d", &n);
		printf("What is the number of columns(attributes)?: ");
		scanf("%d", &m);
		/* Handle Attributes */
		printf("Would you like to name your attributes?(yes or no): ");
                scanf("%s", na);
		if(strcmp(na, "yes")==0 || strcmp(na, "y")==0){
			printf("What is the name of attribute one?: ");
		    scanf("%s", attr1);
			printf("What is the name of attribute two?: ");
		    scanf("%s", attr2);
			printf("What is the name of attribute three?: ");
		    scanf("%s", attr3);
		}
		printf("What is the range for the random generator?: ");
        scanf("%d", &z);
        /*initialize array*/
        double matrix[n][m];
        /*Generate random values and populate array*/
		for (x=0; x<n; x++){
            for(y=0; y<m; y++){
                matrix[x][y] = genRand(z);
            }
        }
        printf("\nValues generated\n");
		/*open file*/
		outp = fopen(name,"w");
		if (outp == NULL){
			printf("Error opening file");
			exit(0);
		}
		/*write to file*/
		int q,w;
		for (q=0; q<n; q++){
			for (w=0; w<m; w++){
				if(q==0){
					if(w==0){
					fprintf(outp, "%7s", attr1);
					}
					else if(w==1){
					fprintf(outp, "%7s", attr2);
					}
					else{
					fprintf(outp, "%7s", attr3);
					}
				}
				else if(q!=0){
				fprintf(outp, "%7.1f", matrix[q][w]);
				}
				}
			fprintf (outp, "\n");
		}
		/*close file*/
		fclose (outp);
        printf("\nComplete!\n");
        return 0;
}
void ekuCreate(void *arg)
{
	CE_ExtendedKeyUsage *eku = (CE_ExtendedKeyUsage *)arg;
	eku->numPurposes = genRand(1, NUM_SKU_OIDS);
	eku->purposes = ekuOids;
}
示例#19
0
/* 
 * Test harness for CCCryptor with lots of options. 
 */
CCCryptorStatus doCCCrypt(
	bool forEncrypt,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	const void *keyBytes, size_t keyLen,
	const void *iv,
	bool randUpdates,
	bool inPlace,								/* !doPadding only */
	size_t ctxSize,								/* if nonzero, we allocate ctx */
	bool askOutSize,
	const uint8_t *inText, size_t inTextLen,
	uint8_t **outText, size_t *outTextLen)		/* both returned, WE malloc */
{
	CCCryptorRef	cryptor = NULL;
	CCCryptorStatus crtn;
	CCOperation		op = forEncrypt ? kCCEncrypt : kCCDecrypt;
	CCOptions		options = 0;
	uint8_t			*outBuf = NULL;			/* mallocd output buffer */
	uint8_t			*outp;					/* running ptr into outBuf */
	const uint8		*inp;					/* running ptr into inText */
	size_t			outLen;					/* bytes remaining in outBuf */
	size_t			toMove;					/* bytes remaining in inText */
	size_t			thisMoveOut;			/* output from CCCryptUpdate()/CCCryptFinal() */
	size_t			outBytes;				/* total bytes actually produced in outBuf */
	char			ctx[CC_MAX_CTX_SIZE];	/* for CCCryptorCreateFromData() */
	uint8_t			*textMarker = NULL;		/* 8 bytes of marker here after expected end of 
											 * output */
	char			*ctxMarker = NULL;		/* ditto for caller-provided context */
	unsigned		dex;
	size_t			askedOutSize;			/* from the lib */
	size_t			thisOutLen;				/* dataOutAvailable we use */
	
	if(ctxSize > CC_MAX_CTX_SIZE) {
		printf("***HEY! Adjust CC_MAX_CTX_SIZE!\n");
		exit(1);
	}
	if(!doCbc) {
		options |= kCCOptionECBMode;
	}
	if(doPadding) {
		options |= kCCOptionPKCS7Padding;
	}
	
	/* just hack this one */
	outLen = inTextLen;
	if(forEncrypt) {
		outLen += MAX_BLOCK_SIZE;
	}
	
	outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH);
	memset(outBuf, 0xEE, outLen + MARKER_LENGTH);
	
	/* library should not touch this memory */
	textMarker = outBuf + outLen;
	memset(textMarker, MARKER_BYTE, MARKER_LENGTH);
	
	/* subsequent errors to errOut: */

	if(inPlace) {
		memmove(outBuf, inText, inTextLen);
		inp = outBuf;
	}
	else {
		inp = inText;
	}

	if(!randUpdates) {
		/* one shot */
		if(askOutSize) {
			crtn = CCCrypt(op, encrAlg, options,
				keyBytes, keyLen, iv,
				inp, inTextLen,
				outBuf, 0, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printf("   alg %d inTextLen %lu cbc %d padding %d keyLen %lu\n",
					(int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding,
					(unsigned long)keyLen);
				printCCError("CCCrypt", crtn);
				crtn = -1;
				goto errOut;
			}
			outLen = askedOutSize;
		}
		crtn = CCCrypt(op, encrAlg, options,
			keyBytes, keyLen, iv,
			inp, inTextLen,
			outBuf, outLen, &outLen);
		if(crtn) {
			printCCError("CCCrypt", crtn);
			goto errOut;
		}
		*outText = outBuf;
		*outTextLen = outLen;
		goto errOut;
	}
	
	/* random multi updates */
	if(ctxSize) {
		size_t ctxSizeCreated;
		
		if(askOutSize) {
			crtn = CCCryptorCreateFromData(op, encrAlg, options,
				keyBytes, keyLen, iv,
				ctx, 0 /* ctxSize */,
				&cryptor, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printCCError("CCCryptorCreateFromData", crtn);
				crtn = -1;
				goto errOut;
			}
			ctxSize = askedOutSize;
		}
		crtn = CCCryptorCreateFromData(op, encrAlg, options,
			keyBytes, keyLen, iv,
			ctx, ctxSize, &cryptor, &ctxSizeCreated);
		if(crtn) {
			printCCError("CCCryptorCreateFromData", crtn);
			return crtn;
		}
		ctxMarker = ctx + ctxSizeCreated;
		memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH);
	}
	else {
		crtn = CCCryptorCreate(op, encrAlg, options,
			keyBytes, keyLen, iv,
			&cryptor);
		if(crtn) {
			printCCError("CCCryptorCreate", crtn);
			return crtn;
		}
	}
	
	toMove = inTextLen;		/* total to go */
	outp = outBuf;
	outBytes = 0;			/* bytes actually produced in outBuf */
	
	while(toMove) {
		uint32 thisMoveIn;			/* input to CCryptUpdate() */
		
		thisMoveIn = genRand(1, toMove);
		logSize(("###ptext segment len %lu\n", (unsigned long)thisMoveIn)); 
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn,
			outp, thisOutLen, &thisMoveOut);
		if(crtn) {
			printCCError("CCCryptorUpdate", crtn);
			goto errOut;
		}
		inp			+= thisMoveIn;
		toMove		-= thisMoveIn;
		outp		+= thisMoveOut;
		outLen   	-= thisMoveOut;
		outBytes	+= thisMoveOut;
	}
	
	if(doPadding) {
		/* Final is not needed if padding is disabled */
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut);
	}
	else {
		thisMoveOut = 0;
		crtn = kCCSuccess;
	}
	
	if(crtn) {
		printCCError("CCCryptorFinal", crtn);
		goto errOut;
	}
	
	outBytes += thisMoveOut;
	*outText = outBuf;
	*outTextLen = outBytes;
	crtn = kCCSuccess;

	for(dex=0; dex<MARKER_LENGTH; dex++) {
		if(textMarker[dex] != MARKER_BYTE) {
			printf("***lib scribbled on our textMarker memory (op=%s)!\n",
				forEncrypt ? "encrypt" : "decrypt");
			crtn = (CCCryptorStatus)-1;
		}
	}
	if(ctxSize) {
		for(dex=0; dex<MARKER_LENGTH; dex++) {
			if(ctxMarker[dex] != MARKER_BYTE) {
				printf("***lib scribbled on our ctxMarker memory (op=%s)!\n",
					forEncrypt ? "encrypt" : "decrypt");
				crtn = (CCCryptorStatus)-1;
			}
		}
	}
	
errOut:
	if(crtn) {
		if(outBuf) {
			free(outBuf);
		}
	}
	if(cryptor) {
		CCCryptorRelease(cryptor);
	}
	return crtn;
}
int main(int argc, char **argv)
{
	CSSM_CL_HANDLE	clHand;			// CL handle
	CSSM_X509_NAME	*subjName;
	CSSM_X509_NAME	*rootName;
	CSSM_X509_TIME	*notBefore;		// UTC-style "not before" time
	CSSM_X509_TIME	*notAfter;		// UTC-style "not after" time
	CSSM_DATA_PTR	rawCert;		// from CSSM_CL_CertCreateTemplate
	CSSM_DATA		signedRootCert;	// from CSSM_CL_CertSign
	CSSM_DATA		signedSubjCert;	// from CSSM_CL_CertSign
	CSSM_CSP_HANDLE	cspHand;		// CSP handle
	CSSM_KEY		subjPubKey;		// subject's RSA public key blob
	CSSM_KEY		subjPrivKey;	// subject's RSA private key - ref format
	CSSM_KEY		rootPubKey;		// root's RSA public key blob
	CSSM_KEY		rootPrivKey;	// root's RSA private key - ref format
	CSSM_RETURN		crtn;
	CSSM_KEY_PTR	extractRootKey;	// from CSSM_CL_CertGetKeyInfo()
	CSSM_KEY_PTR	extractSubjKey;	// ditto
	CSSM_CC_HANDLE	signContext;	// for signing/verifying the cert
	unsigned		badByte;
	int				arg;
	unsigned		errorCount = 0;
	
	/* user-spec'd variables */
	CSSM_BOOL		writeBlobs = CSSM_FALSE;
	CSSM_ALGORITHMS	keyAlg = KEY_ALG_DEFAULT;
	CSSM_ALGORITHMS sigAlg = SIG_ALG_DEFAULT;
	uint32			keySizeInBits = CSP_KEY_SIZE_DEFAULT;
	
	/* 
	 * Two extensions. Subject has one (KeyUsage); root has KeyUsage and 
	 * BasicConstraints.
	 */
	CSSM_X509_EXTENSION 	exts[2];
	CE_KeyUsage				keyUsage;
	CE_BasicConstraints		bc;
	
	for(arg=1; arg<argc; arg++) {
		switch(argv[arg][0]) {
			case 'w':
				writeBlobs = CSSM_TRUE;
				break;
			case 'a':
				if((argv[arg][1] == '\0') || (argv[arg][2] == '\0')) {
					usage(argv);
				}
				switch(argv[arg][2]) {
					case 's':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_SHA1WithRSA;
						break;
					case 'm':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_MD5WithRSA;
						break;
					case 'f':
						keyAlg = CSSM_ALGID_FEE;
						sigAlg = CSSM_ALGID_FEE_MD5;
						break;
					case 'F':
						keyAlg = CSSM_ALGID_FEE;
						sigAlg = CSSM_ALGID_FEE_SHA1;
						break;
					case 'e':
						keyAlg = CSSM_ALGID_FEE;
						sigAlg = CSSM_ALGID_SHA1WithECDSA;
						break;
					case 'E':
						keyAlg = CSSM_ALGID_ECDSA;
						sigAlg = CSSM_ALGID_SHA1WithECDSA;
						break;
					case '7':
						keyAlg = CSSM_ALGID_ECDSA;
						sigAlg = CSSM_ALGID_SHA256WithECDSA;
						break;
					case '8':
						keyAlg = CSSM_ALGID_ECDSA;
						sigAlg = CSSM_ALGID_SHA384WithECDSA;
						break;
					case '9':
						keyAlg = CSSM_ALGID_ECDSA;
						sigAlg = CSSM_ALGID_SHA512WithECDSA;
						break;
					case '2':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_SHA224WithRSA;
						break;
					case '6':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_SHA256WithRSA;
						break;
					case '3':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_SHA384WithRSA;
						break;
					case '5':
						keyAlg = CSSM_ALGID_RSA;
						sigAlg = CSSM_ALGID_SHA512WithRSA;
						break;
					default:
						usage(argv);
				}
				break;
		    case 'k':
				keySizeInBits = atoi(&argv[arg][2]);
				break;
			default:
				usage(argv);
		}
	}
	
	/* connect to CL and CSP */
	clHand = clStartup();
	if(clHand == 0) {
		return 0;
	}
	cspHand = cspStartup();
	if(cspHand == 0) {
		return 0;
	}

	/* subsequent errors to abort: to detach */
	
	/* cook up an RSA key pair for the subject */
	crtn = cspGenKeyPair(cspHand,
		keyAlg,
		SUBJ_KEY_LABEL,
		strlen(SUBJ_KEY_LABEL),
		keySizeInBits,
		&subjPubKey,
		CSSM_FALSE,			// pubIsRef - should work both ways, but not yet
		CSSM_KEYUSE_VERIFY,
		CSSM_KEYBLOB_RAW_FORMAT_NONE,
		&subjPrivKey,
		CSSM_FALSE,			// privIsRef
		CSSM_KEYUSE_SIGN,
		CSSM_KEYBLOB_RAW_FORMAT_NONE,
		CSSM_FALSE);
	if(crtn) {
		errorCount++;
		goto abort;
	}
	if(writeBlobs) {
		writeFile(SUBJ_PRIV_KEY_FILE, subjPrivKey.KeyData.Data,
			subjPrivKey.KeyData.Length);
		printf("...wrote %lu bytes to %s\n", subjPrivKey.KeyData.Length,
			SUBJ_PRIV_KEY_FILE);
	}

	/* and the root */
	crtn = cspGenKeyPair(cspHand,
		keyAlg,
		ROOT_KEY_LABEL,
		strlen(ROOT_KEY_LABEL),
		keySizeInBits,
		&rootPubKey,
		CSSM_FALSE,			// pubIsRef - should work both ways, but not yet
		CSSM_KEYUSE_VERIFY,
		CSSM_KEYBLOB_RAW_FORMAT_NONE,
		&rootPrivKey,
		CSSM_FALSE,			// privIsRef
		CSSM_KEYUSE_SIGN,
		CSSM_KEYBLOB_RAW_FORMAT_NONE,
		CSSM_FALSE);
	if(crtn) {
		errorCount++;
		goto abort;
	}
	if(writeBlobs) {
		writeFile(ROOT_PRIV_KEY_FILE, rootPrivKey.KeyData.Data,
			rootPrivKey.KeyData.Length);
		printf("...wrote %lu bytes to %s\n", rootPrivKey.KeyData.Length,
			ROOT_PRIV_KEY_FILE);
	}

	if(compareKeyData(&rootPubKey, &subjPubKey)) {
	 	printf("**WARNING: Identical root and subj keys!\n");
	}

	/*
	 * Cook up various cert fields.
	 * First, the RDNs for subject and issuer. 
	 */
	rootName = CB_BuildX509Name(rootRdn, NUM_ROOT_NAMES);
	subjName = CB_BuildX509Name(subjRdn, NUM_SUBJ_NAMES);
	if((rootName == NULL) || (subjName == NULL)) {
		printf("CB_BuildX509Name failure");
		errorCount++;
		goto abort;
	}
	
	/* not before/after in generalized time format */
	notBefore = CB_BuildX509Time(0);
	notAfter  = CB_BuildX509Time(10000);

	/* A KeyUsage extension for both certs */
	exts[0].extnId = CSSMOID_KeyUsage;
	exts[0].critical = CSSM_FALSE;
	exts[0].format = CSSM_X509_DATAFORMAT_PARSED;
	keyUsage = CE_KU_DigitalSignature | CE_KU_KeyCertSign |
			   CE_KU_KeyEncipherment | CE_KU_DataEncipherment;
	exts[0].value.parsedValue = &keyUsage;
	exts[0].BERvalue.Data = NULL;
	exts[0].BERvalue.Length = 0;

	/* BasicConstraints for root only */
	exts[1].extnId = CSSMOID_BasicConstraints;
	exts[1].critical = CSSM_TRUE;
	exts[1].format = CSSM_X509_DATAFORMAT_PARSED;
	bc.cA = CSSM_TRUE;
	bc.pathLenConstraintPresent = CSSM_TRUE;
	bc.pathLenConstraint = 2;
	exts[1].value.parsedValue = &bc;
	exts[1].BERvalue.Data = NULL;
	exts[1].BERvalue.Length = 0;
	
	/* cook up root cert */
	printf("Creating root cert...\n");
	rawCert = CB_MakeCertTemplate(clHand,
		0x12345678,			// serial number
		rootName,
		rootName,
		notBefore,
		notAfter,
		&rootPubKey,
		sigAlg,
		NULL,				// subjUniqueId
		NULL,				// issuerUniqueId
		exts,				// extensions
		2);					// numExtensions

	if(rawCert == NULL) {
		errorCount++;
		goto abort;
	}
	if(writeBlobs) {
		writeFile(ROOT_TBS_FILE_NAME, rawCert->Data, rawCert->Length);
		printf("...wrote %lu bytes to %s\n", rawCert->Length, ROOT_TBS_FILE_NAME);
	}
	
	/* Self-sign; this is a root cert */
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
			sigAlg,
			NULL,			// AccessCred
			&rootPrivKey,
			&signContext);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext", crtn);
		errorCount++;
		goto abort;
	}
	signedRootCert.Data = NULL;
	signedRootCert.Length = 0;
	crtn = CSSM_CL_CertSign(clHand,
		signContext,
		rawCert,			// CertToBeSigned
		NULL,				// SignScope
		0,					// ScopeSize,
		&signedRootCert);
	if(crtn) {
		printError("CSSM_CL_CertSign", crtn);
		errorCount++;
		goto abort;
	}
	crtn = CSSM_DeleteContext(signContext);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		errorCount++;
		goto abort;
	}
	appFreeCssmData(rawCert, CSSM_TRUE);
	if(writeBlobs) {
		writeFile(ROOT_CERT_FILE_NAME, signedRootCert.Data, signedRootCert.Length);
		printf("...wrote %lu bytes to %s\n", signedRootCert.Length, 
			ROOT_CERT_FILE_NAME);
	}

	/* now a subject cert signed by the root cert */
	printf("Creating subject cert...\n");
	rawCert = CB_MakeCertTemplate(clHand,
		0x8765,				// serial number
		rootName,
		subjName,
		notBefore,
		notAfter,
		&subjPubKey,
		sigAlg,
		NULL,				// subjUniqueId
		NULL,				// issuerUniqueId
		exts,				// extensions
		1);					// numExtensions
	if(rawCert == NULL) {
		errorCount++;
		goto abort;
	}
	if(writeBlobs) {
		writeFile(SUBJ_TBS_FILE_NAME, rawCert->Data, rawCert->Length);
		printf("...wrote %lu bytes to %s\n", rawCert->Length, SUBJ_TBS_FILE_NAME);
	}

	/* sign by root */
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
			sigAlg,
			NULL,			// AccessCred
			&rootPrivKey,
			&signContext);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext", crtn);
		errorCount++;
		goto abort;
	}
	signedSubjCert.Data = NULL;
	signedSubjCert.Length = 0;
	crtn = CSSM_CL_CertSign(clHand,
		signContext,
		rawCert,			// CertToBeSigned
		NULL,				// SignScope
		0,					// ScopeSize,
		&signedSubjCert);
	if(crtn) {
		printError("CSSM_CL_CertSign", crtn);
		errorCount++;
		goto abort;
	}
	crtn = CSSM_DeleteContext(signContext);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		errorCount++;
		goto abort;
	}
	appFreeCssmData(rawCert, CSSM_TRUE);
	if(writeBlobs) {
		writeFile(SUBJ_CERT_FILE_NAME, signedSubjCert.Data, signedSubjCert.Length);
		printf("...wrote %lu bytes to %s\n", signedSubjCert.Length, 
			SUBJ_CERT_FILE_NAME);
	}

	/* Free the stuff we allocd to get here */
	CB_FreeX509Name(rootName);
	CB_FreeX509Name(subjName);
	CB_FreeX509Time(notBefore);
	CB_FreeX509Time(notAfter);

	/*
	 * Extract public keys from the two certs, verify.
	 */
	crtn = CSSM_CL_CertGetKeyInfo(clHand, &signedSubjCert, &extractSubjKey);
	if(crtn) {
		printError("CSSM_CL_CertGetKeyInfo", crtn);
	}
	else {
		/* compare key data - header is different.
		 * Known header differences:
		 *  -- CspID - CSSM_CL_CertGetKeyInfo returns a key with NULL for
		 *     this field
		 * --  Format. rootPubKey      : 6 (CSSM_KEYBLOB_RAW_FORMAT_BSAFE)
		 *             extractRootKey  : 1 (CSSM_KEYBLOB_RAW_FORMAT_PKCS1)
		 * --  KeyAttr. rootPubKey     : 0x20 (CSSM_KEYATTR_EXTRACTABLE)
		 *              extractRootKey : 0x0
		 */
		if(!compareKeyData(extractSubjKey, &subjPubKey)) {
			printf("***CSSM_CL_CertGetKeyInfo(signedSubjCert) returned bad key data\n");
		}
		if(extractSubjKey->KeyHeader.LogicalKeySizeInBits !=
				subjPubKey.KeyHeader.LogicalKeySizeInBits) {
			printf("***EffectiveKeySizeInBits mismatch: extract %u subj %u\n",
				(unsigned)extractSubjKey->KeyHeader.LogicalKeySizeInBits,
				(unsigned)subjPubKey.KeyHeader.LogicalKeySizeInBits);
		}
	}
	crtn = CSSM_CL_CertGetKeyInfo(clHand, &signedRootCert, &extractRootKey);
	if(crtn) {
		printError("CSSM_CL_CertGetKeyInfo", crtn);
	}
	else {
		if(!compareKeyData(extractRootKey, &rootPubKey)) {
			printf("***CSSM_CL_CertGetKeyInfo(signedRootCert) returned bad key data\n");
		}
	}

	/*
	 * Verify:
	 */
	printf("Verifying certificates...\n");
	
	/*
	 *  Verify root cert by root pub key, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedRootCert,
			NULL,
			&rootPubKey,
			sigAlg,
			CSSM_OK,
			"Verify(root by root key)")) {
		errorCount++;
		/* continue */
	}
	
	/*
	 *  Verify root cert by root cert, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedRootCert,
			&signedRootCert,
			NULL,
			CSSM_ALGID_NONE,			// sigAlg not used here
			CSSM_OK,
			"Verify(root by root cert)")) {
		errorCount++;
		/* continue */
	}


	/*
	 *  Verify subject cert by root pub key, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			NULL,
			&rootPubKey,
			sigAlg,
			CSSM_OK,
			"Verify(subj by root key)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify subject cert by root cert, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			&signedRootCert,
			NULL,
			CSSM_ALGID_NONE,			// sigAlg not used here
			CSSM_OK,
			"Verify(subj by root cert)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify subject cert by root cert AND key, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			&signedRootCert,
			&rootPubKey,
			sigAlg,
			CSSM_OK,
			"Verify(subj by root cert and key)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify subject cert by extracted root pub key, should succeed.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			NULL,
			extractRootKey,
			sigAlg,
			CSSM_OK,
			"Verify(subj by extracted root key)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify subject cert by subject pub key, should fail.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			NULL,
			&subjPubKey,
			sigAlg,
			CSSMERR_CL_VERIFICATION_FAILURE,
			"Verify(subj by subj key)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify subject cert by subject cert, should fail.
	 */
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			&signedSubjCert,
			NULL,
			CSSM_ALGID_NONE,			// sigAlg not used here
			CSSMERR_CL_VERIFICATION_FAILURE,
			"Verify(subj by subj cert)")) {
		errorCount++;
		/* continue */
	}

	/*
	 *  Verify erroneous subject cert by root pub key, should fail.
	 */
	badByte = genRand(1, signedSubjCert.Length - 1);
	signedSubjCert.Data[badByte] ^= 0x55;
	if(verifyCert(clHand,
			cspHand,
			&signedSubjCert,
			NULL,
			&rootPubKey,
			sigAlg,
			CSSMERR_CL_VERIFICATION_FAILURE,
			"Verify(bad subj by root key)")) {
		errorCount++;
		/* continue */
	}


	/* free/delete certs and keys */
	appFreeCssmData(&signedSubjCert, CSSM_FALSE);
	appFreeCssmData(&signedRootCert, CSSM_FALSE);

	cspFreeKey(cspHand, &rootPubKey);
	cspFreeKey(cspHand, &subjPubKey);

	/* These don't work because CSSM_CL_CertGetKeyInfo() gives keys with
	 * a bogus GUID. This may be a problem with the Apple CSP...
	 *
	cspFreeKey(cspHand, extractRootKey);
	cspFreeKey(cspHand, extractSubjKey);
	 *
	 * do it this way instead...*/
	CSSM_FREE(extractRootKey->KeyData.Data);
	CSSM_FREE(extractSubjKey->KeyData.Data);

	/* need to do this regardless...*/
	CSSM_FREE(extractRootKey);
	CSSM_FREE(extractSubjKey);

abort:
	if(cspHand != 0) {
		CSSM_ModuleDetach(cspHand);
	}

	if(errorCount) {
		printf("Signer/Subject test failed with %d errors\n", errorCount);
	}
	else {
		printf("Signer/Subject test succeeded\n");
	}
	return 0;
}
int CommonCryptoSymRegression(int argc, char *const *argv)
{
	unsigned			loop;
	uint8_t				*ptext;
	size_t				ptextLen;
	bool				stagedEncr = false;
	bool				stagedDecr = false;
	bool				doPadding;
	bool				doCbc = false;
	bool				nullIV;
	const char			*algStr;
	CCAlgorithm			encrAlg;	
	int					i;
	int					currAlg;		// ALG_xxx
	uint32_t				minKeySizeInBytes;
	uint32_t				maxKeySizeInBytes;
	uint32_t				keySizeInBytes = 0;
	int					rtn = 0;
	uint32_t				blockSize;		// for noPadding case
	size_t				ctxSize;		// always set per alg
	size_t				ctxSizeUsed;	// passed to doTest
	bool				askOutSize;		// inquire output size each op
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	SymAlg		minAlg = ALG_FIRST;
	SymAlg		maxAlg = ALG_LAST;
	unsigned	loops = LOOPS_DEF;
	bool		verbose = false;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = true;
	unsigned	pauseInterval = 0;
	bool		paddingSpec = false;		// true: user calls doPadding, const
	bool		cbcSpec = false;			// ditto for doCbc
	bool		stagedSpec = false;			// ditto for stagedEncr and stagedDecr
	bool		inPlace = false;			// en/decrypt in place for ECB
	bool		allocCtxSpec = false;		// use allocCtx
	bool		allocCtx = false;			// allocate context ourself

	plan_tests(kTestTestCount);
	

	ptext = (uint8_t *)malloc(maxPtextSize);
	if(ptext == NULL) {
		diag("Insufficient heap space\n");
		exit(1);
	}
	/* ptext length set in test loop */
	
	if(!quiet) diag("Starting ccSymTest; args: ");
	for(i=1; i<argc; i++) {
		if(!quiet) diag("%s ", argv[i]);
	}
	if(!quiet) diag("\n");
	
	if(pauseInterval) {
		fpurge(stdin);
		diag("Top of test; hit CR to proceed: ");
		getchar();
	}

	for(currAlg=minAlg; currAlg<=maxAlg; currAlg++) {
		switch(currAlg) {
			case ALG_DES:
				encrAlg = kCCAlgorithmDES;
				blockSize = kCCBlockSizeDES;
				minKeySizeInBytes = kCCKeySizeDES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeDES;
				algStr = "DES";
                diag("Running DES Tests");
				break;
			case ALG_3DES:
				encrAlg = kCCAlgorithm3DES;
				blockSize = kCCBlockSize3DES;
				minKeySizeInBytes = kCCKeySize3DES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSize3DES;
				
				algStr = "3DES";
                diag("Running 3DES Tests");
				break;
			case ALG_AES_128:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES128;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES128";
                diag("Running AES (128 bit key) Tests");
				break;
			case ALG_AES_192:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES192;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES192";
                diag("Running AES (192 bit key) Tests");
				break;
			case ALG_AES_256:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES256;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES256";
                diag("Running AES (256 bit key) Tests");
				break;
			case ALG_CAST:
				encrAlg = kCCAlgorithmCAST;
				blockSize = kCCBlockSizeCAST;
				minKeySizeInBytes = kCCKeySizeMinCAST;
				maxKeySizeInBytes = kCCKeySizeMaxCAST;
				ctxSize = kCCContextSizeCAST;
				algStr = "CAST";
                diag("Running CAST Tests");
				break;
			case ALG_RC4:
				encrAlg = kCCAlgorithmRC4;
				blockSize = 0;
				minKeySizeInBytes = kCCKeySizeMinRC4;
				maxKeySizeInBytes = kCCKeySizeMaxRC4;
				ctxSize = kCCContextSizeRC4;
				algStr = "RC4";
                diag("Running RC4 Tests");
				break;
			default:
				diag("***BRRZAP!\n");
				exit(1);
		}
		if(!quiet || verbose) {
			diag("Testing alg %s\n", algStr);
		}
		for(loop=1; ; loop++) {
			ptextLen = (size_t) genRand((unsigned int) minPtextSize, (unsigned int) maxPtextSize);
			appGetRandomBytes(ptext, ptextLen);
			
			/* per-loop settings */
			if(!keySizeSpec) {
				if(minKeySizeInBytes == maxKeySizeInBytes) {
					keySizeInBytes = minKeySizeInBytes;
				}
				else {
					keySizeInBytes = genRand(minKeySizeInBytes, maxKeySizeInBytes);
				}
			}
			if(blockSize == 0) {
				/* stream cipher */
				doCbc = false;
				doPadding = false;
			}
			else {
				if(!cbcSpec) {
					doCbc = isBitSet(0, loop);
				}
				if(!paddingSpec) {
					doPadding = isBitSet(1, loop);
				}
			}
			if(!doPadding && (blockSize != 0)) {
				/* align plaintext */
				ptextLen = (ptextLen / blockSize) * blockSize;
				if(ptextLen == 0) {
					ptextLen = blockSize;
				}
			}
			if(!stagedSpec) {
				stagedEncr = isBitSet(2, loop);
				stagedDecr = isBitSet(3, loop);
			}
			if(doCbc) {
				nullIV = isBitSet(4, loop);
			}
			else {
				nullIV = false;
			}
			inPlace = isBitSet(5, loop);
			if(allocCtxSpec) {
				ctxSizeUsed = allocCtx ? ctxSize : 0;
			}
			else if(isBitSet(6, loop)) {
				ctxSizeUsed = ctxSize;
			}
			else {
				ctxSizeUsed = 0;
			}
			askOutSize = isBitSet(7, loop);
			if(!quiet) {
			   	if(verbose || ((loop % LOOP_NOTIFY) == 0)) {
					diag("..loop %3d ptextLen %lu keyLen %d cbc=%d padding=%d stagedEncr=%d "
							"stagedDecr=%d\n",
						loop, (unsigned long)ptextLen, (int)keySizeInBytes, 
						(int)doCbc, (int)doPadding,
					 	(int)stagedEncr, (int)stagedDecr);
					diag("           nullIV %d inPlace %d ctxSize %d askOutSize %d\n",
						(int)nullIV, (int)inPlace, (int)ctxSizeUsed, (int)askOutSize);
				}
			}
			
			if(doTest(ptext, ptextLen,
					encrAlg, doCbc, doPadding, nullIV,
					keySizeInBytes,
					stagedEncr,	stagedDecr, inPlace, ctxSizeUsed, askOutSize,
					quiet)) {
				rtn = 1;
				break;
			}
			if(pauseInterval && ((loop % pauseInterval) == 0)) {
				char c;
				fpurge(stdin);
				diag("Hit CR to proceed, q to abort: ");
				c = getchar();
				if(c == 'q') {
					goto testDone;
				}
			}
			if(loops && (loop == loops)) {
				break;
			}
		}	/* main loop */
		if(rtn) {
			break;
		}
		
	}	/* for algs */
	
testDone:

    ok(rtn == 0, "ccSymTest");

	if(pauseInterval) {
		fpurge(stdin);
		diag("ModuleDetach/Unload complete; hit CR to exit: ");
		getchar();
	}
	if((rtn == 0) && !quiet) {
		diag("%s test complete\n", argv[0]);
	}
	free(ptext);
	return rtn;
}
示例#22
0
    DEVICE void operator() (
        vec3f*                                          aRayOrg,
        vec3f*                                          aRayDir,
        const tControlStructure&                        aGridParameters,
        const tStorageStructure&                        aScene,
        const tMaterialStorageStructure&                aMaterialStorage,
        const tLightSource&                             aLightSource,
        vec3f&                                          oRadiance,
        uint*                                           aSharedMem,
        int                                             aSeed = 0)
    {
        //////////////////////////////////////////////////////////////////////////
        //Traversal initialization
        t_Traverser     traverser;
        t_State         state;

        //////////////////////////////////////////////////////////////////////////
        //Integration Initialization
        CosineHemisphereSampler genDir;
        t_RNG genRand(  12872141u + aSeed * 426997u + aSeed,
            2611909u + aSeed * 14910827u + globalThreadId1D(1887143u) + aSeed,
            1010567u + aSeed * 2757577u + globalThreadId1D(45751u) + aSeed,
            416191069u);
        //t_RNG genRand(globalThreadId1D() + RESX * RESY * (*aImageId));

#ifndef GATHERSTATISTICS
        oRadiance = vec3f::rep(1.f);
#else
        oRadiance.x = 1.f; //number of rays traced
        oRadiance.y = 0.f; //number of rays active after path termination
        oRadiance.z = 0.f; //number of intersection tests
#endif

        //////////////////////////////////////////////////////////////////////////
        //Integration loop
        float rayT   = FLT_MAX;
        uint  bestHit;

        //NOTE: Device capability 1.2 or higher required
        while (ANY(rayT > 0.f))//Termination criteria
        {
#ifndef GATHERSTATISTICS
            traverser.traverse(aRayOrg, aRayDir, rayT, bestHit, state,
                aGridParameters, aScene, aSharedMem);
#else
            traverser.traverse(aRayOrg, aRayDir, rayT, bestHit, state,
                aGridParameters, aScene, aSharedMem, oRadiance);

            oRadiance.y += 1.f;
#endif
            if ((rayT < FLT_MAX) && (rayT > 0.f))
            {
                bestHit = aScene.indices[bestHit];
                vec3f normal = aScene(bestHit).vertices[0];
                //register reuse: state.tMax should be edge1
                state.tMax = aScene(bestHit).vertices[1];
                //register reuse: state.cellId should be edge2
                state.cellId = aScene(bestHit).vertices[2];

                state.tMax = state.tMax - normal;
                state.cellId = state.cellId - normal;

                normal = ~(state.tMax % state.cellId);
                state.tMax = ~state.tMax;
                state.cellId = normal % state.tMax;

                //vec3f::getLocalCoordinates(normal, state.tMax, state.cellId);

                if (normal.dot(aRayDir[threadId1D()]) > 0.f)
                {
                    normal = -normal;
                }

                float4 diffReflectance = aMaterialStorage.getDiffuseReflectance(
                    aScene.getMaterialId(bestHit));
                //float albedo = (diffReflectance.x * 0.222f +
                //    diffReflectance.y * 0.7067f +
                //    diffReflectance.z * 0.0713f);
                float albedo = 0.5f;
                float rnum = genRand();

                if( rnum < albedo )
                {
#ifndef GATHERSTATISTICS
                    oRadiance = oRadiance / albedo;
                    //pi is to account for cosine weighted hemisphere sampling
                    oRadiance.x = oRadiance.x * diffReflectance.x * M_PI;
                    oRadiance.y = oRadiance.y * diffReflectance.y * M_PI;
                    oRadiance.z = oRadiance.z * diffReflectance.z * M_PI;
#else
                    oRadiance.x += 1.f;
#endif
                    //generate new ray
                    aRayOrg[threadId1D()] = aRayOrg[threadId1D()]
                    + rayT * aRayDir[threadId1D()] + normal *  0.001f;

                    vec3f randDir = genDir(genRand(), genRand());
                    aRayDir[threadId1D()] = state.tMax * randDir.x +
                        state.cellId * randDir.y + normal * randDir.z;

                    rayT = FLT_MAX;
                }
                else
                {
                    //terminate path and save last hit-point
                    aRayDir[threadId1D()] = aRayOrg[threadId1D()]
                    + (rayT - 0.001f) * aRayDir[threadId1D()];
#ifndef GATHERSTATISTICS
                    oRadiance.x = oRadiance.x * diffReflectance.x / (1 - albedo);
                    oRadiance.y = oRadiance.y * diffReflectance.y / (1 - albedo);
                    oRadiance.z = oRadiance.z * diffReflectance.z / (1 - albedo);
#endif
                    //save cos between normal and incoming direction
                    aRayOrg[threadId1D()] = normal;

                    rayT = -1.f;
                }
            }
            else if (rayT > 0.f)
            {
#ifndef GATHERSTATISTICS
                //terminate path
                oRadiance.x = oRadiance.x * BACKGROUND_R;
                oRadiance.y = oRadiance.y * BACKGROUND_G;
                oRadiance.z = oRadiance.z * BACKGROUND_B;
#endif
                rayT = -2.f;
            }//end if (rayT < FLT_MAX) && (rayT > 0.f)
        }
        //end integration loop
        //////////////////////////////////////////////////////////////////////////
        //trace ray to light source

        //register reuse state.cellId.x should be vec3f surfaceNormal
        state.cellId = aRayOrg[threadId1D()];

        aRayOrg[threadId1D()] = aLightSource.getPoint(genRand(), genRand());
        aRayDir[threadId1D()] = aRayDir[threadId1D()] - aRayOrg[threadId1D()];

        if (rayT > -2.f)
        {
            rayT = FLT_MAX;
#ifndef GATHERSTATISTICS
            oRadiance = oRadiance * max(0.f, -state.cellId.dot(~aRayDir[threadId1D()]));
#endif
        }

#ifndef GATHERSTATISTICS
        traverser.traverseShadowRay(aRayOrg, aRayDir, rayT, bestHit, state,
            aGridParameters, aScene, aSharedMem);

        if (rayT >= 0.9999f)
        {
            float attenuation = aRayDir[threadId1D()].dot(aRayDir[threadId1D()]);
            oRadiance = oRadiance *
                aLightSource.intensity *
                dcLightSource.getArea() *
                max(0.f, aLightSource.normal.dot(~aRayDir[threadId1D()])) /
                attenuation;
            //oRadiance = oRadiance / aRayDir[threadId1D()].len() / aRayDir[threadId1D()].len() * max(0.f, aLightSource.normal.dot(aRayDir[threadId1D()]));


        }
        else if (rayT > -2.f)
        {
            //occluded
            oRadiance = vec3f::rep(0.f);
        }
#else
        traverser.traverseShadowRay(aRayOrg, aRayDir, rayT, bestHit, state,
             aGridParameters, aScene, aSharedMem, oRadiance);
        
        oRadiance.x += 1.f;
        oRadiance.y += 1.f;
#endif

    }
示例#23
0
    DEVICE void operator() (
        vec3f*                                          aRayOrg,
        vec3f*                                          aRayDir,
        const tControlStructure&                        aGridParameters,
        const tStorageStructure&                        aScene,
        const tMaterialStorageStructure&                aMaterialStorage,
        const tLightSource&                             aLightSource,
        vec3f&                                          oRadiance,
        uint*                                           aSharedMem,
        int                                             aSeed = 0)
    {
        //////////////////////////////////////////////////////////////////////////
        //Traversal initialization
        t_Traverser     traverser;
        t_State         state;

        //////////////////////////////////////////////////////////////////////////
        //Integration Initialization
        CosineHemisphereSampler genDir;
        t_RNG genRand(  1236789u + globalThreadId1D(),
                        369u + globalThreadId1D(aSeed),
                        351288629u + globalThreadId1D(aSeed),
                        416191069u );
        //t_RNG genRand(globalThreadId1D() + RESX * RESY * (*aImageId));

#ifndef GATHERSTATISTICS
        oRadiance = vec3f::rep(1.f);
#else
        oRadiance.x = 1.f; //number of rays traced
        oRadiance.y = 0.f; //number of rays active after path termination
        oRadiance.z = 0.f; //number of intersection tests
#endif

        //////////////////////////////////////////////////////////////////////////
        //Integration loop
        float rayT   = FLT_MAX;
        uint  bestHit;
        uint bounceCount = 0u;

        //NOTE: Device capability 1.2 or higher required
        while (ANY(rayT > 0.f))//Termination criteria
        {
#ifndef GATHERSTATISTICS
            traverser.traverse(aRayOrg, aRayDir, rayT, bestHit, state,
                               aGridParameters, aScene, aSharedMem);
#else
            traverser.traverse(aRayOrg, aRayDir, rayT, bestHit, state,
                               aGridParameters, aScene, aSharedMem, oRadiance);

            oRadiance.y += 1.f;
#endif
            if ((rayT < FLT_MAX) && (rayT > 0.f))
            {
                bestHit = aScene.indices[bestHit];
                vec3f normal = aScene(bestHit).vertices[0];
                //register reuse: state.tMax should be edge1
                state.tMax = aScene(bestHit).vertices[1];
                //register reuse: state.cellId should be edge2
                state.cellId = aScene(bestHit).vertices[2];

                state.tMax = state.tMax - normal;
                state.cellId = state.cellId - normal;

                normal = ~(state.tMax % state.cellId);
                state.tMax = ~state.tMax;
                state.cellId = normal % state.tMax;

                if (normal.dot(aRayDir[threadId1D()]) > 0.f)
                {
                    normal = -normal;
                }

                float4 diffReflectance = aMaterialStorage.getDiffuseReflectance(
                                             aScene.getMaterialId(bestHit));

                if( bounceCount < 1 )
                {

                    ++bounceCount;
#ifndef GATHERSTATISTICS

                    oRadiance.x = oRadiance.x * diffReflectance.x;
                    oRadiance.y = oRadiance.y * diffReflectance.y;
                    oRadiance.z = oRadiance.z * diffReflectance.z;
#else
                    oRadiance.x += 1.f;
#endif
                    //generate new ray
                    aRayOrg[threadId1D()] = aRayOrg[threadId1D()]
                                            + rayT * aRayDir[threadId1D()] + normal * EPS;

                    vec3f randDir = genDir(genRand(), genRand());
                    aRayDir[threadId1D()] = state.tMax * randDir.x +
                                            state.cellId * randDir.y + normal * randDir.z;

                    rayT = FLT_MAX;
                }
                else
                {
                    //terminate path and save last hit-point
                    aRayDir[threadId1D()] = aRayOrg[threadId1D()]
                                            + (rayT - 0.0001f) * aRayDir[threadId1D()];
#ifndef GATHERSTATISTICS
                    oRadiance.x = oRadiance.x * diffReflectance.x;
                    oRadiance.y = oRadiance.y * diffReflectance.y;
                    oRadiance.z = oRadiance.z * diffReflectance.z;
#endif
                    //save normal for later
                    aRayOrg[threadId1D()] = normal;

                    rayT = -1.f;
                }
            }
            else if (rayT > 0.f)
            {
#ifndef GATHERSTATISTICS
                //terminate path
                oRadiance.x = oRadiance.x * BACKGROUND_R;
                oRadiance.y = oRadiance.y * BACKGROUND_G;
                oRadiance.z = oRadiance.z * BACKGROUND_B;
#endif
                rayT = -2.f;
            }//end if (rayT < FLT_MAX) && (rayT > 0.f)
        }
        //end integration loop
        //////////////////////////////////////////////////////////////////////////
        //trace ray to light source

        //register reuse state.cellId should be vec3f surfaceNormal
        state.cellId = aRayOrg[threadId1D()];

        aRayOrg[threadId1D()] = aLightSource.getPoint(genRand(), genRand());
        aRayDir[threadId1D()] = aRayDir[threadId1D()] - aRayOrg[threadId1D()];

        if (rayT > -2.f)
        {
            rayT = FLT_MAX;
#ifndef GATHERSTATISTICS
            oRadiance = oRadiance * fabsf(state.cellId.dot(~aRayDir[threadId1D()]));
#endif
        }

#ifndef GATHERSTATISTICS
        traverser.traverseShadowRay(aRayOrg, aRayDir, rayT, bestHit, state,
                                    aGridParameters, aScene, aSharedMem);

        if (rayT >= 0.9999f)
        {
            oRadiance = oRadiance * aLightSource.intensity;
            oRadiance = oRadiance * max(0.f, aLightSource.normal.dot(~aRayDir[threadId1D()]));
        }
        else if (rayT > -2.f)
        {
            //occluded
            oRadiance = vec3f::rep(0.f);
        }
#else
        traverser.traverseShadowRay(aRayOrg, aRayDir, rayT, bestHit, state,
                                    aGridParameters, aScene, aSharedMem, oRadiance);

        oRadiance.x += 1.f;
        oRadiance.y += 1.f;
#endif
    }