Esempio n. 1
0
void ts::client::Resource_downloader::request_car(const resources::Car_identifier& car_identifier)
{
    auto key = generate_key();    
    auto& download_info = download_map_[key];

    download_info.target_directory_ = "download";
    download_info.full_target_directory_ = resource_store_->car_store().root_directory();
    download_info.full_target_directory_ += "/";
    download_info.full_target_directory_ += download_info.target_directory_;    

    message_buffer_.message = downloads::make_car_download_request(key, car_identifier);
    message_center_->dispatch_message(message_buffer_);

    cup::Chat_message chat_message;
    chat_message.append("Trying to download car ", sf::Color(255, 150, 0));
    chat_message.append(car_identifier.car_name, sf::Color(255, 220, 50));
    chat_message.append("...", sf::Color(255, 150, 0));

    message_buffer_.message = cup::make_chatbox_output_message(chat_message);
    message_center_->handle_message(message_buffer_);
}
Esempio n. 2
0
 Hash* Hash::Hash_Insert(int x,int y,Node* s){
  if ((x<(-1*costante))||(y<(-1*costante))){
   Hash* tmp=new Hash(dimensione,2*costante);
   tmp->Copy(a,dimensione);
   tmp=tmp->Hash_Insert(x,y,s);
   return tmp;}
  else{
   int key=generate_key(x,y);
   key=key%dimensione;
   if (a[key].is_in){
    key=scansione_secondaria(key,x,y);}
   a[key].is_in=true;
   a[key].x=x;
   a[key].y=y;
   a[key].node=s;
   dim_attuale++;
   if (dim_attuale>=(dimensione/3)){
    Hash* tmp=new Hash(2*dimensione,costante);
    tmp->Copy(a,dimensione);
    return tmp;}
   else {
  return this;}}}
Esempio n. 3
0
int main() {
    
    char inputStr[SIZE];
    char encrypt[SIZE];
    char decrypt[SIZE];
    int key[SIZE];
    int i, size;
    
    printf( "Enter a string to encrypt: " );
    scanf( " %[^\n]s", inputStr ); //to scan a sentence from the keyboard
    
    size = strlen( inputStr ); // strlen is a library function defined in
                                // string.h to find the length of a string
    
    printf( "\nGenerating key...\n" );
    generate_key( key, size ); //should randomly generate unique keys
    
    /** Print keys **/
    printf("Key = ");
	for(i = 0; i < size; i++){
		printf("%d ", key[i]);
	}
	printf("\n");
    
    printf( "Encrypting string...\n" );
    encrypt_data( encrypt, inputStr, key, size ); //Encrypt a string
	
    /** Print encrypted string **/
	printf("Encrypted string: \"%s\"\n", encrypt);
    
    printf( "Decrypting string...\n" );
    decrypt_data( decrypt, encrypt, key, size ); //Decrypt a string
	
    /** Print decrypted string **/
	printf("Decrypted string: \"%s\"\n", decrypt);
    
    return 0;
}
Esempio n. 4
0
int main(int argc, char* argv[]) {
	// The identifier for the shared memory segment
	int segment_id;

	// The *actual* shared memory, that this and other
	// processes can read and write to as if it were
	// any other plain old memory
	char* shared_memory;

	// Key for the memory segment
	key_t segment_key;

	// Fetch command-line arguments
	struct Arguments args;
	parse_arguments(&args, argc, argv);

	segment_key = generate_key("shm");

	/*
		The call that actually allocates the shared memory segment.
		Arguments:
			1. The shared memory key. This must be unique across the OS.
			2. The number of bytes to allocate. This will be rounded up to the OS'
				 pages size for alignment purposes.
			3. The creation flags and permission bits, where:
				 - IPC_CREAT means that a new segment is to be created
				 - IPC_EXCL means that the call will fail if
					 the segment-key is already taken (removed)
				 - 0666 means read + write permission for user, group and world.
		When the shared memory key already exists, this call will fail. To see
		which keys are currently in use, and to remove a certain segment, you
		can use the following shell commands:
			- Use `ipcs -m` to show shared memory segments and their IDs
			- Use `ipcrm -m <segment_id>` to remove/deallocate a shared memory segment
	*/
	segment_id = shmget(segment_key, 1 + args.size, IPC_CREAT | 0666);

	if (segment_id < 0) {
		throw("Error allocating segment");
	}

	/*
		Once the shared memory segment has been created, it must be
		attached to the address space of each process that wishes to
		use it. For this, we pass:
			1. The segment ID returned by shmget
			2. A pointer at which to attach the shared memory segment. This
				 address must be page-aligned. If you simply pass NULL, the OS
				 will find a suitable region to attach the segment.
			3. Flags, such as:
				 - SHM_RND: round the second argument (the address at which to
					 attach) down to a multiple of the page size. If you don't
					 pass this flag but specify a non-null address as second argument
					 you must ensure page-alignment yourself.
				 - SHM_RDONLY: attach for reading only (independent of access bits)
		shmat will return a pointer to the address space at which it attached the
		shared memory. Children processes created with fork() inherit this segment.
	*/
	shared_memory = (char*)shmat(segment_id, NULL, 0);

	if (shared_memory == (char*)-1) {
		throw("Error attaching segment");
	}

	communicate(shared_memory, &args);

	cleanup(segment_id, shared_memory);

	return EXIT_SUCCESS;
}
void CurvedSalsaDialog::slot_generateKey( const QString &key )
{
	uint8_t pubKey[32];
	generate_key( pubKey, key.toStdString()  );
	pubKeyLine->setText( b64encode(pubKey).c_str() );
}
Esempio n. 6
0
/*
 * Main function
 */
int main (int argc, char **argv)
{
	FILE *fp = NULL;

	if(argc < 2)
	{
		fprintf(stderr, "Please specify the programs keygen/crypt/invkey/histo/solve and try again\n");
	}
	else
	{
		if(strcmp(argv[1], "keygen") == 0) //Processing keygen command
		{
			if (argc != 4)
			{
				fprintf(stderr,"Please double check your arguments. The keygen function expects to have exactly 2 arguments -p=pphrase and -t=period\n");
			}
			else
			{
				char *pphrase = "";
				int period = 0;
				//Use for loop to go through all arguments
				for (int index = argc-1; index > 1; index--)
				{
					//find '=' at each argument
					char *val = strchr(argv[index], '=');
					if (val == NULL)
					{
						//malformed command
						fprintf(stderr,"Please double check your arguments. The keygen function expects to have exactly 2 arguments in following format: -p=pphrase and -t=period\n");
						exit(1);
					}
					else
					{
						char *key = argv[index];
						*val = '\0'; //replace '=' by NULL character to separate key and val pointers
						val++;
						//compare to see which key is it
						if (strncmp(key, "-p", 2) == 0)
						{
							//passphrase
							pphrase = val;
						}
						else if(strncmp(key, "-t", 2) == 0)
						{
							//key length
							period = atoi(val);
						}
						else
						{
							//malformed command
							fprintf(stderr,"Please double check your arguments. The keygen function expects to have exactly 2 arguments in following format: -p=pphrase and -t=period\n");
							exit(1);
						}
					}
				}
				//Check if we have value for pphrase and len before calling keygen function
				if (strncmp(pphrase, "",1) != 0 && *pphrase != '\0' && period > 0)
				{
					//call keygen function
					generate_key(pphrase, period);
				}
				else
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The keygen function expects to have exactly 2 arguments in following format: -p=pphrase and -t=period\n");
					exit(1);
				}
			}
		}
		else if(strcmp(argv[1], "crypt") == 0) //processing crypt command
		{
			if (argc < 3 || argc > 4)
			{
				fprintf (stderr, "Please double check your arguments. The crypt function expects to have at least 1 argument in following format: -k=keyfile and an optional file to encrypt/decrypt\n");
				exit(1);
			}
			else if (argc == 3)
			{
				//Check if there is a -k argument. If so, read the file from stdin
				char *keyfile = "";
				char *checkArgs = "";
				//find '=' at argument
				char *val = strchr(argv[2], '=');
				if (val == NULL)
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The crypt function expects to have at least 1 argument in following format: -k=keyfile and an optional file to encrypt/decrypt\n");
					exit(1);
				}
				else
				{
					checkArgs = argv[2];
					if (strncmp(checkArgs, "-k", 2) != 0)
					{
						//malformed command
						fprintf(stderr,"Please double check your arguments. The crypt function expects to have at least 1 argument in following format: -k=keyfile and an optional file to encrypt/decrypt\n");
						exit(1);
					}
					else
					{
						*val = '\0';
						val++;
						keyfile = val;
						//Now try to open the key file, if open successfully, continue. Else, exit with error
						fp = fopen(keyfile,"r");
						if (fp == NULL)
						{
							fprintf (stderr, "Keyfile %s does not exist\n", keyfile);
							exit(1);
						}
						//Now call crypt function with fp to read keyfile and stdin to read file to be encrypted/decrypted
						crypt(fp, keyfile, stdin);
						fclose(fp);
					}
				}
			}
			else if (argc == 4)
			{
				char *keyfile = "";
				char *file = "";
				char *checkArgs = "";
				FILE *fp2;
				//Use for loop to go through all arguments
				for (int index = argc-1; index > 1; index--)
				{
					//find '=' at each argument
					char *val = strchr(argv[index], '=');
					if (val == NULL)
					{
						//This must be the file name. Let try to open this argument to see if file exists
						file = argv[index];
					}
					else
					{
						checkArgs = argv[index];
						*val = '\0'; //replace '=' by NULL character to separate key and val pointers
						val++;
						//compare to see which key is it
						if (strncmp(checkArgs, "-k", 2) == 0)
						{
							//keyfile
							keyfile = val;
						}
						else
						{
							//malformed command
							fprintf(stderr,"Please double check your arguments. The crypt function expects to have at least 1 argument in following format: -k=keyfile and an optional file to encrypt/decrypt\n");
							exit(1);
						}
					}
				}
				if (strcmp(file,"") == 0 || strcmp(keyfile,"") == 0)
				{
					fprintf(stderr, "Either keyfile or file is missing. Please double check your arguments\n");
					exit(1);
				}
				//Now try to open both file and keyfile to see both exist
				fp = fopen(keyfile, "r");
				if (fp == NULL)
				{
					fprintf (stderr, "Keyfile %s does not exist\n", keyfile);
					exit(1);
				}

				fp2 = fopen(file, "r");
				if (fp2 == NULL)
				{
					fprintf (stderr, "File %s does not exist\n", file);
					//close fp
					fclose(fp);
					exit(1);
				}
				//Call crypt function with fp for keyfile and fp2 for file to be encrypted/decrypted
				crypt(fp, keyfile, fp2);
				fclose(fp);
				fclose(fp2);
			}
		}
		else if(strcmp(argv[1], "invkey") == 0) //process invkey
		{
			if (argc == 3)
			{
				//printf("my letter a number = %d\n",'z');
				fp = fopen(argv[2], "r");
				if(fp == NULL)
				{
					fprintf(stderr, "File %s does not exist.\n", argv[2]);
					exit(1);
				}
				invkey(fp);
				fclose(fp);
			}
			else
			{
				fprintf(stderr, "Please double check your arguments. The invkey function expects to have only 1 argument which is the keyfile\n");
				exit(1);
			}
		}
		else if(strcmp(argv[1], "histo") == 0) //processing histo command
		{
			if (argc == 4 || argc == 5) //expect to have 2 or 3 argument on top of the executable name and function name
			{
				int which = 0;
				int period = 0;
				char *filename = "";
				//Use for loop to go through all arguments
				for (int index = argc-1; index > 1; index--)
				{
					//find '=' at each argument
					char *val = strchr(argv[index], '=');
					if (val == NULL)
					{
						if (argc == 5)
						{
							//Must be the input file
							filename = argv[index];
						}
						else
						{
							//malformed command
							fprintf(stderr,"Please double check your arguments. The histo function expects to have at least 2 arguments in following format: -t=period and -i=which, and an optional input file\n");
							exit(1);
						}
					}
					else
					{
						char *checkArgs = argv[index];
						*val = '\0'; //replace '=' by NULL character to separate key and val pointers
						val++;
						//compare to see which key is it
						if (strncmp(checkArgs, "-t", 2) == 0)
						{
							//period
							period = atoi(val);
						}
						else if(strncmp(checkArgs, "-i", 2) == 0)
						{
							//which
							which = atoi(val);
						}
						else
						{
							//malformed command
							fprintf(stderr,"Please double check your arguments. The histo function expects to have at least 2 arguments in following format: -t=period and -i=which, and an optional input file\n");
							exit(1);
						}
					}
				}

				if (which <= 0 || period <= 0)
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The histo function expects to have at least 2 arguments in following format: -t=period and -i=which, and an optional input file\n");
					exit(1);
				}
				else if (argc == 5 && strcmp(filename,"") == 0)
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The histo function expects to have at least 2 arguments in following format: -t=period and -i=which, and an optional input file\n");
					exit(1);
				}
				//Check if we have which is greater than the period. If so, return error
				if (which > period)
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The histo function does not allow --which value is greater than --period value\n");
					exit(1);
				}
				//Now call histo function with period, which, and input file from stdin or from input file
				if (argc == 4)
				{
					histo(period,which,stdin);
				}
				else
				{
					fp = fopen(filename,"r");
					if (fp == NULL)
					{
						fprintf(stderr,"File %s does not exist.\n", filename);
						exit(1);
					}
					histo(period,which,fp);
					fclose(fp);
				}

			}
			else
			{
				//malformed command
				fprintf(stderr,"Please double check your arguments. The histo function expects to have at least 2 arguments in following format: -t=period and -i=which, and an optional input file\n");
				exit(1);
			}
		}
		else if(strcmp(argv[1], "solve") == 0) //processing solve command
		{
			if (argc == 4)
			{
				char *filename = "";
				int max_t = 0;
				//Use for loop to go through all arguments
				for (int index = argc-1; index > 1; index--)
				{
					//find '=' at each argument
					char *val = strchr(argv[index], '=');
					if (val == NULL)
					{
						//Must be file name
						filename = argv[index];
					}
					else
					{
						char *checkArgs = argv[index];
						*val = '\0'; //replace '=' by NULL character to separate key and val pointers
						val++;
						//compare to see which key is it
						if (strncmp(checkArgs, "-l", 2) == 0)
						{
							//max_t period
							max_t = atoi(val);
						}
						else
						{
							//malformed command
							fprintf(stderr,"Please double check your arguments. The solve function expects to have exactly 2 arguments in following format: -l=max_t and input file\n");
							exit(1);
						}
					}
				}
				if (strcmp(filename,"") == 0 || max_t == 0)
				{
					//malformed command
					fprintf(stderr,"Please double check your arguments. The solve function expects to have exactly 2 arguments in following format: -l=max_t and input file\n");
					exit(1);
				}
				else
				{
					fp = fopen(filename, "r");
					if(fp == NULL)
					{
						fprintf(stderr,"File %s does not exist\n", filename);
						exit(1);
					}
					//Call solve function
					solve(fp,max_t);
					fclose(fp);
				}
			}
			else
			{
				//malformed command
				fprintf(stderr,"Please double check your arguments. The solve function expects to have exactly 2 arguments in following format: -l=max_t and input file\n");
				exit(1);
			}
		}
		else
		{
			fprintf(stderr, "Please enter the correct program name and try again\n");
		}
	}
}
Esempio n. 7
0
int
main(int argc, char **argv) {
	isc_boolean_t show_final_mem = ISC_FALSE;
	isc_buffer_t key_txtbuffer;
	char key_txtsecret[256];
	isc_mem_t *mctx = NULL;
	isc_result_t result = ISC_R_SUCCESS;
	const char *keyname = NULL;
	const char *randomfile = NULL;
	const char *serveraddr = NULL;
	dns_secalg_t alg = DST_ALG_HMACMD5;
	const char *algname = alg_totext(alg);
	char *p;
	int ch;
	int port;
	int keysize;
	struct in_addr addr4_dummy;
	struct in6_addr addr6_dummy;
	char *chrootdir = NULL;
	char *user = NULL;
	isc_boolean_t keyonly = ISC_FALSE;
	int len;

	keydef = keyfile = RNDC_KEYFILE;

	result = isc_file_progname(*argv, program, sizeof(program));
	if (result != ISC_R_SUCCESS)
		memmove(program, "rndc-confgen", 13);
	progname = program;

	keyname = DEFAULT_KEYNAME;
	keysize = DEFAULT_KEYLENGTH;
	serveraddr = DEFAULT_SERVER;
	port = DEFAULT_PORT;

	isc_commandline_errprint = ISC_FALSE;

	while ((ch = isc_commandline_parse(argc, argv,
					   "ab:c:hk:Mmp:r:s:t:u:Vy")) != -1) {
		switch (ch) {
		case 'a':
			keyonly = ISC_TRUE;
			break;
		case 'b':
			keysize = strtol(isc_commandline_argument, &p, 10);
			if (*p != '\0' || keysize < 0)
				fatal("-b requires a non-negative number");
			break;
		case 'c':
			keyfile = isc_commandline_argument;
			break;
		case 'h':
			usage(0);
		case 'k':
		case 'y':	/* Compatible with rndc -y. */
			keyname = isc_commandline_argument;
			break;
		case 'M':
			isc_mem_debugging = ISC_MEM_DEBUGTRACE;
			break;

		case 'm':
			show_final_mem = ISC_TRUE;
			break;
		case 'p':
			port = strtol(isc_commandline_argument, &p, 10);
			if (*p != '\0' || port < 0 || port > 65535)
				fatal("port '%s' out of range",
				      isc_commandline_argument);
			break;
		case 'r':
			randomfile = isc_commandline_argument;
			break;
		case 's':
			serveraddr = isc_commandline_argument;
			if (inet_pton(AF_INET, serveraddr, &addr4_dummy) != 1 &&
			    inet_pton(AF_INET6, serveraddr, &addr6_dummy) != 1)
				fatal("-s should be an IPv4 or IPv6 address");
			break;
		case 't':
			chrootdir = isc_commandline_argument;
			break;
		case 'u':
			user = isc_commandline_argument;
			break;
		case 'V':
			verbose = ISC_TRUE;
			break;
		case '?':
			if (isc_commandline_option != '?') {
				fprintf(stderr, "%s: invalid argument -%c\n",
					program, isc_commandline_option);
				usage(1);
			} else
				usage(0);
			break;
		default:
			fprintf(stderr, "%s: unhandled option -%c\n",
				program, isc_commandline_option);
			exit(1);
		}
	}

	argc -= isc_commandline_index;
	argv += isc_commandline_index;
	POST(argv);

	if (argc > 0)
		usage(1);

	DO("create memory context", isc_mem_create(0, 0, &mctx));
	isc_buffer_init(&key_txtbuffer, &key_txtsecret, sizeof(key_txtsecret));

	generate_key(mctx, randomfile, alg, keysize, &key_txtbuffer);

	if (keyonly) {
		write_key_file(keyfile, chrootdir == NULL ? user : NULL,
			       keyname, &key_txtbuffer, alg);

		if (chrootdir != NULL) {
			char *buf;
			len = strlen(chrootdir) + strlen(keyfile) + 2;
			buf = isc_mem_get(mctx, len);
			if (buf == NULL)
				fatal("isc_mem_get(%d) failed\n", len);
			snprintf(buf, len, "%s%s%s", chrootdir,
				 (*keyfile != '/') ? "/" : "", keyfile);

			write_key_file(buf, user, keyname, &key_txtbuffer, alg);
			isc_mem_put(mctx, buf, len);
		}
	} else {
		printf("\
# Start of rndc.conf\n\
key \"%s\" {\n\
	algorithm %s;\n\
	secret \"%.*s\";\n\
};\n\
\n\
options {\n\
	default-key \"%s\";\n\
	default-server %s;\n\
	default-port %d;\n\
};\n\
# End of rndc.conf\n\
\n\
# Use with the following in named.conf, adjusting the allow list as needed:\n\
# key \"%s\" {\n\
# 	algorithm %s;\n\
# 	secret \"%.*s\";\n\
# };\n\
# \n\
# controls {\n\
# 	inet %s port %d\n\
# 		allow { %s; } keys { \"%s\"; };\n\
# };\n\
# End of named.conf\n",
		       keyname, algname,
		       (int)isc_buffer_usedlength(&key_txtbuffer),
		       (char *)isc_buffer_base(&key_txtbuffer),
		       keyname, serveraddr, port,
		       keyname, algname,
		       (int)isc_buffer_usedlength(&key_txtbuffer),
		       (char *)isc_buffer_base(&key_txtbuffer),
		       serveraddr, port, serveraddr, keyname);
	}

	if (show_final_mem)
		isc_mem_stats(mctx, stderr);

	isc_mem_destroy(&mctx);

	return (0);
}
Esempio n. 8
0
int main(int argc, char* argv[])
{
		rsa_packet packet;
		int i;
		bool cipher_done = 0;
		Command cmd;
		timeval hard_time;
	
    int sceMiVersion = SceMi::Version( SCEMI_VERSION_STRING );
    SceMiParameters params("scemi.params");
    SceMi *sceMi = SceMi::Init(sceMiVersion, &params);
    	
    // Initialize the crypto library
    crypto_init();

    // Initialize the SceMi inport
    InportProxyT<Command> inport ("", "scemi_rsaxactor_req_inport", sceMi);

    // Initialize the SceMi outport
    OutportQueueT<BIG_INT> outport ("", "scemi_rsaxactor_resp_outport", sceMi);

    ResetXactor reset("", "scemi", sceMi);
    ShutdownXactor shutdown("", "scemi_shutdown", sceMi);

    // Service SceMi requests
    SceMiServiceThread *scemi_service_thread = new SceMiServiceThread (sceMi);

    reset.reset();
	
    char *test_texts[] = { "deadbeef"
                         , "badf00d"
                         , "0ff1ce"
                         , "cafe"
                         , "defaced"
                         , "aeb45a0ee831ad6e538f9c59300290db92696abbaa06a0b1df6ca317239292160d81f220c99bd788cce66cc41033e2c3eddb"
                         , "46f4ef8bf4cf769bc5ab709267981dbb44801f9c419e99a2fc7639baaf6de6741cee37af64d5d50c87402713505cb51a88fb"
                         , "4d889e31f9a92bd62df29e16047beb747fc92e3eceebab44d399b386825d1f55294f6d854e56d0f9a7b610c67b2ae7b5e5bd36"
                         , "8ecbff22d54c29902bda135826fd302787742d4ce7a064f73c4ecca822235035fbdf1350bb7d9abcb4f54eb3257f2c96798d2e"
                         , "853493ee4fd1fe0cde743cba9b180bff20bd457c152e258b9e3b478bd25fa60a6766b8d36a95885c2c47aaa63f22ff93ebea08"
                         , "050e383b35f7688879a54ef463961533f040f943467b6a5617fdf88000c91c662d0688ddd5144f12c49106d8d81a5e04ff5ca2"
                         , "f355db88fb426ebea4a551ad129d4fcb243b903411e638a08a81e22bfe250937f1194caea4d1f312f06ecfa906d79e8c948a0d"
                         , "11d1e35094599325a2122f2f919a64e4d4ace48812f192ea7c11410c539707149c5d335f921f132d11795bcc1ebbf4a20b65e9"
                         , "7b101a938d50b8dc88780235f226bc1c6650df830c3290565e12d6b9c347c06b1fb0b6fb2e648019c8526e2d4adc4dc766dba5"
                         , "7305d1b0e93f54de5fa19eb1089fa6fbc566f8479cd381ca5894492c3078d23ef3d7a1923b9a96ffb7bf2b727fc28c6d522e54"
                         , "4228043134c88aed152a8cd0d9aef45f742e6d12511d0ecbfbf34ea593998c499f19c6315e8779184ab58dd8e731a25d410d61"
                         , "c04bb261996776e003d70116c3d7d56c6e2375f349983d478416f6600edeec1dbc286d4a57445be4ded180dcb7e157b35a8a4f"
                         , "eac2be8a8e3ef31a292c4faafa9c8a63acf1e4046672c5379215f6f145ce2062ace5587f3ea226f628178426062dd9ff81186c"
                         , "c3387e260634be9995b52c1f7114cf23d01cce8ef598cc8e5364db272aee60d06e626a2a67964d7391d5ed5c7193ab36eba81e"
                         , "ac84645df2aaca9dee4d03e8b900007905f9bfe93bbef391ea7b57513948ec88b252add18db987b0ff886e1c7d25152f7dc1af"
                         , "7176de621be4b8d4f5060b6ae0ab188d2c33f3aeddaddbe639cd89a8ca5784a8cdb0135108eb7f35020556795764c71536b49e"
                         , "1a3f9f30e4c3d5d244c1d9e6cfb8f4dd47f686efb74e99de63358750e6f0622b24afc212a472bf9a93b0d39e79ff4a71ee57c6"
                         , "68a9101d17cadfa1d89353a1d12d878dede2630904fbd8bf08ee36ccaa3c2b1759415ec3fe54bfa9f1034c5a20d01673fa06f6"
                         , "31206814135169d02ec6893064bcaab54d9a2cc44fedc5e16dba2d97adca09fd6838af21e06def28a3815dccae369ce1e2f4af"
                         , "f536b2e57395c6421008095dc6832282d8083ac466debc88f5979e8ada0e0b4820754f0325de29d77c46eada3683bb5be3fd10"
                         };
    for (int tests = 0; tests < 20; tests++) {
      char *public_key, *private_key;
      printf("Generating keypair in software...");
      generate_key(&packet, &public_key, &private_key);
      
      #ifdef DEFINE
        printf("Raw data dump\n Modulus length: %zi\n", packet.mod_len);
        for(i = 0; i < packet.mod_len; i++) {
          printf("%02X", packet.mod[i]);
        }
        
        printf("\nPrivate exponent length: %zi\n", packet.priv_len);
        for(i = 0; i < packet.priv_len; i++) {
          printf("%02X", packet.priv_exp[i]);
        }
        
          printf("\nPublic exponent length: %zi\n", packet.pub_len);
        for(i = 0; i < packet.pub_len; i++) {
          printf("%02X", packet.pub_exp[i]);
        }
      #endif

      printf("Public Key:\n%s\n", public_key);
      printf("Private Key:\n%s\n", private_key);
    
      char *plaintext = test_texts[tests];
      printf("Plain Text:\n%s\n\n", plaintext);
    
      char *ciphertext;
      ciphertext = encrypt(&packet, public_key, plaintext);
      printf("Software-calculated cipher Text:\n%s\n", ciphertext);
    
          printf("\nCiphertext length: %zi\n", packet.cipher_len);
        for(i = 0; i < packet.cipher_len; i++) {
          printf("%02X", packet.ciphertext[i]);
        }		  
    
    
      char *decrypted;
      decrypted = decrypt(private_key, ciphertext);
      printf("\nSoftware-decrypted plain Text:\n%s\n\n", decrypted);
    
      /*char *signature;
      signature = sign(private_key, plaintext);
      printf("Software signature:\n%s\n", signature);
      
      if (verify(public_key, plaintext, signature)) {
        printf("Software signature GOOD!\n");
      } else {
        printf("Software signature BAD!\n");
      }*/
      
      printf("Sending to FPGA..\n");

      
      // Pack the command for transport to FPGA
      // Command is specified in Command.h, run build and look in tbinclude
      // Assuming mod_len >= priv_len/pub_len/len(ciphertext)
      for(i = 0; i < packet.mod_len; i++) {
        cmd.m_modulus = packet.mod[packet.mod_len - i - 1];
        
        // Send the data for decryption
        if(i < packet.priv_len) {
          cmd.m_exponent = packet.priv_exp[packet.priv_len - i - 1];
        } else {
          cmd.m_exponent = 0;
        }
        
        // Since the exponent is short, pack it backwards
        if(i < packet.cipher_len) {
          cmd.m_data = packet.ciphertext[packet.cipher_len - i - 1];
        } else {
          cmd.m_data = 0;
        }
        
        //printf("Sending message %i, mod: %X coeff: %X data:%X\n", i, cmd.m_data.get(), cmd.m_exponent.get(), cmd.m_data.get());
        inport.sendMessage(cmd);
      }
        
      printf("Sending padding, 1 packet");
      cmd.m_modulus = 0;
      cmd.m_exponent = 0;
      cmd.m_data = 0;
      timer_start(&hard_time);
      inport.sendMessage(cmd);
        
      printf("Getting result..");
      
      std::cout << "Result: " << outport.getMessage() << std::endl;
      timer_poll("FPGA wall time: %d.%06d    seconds\n", &hard_time);
    }

    std::cout << "shutting down..." << std::endl;
    shutdown.blocking_send_finish();
    scemi_service_thread->stop();
    scemi_service_thread->join();
    SceMi::Shutdown(sceMi);
    std::cout << "finished" << std::endl;

    return 0;
}
Esempio n. 9
0
/*
 * subtest_populate --
 *	Populate the tables.
 */
static void
subtest_populate(TEST_OPTS *opts, bool close_test)
{
	WT_CURSOR *maincur, *maincur2;
	WT_RAND_STATE rnd;
	WT_SESSION *session;
	uint64_t i, nrecords;
	uint32_t rndint;
	int key, v0, v1, v2;
	char *big, *bigref;
	bool failed;

	failed = false;
	__wt_random_init_seed(NULL, &rnd);
	CHECK(create_big_string(&bigref), false);
	nrecords = opts->nrecords;

	CHECK(opts->conn->open_session(
	    opts->conn, NULL, NULL, &session), false);

	CHECK(session->open_cursor(session, "table:subtest", NULL,
	    NULL, &maincur), false);

	CHECK(session->open_cursor(session, "table:subtest2", NULL,
	    NULL, &maincur2), false);

	for (i = 0; i < nrecords && !failed; i++) {
		rndint = __wt_random(&rnd);
		generate_key(i, &key);
		generate_value(rndint, i, bigref, &v0, &v1, &v2, &big);
		CHECK(session->begin_transaction(session, NULL), false);
		maincur->set_key(maincur, key);
		maincur->set_value(maincur, v0, v1, v2, big);
		CHECK(maincur->insert(maincur), false);

		maincur2->set_key(maincur2, key);
		maincur2->set_value(maincur2, rndint);
		CHECK(maincur2->insert(maincur2), false);
		CHECK(session->commit_transaction(session, NULL), false);

		if (i == 0)
			/*
			 * Force an initial checkpoint, that helps to
			 * distinguish a clear failure from just not running
			 * long enough.
			 */
			CHECK(session->checkpoint(session, NULL), false);

		if ((i + 1) % VERBOSE_PRINT == 0 && opts->verbose)
			printf("  %" PRIu64 "/%" PRIu64 "\n",
			    (i + 1), nrecords);
		/* Attempt to isolate the failures to checkpointing. */
		if (i == (nrecords/100)) {
			enable_failures(opts->nops, 1000000);
			/* CHECK should expect failures. */
			CHECK(session->checkpoint(session, NULL), true);
			disable_failures();
			if (failed && opts->verbose)
				printf("checkpoint failed (expected).\n");
		}
	}

	/*
	 * Closing handles after an extreme fail is likely to cause
	 * cascading failures (or crashes), so recommended practice is
	 * to immediately exit. We're interested in testing both with
	 * and without the recommended practice.
	 */
	if (failed) {
		if (!close_test) {
			fprintf(stderr, "exit early.\n");
			exit(0);
		} else
			fprintf(stderr, "closing after failure.\n");
	}

	free(bigref);
	CHECK(maincur->close(maincur), false);
	CHECK(maincur2->close(maincur2), false);
	CHECK(session->close(session, NULL), false);
}
Esempio n. 10
0
int main(int argc, char **argv) {

	int c;

	bzero(CONFIG_PATH, PATH_MAX);

	while ((c = getopt(argc,argv, "vf:")) != EOF) {
		switch (c) {
			case 'f':
				snprintf(CONFIG_PATH, PATH_MAX, "%s", optarg);
				break;
			case 'v':
				verbose = 1;
				break;
			case '?':
				fprintf(stderr,"Invalid argument\n");
				exit(1);
		}
	}

	read_config();
#ifdef HAVE_LIBMAGIC
	load_magic();
#endif
	load_regexes();

	pcre_callout = pcre_callout_spider;

	umask(077);

	compile_regexes();

	if (Encrypt) {
		// do we have a password?
		if (!strlen(Password)) {
			fprintf(stderr, "No password supplied\n");
			exit(1);
		}
		// prep the log array
		startlog = (struct logarray *)malloc(sizeof(struct logarray));
		if (startlog == NULL) {
			fprintf(stderr, "Malloc: %s\n", strerror(errno));
			exit(1);
		}
		bzero(startlog -> entry, LOG_MAX);
		currlog = startlog;
		// prep our keying material
		generate_iv();
		generate_key();
	}

	if (Log2File && !LogStdout) {
		// get our filehandle open
		if (AppendLog) {
			if (CustomLogPath[0]) {
				logfp = fopen(CustomLogPath, "a+");
			} else {
				logfp = fopen(LogPath, "a+");
			}
		} else {
			if (CustomLogPath[0]) {
				logfp = fopen(CustomLogPath, "w");
			} else {
				logfp = fopen(LogPath, "w");
			}
		}
		if (logfp == NULL) {
			fprintf(stderr, "unable to open %s:%s\n",
					LogPath,
					strerror(errno));
			exit(1);
		}
	}

	if (LogSyslog) {
		(void)openlog("spider", LOG_PID|LOG_NDELAY, LOG_FAC);
	}

	
	// normally, this would run as a child process
	// we'd hold the child PID in pid_t worker
	// when the Stop Spider button is clicked, 
	// we'll send a TERM signal to the child process
	//
	run_spider(START_PATH);

	if (LogFooter[0]) {
		write_footer();
	}

	if (Encrypt) {
		// write out the encrypted log
		if (!spider_encrypt()) {
			fprintf(stderr, "failure to write encrypted log!\n");
			exit(1);
		}
	}

	if (logfp) { fclose(logfp); }

	if (WhenDone == EXIT_WHEN_DONE) {
		if (verbose) {
			fprintf(stderr, "Normal exit.\n");
		}
		exit(0);
	}
	if (WhenDone == RESTORE_WHEN_DONE) {
		// GTK fru-fru
	}
	if (WhenDone == VIEWLOG_WHEN_DONE) {
		// launch the log viewer
	}

	exit(0);
}
Esempio n. 11
0
int
run_truncate(CONFIG *cfg, CONFIG_THREAD *thread,
    WT_CURSOR *cursor, WT_SESSION *session, int *truncatedp) {

	TRUNCATE_CONFIG *trunc_cfg;
	TRUNCATE_QUEUE_ENTRY *truncate_item;
	char *truncate_key;
	int ret, t_ret;

	ret = 0;
	trunc_cfg = &thread->trunc_cfg;

	*truncatedp = 0;
	/* Update the total inserts */
	trunc_cfg->total_inserts = sum_insert_ops(cfg);
	trunc_cfg->expected_total +=
	    (trunc_cfg->total_inserts - trunc_cfg->last_total_inserts);
	trunc_cfg->last_total_inserts = trunc_cfg->total_inserts;

	/* We are done if there isn't enough data to trigger a new milestone. */
	if (trunc_cfg->expected_total <= trunc_cfg->needed_stones)
		return (0);

	while (trunc_cfg->num_stones < trunc_cfg->needed_stones) {
		trunc_cfg->last_key += trunc_cfg->stone_gap;
		truncate_key = calloc(cfg->key_sz, 1);
		if (truncate_key == NULL) {
			lprintf(cfg, ENOMEM, 0,
			    "truncate: couldn't allocate key array");
			return (ENOMEM);
		}
		truncate_item = calloc(sizeof(TRUNCATE_QUEUE_ENTRY), 1);
		if (truncate_item == NULL) {
			free(truncate_key);
			lprintf(cfg, ENOMEM, 0,
			    "truncate: couldn't allocate item");
			return (ENOMEM);
		}
		generate_key(cfg, truncate_key, trunc_cfg->last_key);
		truncate_item->key = truncate_key;
		truncate_item->diff = trunc_cfg->stone_gap;
		TAILQ_INSERT_TAIL(&cfg->stone_head, truncate_item, q);
		trunc_cfg->num_stones++;
	}

	/* We are done if there isn't enough data to trigger a truncate. */
	if (trunc_cfg->num_stones == 0 ||
	    trunc_cfg->expected_total <= thread->workload->truncate_count)
		return (0);

	truncate_item = TAILQ_FIRST(&cfg->stone_head);
	trunc_cfg->num_stones--;
	TAILQ_REMOVE(&cfg->stone_head, truncate_item, q);
	cursor->set_key(cursor,truncate_item->key);
	if ((ret = cursor->search(cursor)) != 0) {
		lprintf(cfg, ret, 0, "Truncate search: failed");
		goto err;
	}

	if ((ret = session->truncate(session, NULL, NULL, cursor, NULL)) != 0) {
		lprintf(cfg, ret, 0, "Truncate: failed");
		goto err;
	}


	*truncatedp = 1;
	trunc_cfg->expected_total -= truncate_item->diff;

err:	free(truncate_item->key);
	free(truncate_item);
	t_ret = cursor->reset(cursor);
	if (t_ret != 0)
		lprintf(cfg, t_ret, 0, "Cursor reset failed");
	if (ret == 0 && t_ret != 0)
		ret = t_ret;
	return (ret);
}
Esempio n. 12
0
int
run_truncate(CONFIG *cfg, CONFIG_THREAD *thread,
    WT_CURSOR *cursor, WT_SESSION *session, int *truncatedp) {

	TRUNCATE_CONFIG *trunc_cfg;
	TRUNCATE_QUEUE_ENTRY *truncate_item;
	char *truncate_key;
	int ret, t_ret;
	uint64_t used_stone_gap;

	ret = 0;
	trunc_cfg = &thread->trunc_cfg;

	*truncatedp = 0;
	/* Update the total inserts */
	trunc_cfg->total_inserts = sum_insert_ops(cfg);
	trunc_cfg->expected_total +=
	    (trunc_cfg->total_inserts - trunc_cfg->last_total_inserts);
	trunc_cfg->last_total_inserts = trunc_cfg->total_inserts;

	/* We are done if there isn't enough data to trigger a new milestone. */
	if (trunc_cfg->expected_total <= thread->workload->truncate_count)
		return (0);

	/*
	 * If we are falling behind and using more than one stone per lap we
	 * should widen the stone gap for this lap to try and catch up quicker.
	 */
	if (trunc_cfg->expected_total >
	    thread->workload->truncate_count + trunc_cfg->stone_gap) {
		/*
		 * Increase the multiplier until we create stones that are
		 * almost large enough to truncate the whole expected table size
		 * in one operation.
		 */
		trunc_cfg->catchup_multiplier =
		    WT_MIN(trunc_cfg->catchup_multiplier + 1,
		    trunc_cfg->needed_stones - 1);
	} else {
		/* Back off if we start seeing an improvement */
		trunc_cfg->catchup_multiplier =
		    WT_MAX(trunc_cfg->catchup_multiplier - 1, 1);
	}
	used_stone_gap = trunc_cfg->stone_gap * trunc_cfg->catchup_multiplier;

	while (trunc_cfg->num_stones < trunc_cfg->needed_stones) {
		trunc_cfg->last_key += used_stone_gap;
		truncate_key = calloc(cfg->key_sz, 1);
		if (truncate_key == NULL) {
			lprintf(cfg, ENOMEM, 0,
			    "truncate: couldn't allocate key array");
			return (ENOMEM);
		}
		truncate_item = calloc(sizeof(TRUNCATE_QUEUE_ENTRY), 1);
		if (truncate_item == NULL) {
			free(truncate_key);
			lprintf(cfg, ENOMEM, 0,
			    "truncate: couldn't allocate item");
			return (ENOMEM);
		}
		generate_key(cfg, truncate_key, trunc_cfg->last_key);
		truncate_item->key = truncate_key;
		truncate_item->diff = used_stone_gap;
		TAILQ_INSERT_TAIL(&cfg->stone_head, truncate_item, q);
		trunc_cfg->num_stones++;
	}

	/* We are done if there isn't enough data to trigger a truncate. */
	if (trunc_cfg->num_stones == 0 ||
	    trunc_cfg->expected_total <= thread->workload->truncate_count)
		return (0);

	truncate_item = TAILQ_FIRST(&cfg->stone_head);
	trunc_cfg->num_stones--;
	TAILQ_REMOVE(&cfg->stone_head, truncate_item, q);
	cursor->set_key(cursor,truncate_item->key);
	if ((ret = cursor->search(cursor)) != 0) {
		lprintf(cfg, ret, 0, "Truncate search: failed");
		goto err;
	}

	if ((ret = session->truncate(session, NULL, NULL, cursor, NULL)) != 0) {
		lprintf(cfg, ret, 0, "Truncate: failed");
		goto err;
	}

	*truncatedp = 1;
	trunc_cfg->expected_total -= truncate_item->diff;

err:	free(truncate_item->key);
	free(truncate_item);
	t_ret = cursor->reset(cursor);
	if (t_ret != 0)
		lprintf(cfg, t_ret, 0, "Cursor reset failed");
	if (ret == 0 && t_ret != 0)
		ret = t_ret;
	return (ret);
}
Esempio n. 13
0
ssize_t
th_lzss(
    thtk_io_t* input,
    size_t input_size,
    thtk_io_t* output,
    thtk_error_t** error)
{
    struct bitstream bs;
    hash_t hash;
    unsigned char dict[LZSS_DICTSIZE];
    unsigned int dict_head = 1;
    unsigned int dict_head_key;
    unsigned int waiting_bytes = 0;
    size_t bytes_read = 0;
    unsigned int i;
    unsigned char c;

    if (!input || !output) {
        thtk_error_new(error, "input or output is NULL");
        return -1;
    }

    bitstream_init(&bs, output);
    memset(&hash, 0, sizeof(hash));
    memset(dict, 0, sizeof(dict));

    /* Fill the forward-looking buffer. */
    for (i = 0; i < LZSS_MAX_MATCH && i < input_size; ++i) {
        int ret = thtk_io_read(input, &c, 1, error);
        if (ret == -1) {
            return -1;
        } else if (ret != 1) {
            break;
        }
        ++bytes_read;
        dict[dict_head + i] = c;
        waiting_bytes++;
    }

    dict_head_key = generate_key(dict, dict_head);

    while (waiting_bytes) {
        unsigned int match_len = LZSS_MIN_MATCH - 1;
        unsigned int match_offset = 0;
        unsigned int offset;

        /* Find a good match. */
        for (offset = hash.hash[dict_head_key];
             offset != HASH_NULL && waiting_bytes > match_len;
             offset = hash.next[offset]) {
            /* First check a character further ahead to see if this match can
             * be any longer than the current match. */
            if (dict[(dict_head + match_len) & LZSS_DICTSIZE_MASK] ==
                dict[(offset + match_len) & LZSS_DICTSIZE_MASK]) {
                /* Then check the previous characters. */
                for (i = 0;
                     i < match_len &&
                     (dict[(dict_head + i) & LZSS_DICTSIZE_MASK] ==
                      dict[(offset + i) & LZSS_DICTSIZE_MASK]);
                     ++i)
                    ;

                if (i < match_len)
                    continue;

                /* Finally try to extend the match. */
                for (++match_len;
                     match_len < waiting_bytes &&
                     (dict[(dict_head + match_len) & LZSS_DICTSIZE_MASK] ==
                      dict[(offset + match_len) & LZSS_DICTSIZE_MASK]);
                     ++match_len)
                    ;

                match_offset = offset;
            }
        }

        /* Write data to the output buffer. */
        if (match_len < LZSS_MIN_MATCH) {
            match_len = 1;
            bitstream_write1(&bs, 1);
            bitstream_write(&bs, 8, dict[dict_head]);
        } else {
            bitstream_write1(&bs, 0);
            bitstream_write(&bs, 13, match_offset);
            bitstream_write(&bs, 4, match_len - LZSS_MIN_MATCH);
        }

        /* Add bytes to the dictionary. */
        for (i = 0; i < match_len; ++i) {
            const unsigned int offset =
                (dict_head + LZSS_MAX_MATCH) & LZSS_DICTSIZE_MASK;

            if (offset != HASH_NULL)
                list_remove(&hash, generate_key(dict, offset), offset);
            if (dict_head != HASH_NULL)
                list_add(&hash, dict_head_key, dict_head);

            if (bytes_read < input_size) {
                int ret = thtk_io_read(input, &c, 1, error);
                if (ret == 1) {
                    dict[offset] = c;
                    ++bytes_read;
                } else if (ret == 0) {
                    --waiting_bytes;
                } else {
                    return -1;
                }
            } else {
                --waiting_bytes;
            }

            dict_head = (dict_head + 1) & LZSS_DICTSIZE_MASK;
            dict_head_key = generate_key(dict, dict_head);
        }
    }

    bitstream_write1(&bs, 0);
    bitstream_write(&bs, 13, HASH_NULL);
    bitstream_write(&bs, 4, 0);

    bitstream_finish(&bs);

    return bs.byte_count;
}
Esempio n. 14
0
int
main (int argc, char *argv[])
{
	int flags1 = 0, flags2 = 0, outfd, infd, decfd;
	mode_t mode;
	char choice, temp;
	int done = 0, n, olen;

	bzero (&key, 16);
	bzero (&iv, 8);
	bzero (&mode, sizeof (mode));

	flags1 = flags1 | O_RDONLY;
	flags2 = flags2 | O_RDONLY;
	flags2 = flags2 | O_WRONLY;
	flags2 = flags2 | O_CREAT;

	mode = mode | S_IRUSR;
	mode = mode | S_IWUSR;

	while (!done)
	  {
		  printf ("E - Encrypt a file\n");
		  printf ("D - Decrypt a file\n");
		  printf ("G - Generate a key\n");
		  printf ("Q - Quit\n");

		  choice = getchar ();
		  temp = getchar ();

		  switch (choice)
		    {
		    case 'e':
		    case 'E':

			    if ((infd = open (argv[1], flags1, mode)) == -1)
				    perror ("open input file error");

			    if ((outfd = open (argv[2], flags2, mode)) == -1)
				    perror ("open output file error");

			    encrypt (infd, outfd);

			    close (infd);
			    close (outfd);
			    break;

		    case 'd':
		    case 'D':

			    if ((outfd = open (argv[2], flags1, mode)) == -1)
				    perror ("open output file error");

			    if ((decfd = open (argv[3], flags2, mode)) == -1)
				    perror ("open output file error");

			    decrypt (outfd, decfd);

			    close (outfd);
			    fsync (decfd);
			    close (decfd);
			    break;

		    case 'g':
		    case 'G':
			    generate_key ();
			    break;

		    case 'Q':
		    case 'q':
			    done = 1;
			    break;

		    default:
			    printf ("ERROR: Unrecognized command.  Try again.\n");
			    break;
		    }
	  }
	return 0;
}
Esempio n. 15
0
void PictureShape::paint(QPainter &painter, const KoViewConverter &converter,
                         KoShapePaintingContext &paintContext)
{
    Q_UNUSED(paintContext);

    QRectF viewRect = converter.documentToView(QRectF(QPointF(0,0), size()));
    if (imageData() == 0) {
        painter.fillRect(viewRect, QColor(Qt::gray));
        return;
    }

    painter.save();
    applyConversion(painter, converter);
    paintBorder(painter, converter);
    painter.restore();

    QSize pixmapSize = calcOptimalPixmapSize(viewRect.size(), imageData()->image().size());

    // Normalize the clipping rect if it isn't already done.
    m_clippingRect.normalize(imageData()->imageSize());

    // Handle style:mirror, i.e. mirroring horizontally and/or vertically.
    // 
    // NOTE: At this time we don't handle HorizontalOnEven
    //       and HorizontalOnOdd, which have to know which
    //       page they are on.  In those cases we treat it as
    //       no horizontal mirroring at all.
    bool   doFlip = false;
    QSizeF shapeSize = size();
    QSizeF viewSize = converter.documentToView(shapeSize);
    qreal  midpointX = 0.0;
    qreal  midpointY = 0.0;
    qreal  scaleX = 1.0;
    qreal  scaleY = 1.0;
    if (m_mirrorMode & MirrorHorizontal) {
        midpointX = viewSize.width() / qreal(2.0);
        scaleX = -1.0;
        doFlip = true;
    }
    if (m_mirrorMode & MirrorVertical) {
        midpointY = viewSize.height() / qreal(2.0);
        scaleY = -1.0;
        doFlip = true;
    }
    if (doFlip) {
        QTransform outputTransform = painter.transform();
        QTransform worldTransform  = QTransform();

        //kDebug(31000) << "Flipping" << midpointX << midpointY << scaleX << scaleY;
        worldTransform.translate(midpointX, midpointY);
        worldTransform.scale(scaleX, scaleY);
        worldTransform.translate(-midpointX, -midpointY);
        //kDebug(31000) << "After flipping for window" << worldTransform;

        QTransform newTransform = worldTransform * outputTransform;
        painter.setWorldTransform(newTransform);
    }

    // Paint the image as prepared in waitUntilReady()
    if (!m_printQualityImage.isNull() && pixmapSize != m_printQualityRequestedSize) {
        QSizeF imageSize = m_printQualityImage.size();
        QRectF cropRect(
            imageSize.width()  * m_clippingRect.left,
            imageSize.height() * m_clippingRect.top,
            imageSize.width()  * m_clippingRect.width(),
            imageSize.height() * m_clippingRect.height()
        );

        painter.drawImage(viewRect, m_printQualityImage, cropRect);
        m_printQualityImage = QImage(); // free memory
    }
    else {
        QPixmap pixmap;
        QString key(generate_key(imageData()->key(), pixmapSize));

        // If the required pixmap is not in the cache
        // launch a task in a background thread that scales
        // the source image to the required size
        if (!QPixmapCache::find(key, &pixmap)) {
            QThreadPool::globalInstance()->start(new _Private::PixmapScaler(this, pixmapSize));
            painter.fillRect(viewRect, QColor(Qt::gray)); // just paint a gray rect as long as we don't have the required pixmap
        }
        else {
            QRectF cropRect(
                pixmapSize.width()  * m_clippingRect.left,
                pixmapSize.height() * m_clippingRect.top,
                pixmapSize.width()  * m_clippingRect.width(),
                pixmapSize.height() * m_clippingRect.height()
            );

            painter.drawPixmap(viewRect, pixmap, cropRect);
        }
    }
}
Esempio n. 16
0
static void
generate_key_pair(const u_char *seed, u_char *client_to_server_key, u_char *server_to_client_key, int ossh_key_fix)
{
	generate_key(seed, "client_to_server", strlen("client_to_server"), client_to_server_key, ossh_key_fix);
	generate_key(seed, "server_to_client", strlen("server_to_client"), server_to_client_key, ossh_key_fix);
}
Esempio n. 17
0
void PictureShape::paint(QPainter &painter, const KViewConverter &converter)
{
    QRectF pixelsF = converter.documentToView(QRectF(QPointF(0,0), size()));
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        painter.fillRect(pixelsF, QColor(Qt::gray));
        return;
    }
    const QRect pixels = pixelsF.toRect();
    QSize pixmapSize = pixels.size();

    QString key(generate_key(imageData->key(), pixmapSize));
    QPixmap pixmap;
#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) { // first check cache.
#else
    if (!QPixmapCache::find(key, pixmap)) { // first check cache.
#endif
        // no? Does the imageData have it then?
        if (!(imageData->hasCachedPixmap() && imageData->pixmap().size() == pixmapSize)) {
            // ok, not what we want.
            // before asking to render it, make sure the image doesn't get too big
            QSize imageSize = imageData->image().size();
            if (imageSize.width() < pixmapSize.width() || imageSize.height() < pixmapSize.height()) {
                // kDebug() << "clipping size to orig image size" << imageSize;
                pixmapSize.setWidth(imageSize.width());
                pixmapSize.setHeight(imageSize.height());
            }

            if (m_printQualityImage.isNull()) {
                const int MaxSize = 1000; // TODO set the number as a KImageCollection size
                // make sure our pixmap doesn't get too slow.
                // In future we may want to make this action cause a multi-threaded rescale of the pixmap.
                if (pixmapSize.width() > MaxSize) { // resize to max size.
                    pixmapSize.setHeight(qRound(pixelsF.height() / pixelsF.width() * MaxSize));
                    pixmapSize.setWidth(MaxSize);
                }
                if (pixmapSize.height() > MaxSize) {
                    pixmapSize.setWidth(qRound(pixelsF.width() / pixelsF.height() * MaxSize));
                    pixmapSize.setHeight(MaxSize);
                }
            }
            key = generate_key(imageData->key(), pixmapSize);
        }
    }

    if (!m_printQualityImage.isNull() && pixmapSize == m_printQualityImage.size()) { // painting the image as prepared in waitUntilReady()
        painter.drawImage(pixels, m_printQualityImage, QRect(0, 0, pixmapSize.width(), pixmapSize.height()));
        m_printQualityImage = QImage(); // free memory
        return;
    }

#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) {
#else
    if (!QPixmapCache::find(key, pixmap)) {
#endif
        m_renderQueue->addSize(pixmapSize);
        QTimer::singleShot(0, m_renderQueue, SLOT(renderImage()));
        if (!imageData->hasCachedPixmap()
            || imageData->pixmap().size().width() > pixmapSize.width()) { // don't scale down
            QTimer::singleShot(0, m_renderQueue, SLOT(updateShape()));
            return;
        }
        pixmap = imageData->pixmap();
    }
    painter.drawPixmap(pixels, pixmap, QRect(0, 0, pixmap.width(), pixmap.height()));
}

void PictureShape::waitUntilReady(const KViewConverter &converter, bool asynchronous) const
{
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    if (asynchronous) {
        // get pixmap and schedule it if not
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QImage image = imageData->image();
        if (image.isNull()) {
            return;
        }
        if (image.size().width() < pixels.width()) { // don't scale up.
            pixels = image.size();
        }
        m_printQualityImage = image.scaled(pixels, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    }
    else {
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QString key(generate_key(imageData->key(), pixels));
        if (QPixmapCache::find(key) == 0) {
            QPixmap pixmap = imageData->pixmap(pixels);
            QPixmapCache::insert(key, pixmap);
        }
    }
}

void PictureShape::saveOdf(KShapeSavingContext &context) const
{
    // make sure we have a valid image data pointer before saving
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    KXmlWriter &writer = context.xmlWriter();

    writer.startElement("draw:frame");
    saveOdfAttributes(context, OdfAllAttributes);
    writer.startElement("draw:image");
    // In the spec, only the xlink:href attribute is marked as mandatory, cool :)
    QString name = context.imageHref(imageData);
    writer.addAttribute("xlink:type", "simple");
    writer.addAttribute("xlink:show", "embed");
    writer.addAttribute("xlink:actuate", "onLoad");
    writer.addAttribute("xlink:href", name);
    if (parent()) {
        parent()->saveOdfChildElements(context);
    }
    writer.endElement(); // draw:image
    saveOdfCommonChildElements(context);
    writer.endElement(); // draw:frame

    context.addDataCenter(m_imageCollection);
}
Esempio n. 18
0
int
setup_truncate(CONFIG *cfg, CONFIG_THREAD *thread, WT_SESSION *session) {

	TRUNCATE_CONFIG *trunc_cfg;
	TRUNCATE_QUEUE_ENTRY *truncate_item;
	WORKLOAD *workload;
	WT_CURSOR *cursor;
	char *key, *truncate_key;
	int ret;
	uint64_t end_point, final_stone_gap, i, start_point;

	end_point = final_stone_gap = start_point = 0;
	trunc_cfg = &thread->trunc_cfg;
	workload = thread->workload;

	/* We are limited to only one table when running truncate. */
	if ((ret = session->open_cursor(
	    session, cfg->uris[0], NULL, NULL, &cursor)) != 0)
		goto err;

	/* How many entries between each stone. */
	trunc_cfg->stone_gap =
	    (workload->truncate_count * workload->truncate_pct) / 100;
	/* How many stones we need. */
	trunc_cfg->needed_stones =
	    workload->truncate_count / trunc_cfg->stone_gap;

	final_stone_gap = trunc_cfg->stone_gap;

	/* Reset this value for use again. */
	trunc_cfg->stone_gap = 0;

	/*
	 * Here we check if there is data in the collection. If there is
	 * data available, then we need to setup some initial truncation
	 * stones.
	 */
	if ((ret = cursor->next(cursor)) != 0 ||
	    (ret = cursor->get_key(cursor, &key)) != 0) {
		lprintf(cfg, ret, 0, "truncate setup start: failed");
		goto err;
	}

	start_point = decode_key(key);
	if ((cursor->reset(cursor)) != 0 || (ret = cursor->prev(cursor)) != 0 ||
	    (ret = cursor->get_key(cursor, &key)) != 0) {
		lprintf(cfg, ret, 0, "truncate setup end: failed");
		goto err;
	}
	end_point = decode_key(key);

	/* Assign stones if there are enough documents. */
	if (start_point + trunc_cfg->needed_stones > end_point)
		trunc_cfg->stone_gap = 0;
	else
		trunc_cfg->stone_gap =
		    (end_point - start_point) / trunc_cfg->needed_stones;

	/* If we have enough data allocate some stones. */
	if (trunc_cfg->stone_gap != 0) {
		trunc_cfg->expected_total = (end_point - start_point);
		for (i = 1; i <= trunc_cfg->needed_stones; i++) {
			truncate_key = calloc(cfg->key_sz, 1);
			if (truncate_key == NULL) {
				ret = enomem(cfg);
				goto err;
			}
			truncate_item = calloc(sizeof(TRUNCATE_QUEUE_ENTRY), 1);
			if (truncate_item == NULL) {
				free(truncate_key);
				ret = enomem(cfg);
				goto err;
			}
			generate_key(
			    cfg, truncate_key, trunc_cfg->stone_gap * i);
			truncate_item->key = truncate_key;
			truncate_item->diff =
			    (trunc_cfg->stone_gap * i) - trunc_cfg->last_key;
			TAILQ_INSERT_TAIL( &cfg->stone_head, truncate_item, q);
			trunc_cfg->last_key = trunc_cfg->stone_gap * i;
			trunc_cfg->num_stones++;
		}
	}
	trunc_cfg->stone_gap = final_stone_gap;

err:	if ((ret = cursor->close(cursor)) != 0) {
		lprintf(cfg, ret, 0, "truncate setup: cursor close failed");
	}
	return (ret);
}
Esempio n. 19
0
/*
 * check_results --
 *	Check all the tables and verify the results.
 */
static int
check_results(TEST_OPTS *opts, uint64_t *foundp)
{
	WT_CURSOR *maincur, *maincur2, *v0cur, *v1cur, *v2cur;
	WT_SESSION *session;
	uint64_t count, idxcount, nrecords;
	uint32_t rndint;
	int key, key_got, ret, v0, v1, v2;
	char *big, *bigref;

	testutil_check(create_big_string(&bigref));
	nrecords = opts->nrecords;
	testutil_check(wiredtiger_open(opts->home, NULL,
	    "create,log=(enabled)", &opts->conn));
	testutil_check(
	    opts->conn->open_session(opts->conn, NULL, NULL, &session));

	testutil_check(session->open_cursor(session, "table:subtest", NULL,
	    NULL, &maincur));
	testutil_check(session->open_cursor(session, "table:subtest2", NULL,
	    NULL, &maincur2));
	testutil_check(session->open_cursor(session, "index:subtest:v0", NULL,
	    NULL, &v0cur));
	testutil_check(session->open_cursor(session, "index:subtest:v1", NULL,
	    NULL, &v1cur));
	testutil_check(session->open_cursor(session, "index:subtest:v2", NULL,
	    NULL, &v2cur));

	count = 0;
	while ((ret = maincur->next(maincur)) == 0) {
		testutil_check(maincur2->next(maincur2));
		testutil_check(maincur2->get_key(maincur2, &key_got));
		testutil_check(maincur2->get_value(maincur2, &rndint));

		generate_key(count, &key);
		generate_value(rndint, count, bigref, &v0, &v1, &v2, &big);
		testutil_assert(key == key_got);

		/* Check the key/values in main table. */
		testutil_check(maincur->get_key(maincur, &key_got));
		testutil_assert(key == key_got);
		check_values(maincur, v0, v1, v2, big);

		/* Check the values in the indices. */
		v0cur->set_key(v0cur, v0);
		testutil_check(v0cur->search(v0cur));
		check_values(v0cur, v0, v1, v2, big);
		v1cur->set_key(v1cur, v1);
		testutil_check(v1cur->search(v1cur));
		check_values(v1cur, v0, v1, v2, big);
		v2cur->set_key(v2cur, v2);
		testutil_check(v2cur->search(v2cur));
		check_values(v2cur, v0, v1, v2, big);

		count++;
		if (count % VERBOSE_PRINT == 0 && opts->verbose)
			printf("checked %" PRIu64 "/%" PRIu64 "\n", count,
			    nrecords);
	}
	if (count % VERBOSE_PRINT != 0 && opts->verbose)
		printf("checked %" PRIu64 "/%" PRIu64 "\n", count, nrecords);

	/*
	 * Always expect at least one entry, as populate does a
	 * checkpoint after the first insert.
	 */
	testutil_assert(count > 0);
	testutil_assert(ret == WT_NOTFOUND);
	testutil_assert(maincur2->next(maincur2) == WT_NOTFOUND);
	cursor_count_items(v0cur, &idxcount);
	testutil_assert(count == idxcount);
	cursor_count_items(v1cur, &idxcount);
	testutil_assert(count == idxcount);
	cursor_count_items(v2cur, &idxcount);
	testutil_assert(count == idxcount);

	testutil_check(opts->conn->close(opts->conn, NULL));
	opts->conn = NULL;

	free(bigref);
	*foundp = count;
	return (0);
}
Esempio n. 20
0
int main(int argc, char* argv[]) {
	clock_t start, finish;
	double time_taken;
	unsigned long file_size;
	unsigned short int padding;

	if (argc < 2) {
		printf("You must provide at least 1 parameter, where you specify the action.");
		return 1;
	}

	if (strcmp(argv[1], ACTION_GENERATE_KEY) == 0) { // Generate key file
		if (argc != 3) {
			printf("Invalid # of parameter specified. Usage: run_des -g keyfile.key");
			return 1;
		}

		key_file = fopen(argv[2], "wb");
		if (!key_file) {
			printf("Could not open file to write key.");
			return 1;
		}

		unsigned int iseed = (unsigned int)time(NULL);
		srand (iseed);

		short int bytes_written;
		unsigned char* des_key = (unsigned char*) malloc(8*sizeof(char));
		generate_key(des_key);
		bytes_written = fwrite(des_key, 1, DES_KEY_SIZE, key_file);
		if (bytes_written != DES_KEY_SIZE) {
			printf("Error writing key to output file.");
			fclose(key_file);
			free(des_key);
			return 1;
		}

		free(des_key);
		fclose(key_file);
	} else if ((strcmp(argv[1], ACTION_ENCRYPT) == 0) || (strcmp(argv[1], ACTION_DECRYPT) == 0)) { // Encrypt or decrypt
		if (argc != 5) {
			printf("Invalid # of parameters (%d) specified. Usage: run_des [-e|-d] keyfile.key input.file output.file", argc);
			return 1;
		}

		// Read key file
		key_file = fopen(argv[2], "rb");
		if (!key_file) {
			printf("Could not open key file to read key.");
			return 1;
		}

		short int bytes_read;
		unsigned char* des_key = (unsigned char*) malloc(8*sizeof(char));
		bytes_read = fread(des_key, sizeof(unsigned char), DES_KEY_SIZE, key_file);
		if (bytes_read != DES_KEY_SIZE) {
			printf("Key read from key file does nto have valid key size.");
			fclose(key_file);
			return 1;
		}
		fclose(key_file);

		// Open input file
		input_file = fopen(argv[3], "rb");
		if (!input_file) {
			printf("Could not open input file to read data.");
			return 1;
		}

		// Open output file
		output_file = fopen(argv[4], "wb");
		if (!output_file) {
			printf("Could not open output file to write data.");
			return 1;
		}

		// Generate DES key set
		short int bytes_written, process_mode;
		unsigned long block_count = 0, number_of_blocks;
		unsigned char* data_block = (unsigned char*) malloc(8*sizeof(char));
		unsigned char* processed_block = (unsigned char*) malloc(8*sizeof(char));
		key_set* key_sets = (key_set*)malloc(17*sizeof(key_set));

		start = clock();
		generate_sub_keys(des_key, key_sets);
		finish = clock();
		time_taken = (double)(finish - start)/(double)CLOCKS_PER_SEC;

		// Determine process mode
		if (strcmp(argv[1], ACTION_ENCRYPT) == 0) {
			process_mode = ENCRYPTION_MODE;
			printf("Encrypting..\n");
		} else {
			process_mode = DECRYPTION_MODE;
			printf("Decrypting..\n");
		}

		// Get number of blocks in the file
		fseek(input_file, 0L, SEEK_END);
		file_size = ftell(input_file);

		fseek(input_file, 0L, SEEK_SET);
		number_of_blocks = file_size/8 + ((file_size%8)?1:0);

		start = clock();

		// Start reading input file, process and write to output file
		while(fread(data_block, 1, 8, input_file)) {
			block_count++;
			if (block_count == number_of_blocks) {
				if (process_mode == ENCRYPTION_MODE) {
					padding = 8 - file_size%8;
					if (padding < 8) { // Fill empty data block bytes with padding
						memset((data_block + 8 - padding), (unsigned char)padding, padding);
					}

					process_message(data_block, processed_block, key_sets, process_mode);
					bytes_written = fwrite(processed_block, 1, 8, output_file);

					if (padding == 8) { // Write an extra block for padding
						memset(data_block, (unsigned char)padding, 8);
						process_message(data_block, processed_block, key_sets, process_mode);
						bytes_written = fwrite(processed_block, 1, 8, output_file);
					}
				} else {
					process_message(data_block, processed_block, key_sets, process_mode);
					padding = processed_block[7];

					if (padding < 8) {
						bytes_written = fwrite(processed_block, 1, 8 - padding, output_file);
					}
				}
			} else {
				process_message(data_block, processed_block, key_sets, process_mode);
				bytes_written = fwrite(processed_block, 1, 8, output_file);
			}
			memset(data_block, 0, 8);
		}

		finish = clock();

		// Free up memory
		free(des_key);
		free(data_block);
		free(processed_block);
		fclose(input_file);
		fclose(output_file);

		// Provide feedback
		time_taken = (double)(finish - start)/(double)CLOCKS_PER_SEC;
		printf("Finished processing %s. Time taken: %lf seconds.\n", argv[3], time_taken);
		return 0;
	} else {
		printf("Invalid action: %s. First parameter must be [ -g | -e | -d ].", argv[1]);
		return 1;
	}

	return 0;
}
Esempio n. 21
0
int main(int argc, char *argv[])
{
	int ret;
	char base32_key[BASE32_LEN(keylen)+1];
	unsigned char uefiblob[4100];
	unsigned char blob[4096];	/* resulting sealed blob */
	unsigned int bloblen;	/* blob length */
	unsigned char wellknown[20] = {0};
	unsigned char totpstring[64];
	uint32_t pcrmask =  0x000003BF; // PCRs 0-5 and 7-9
	const char * hostname = "TPMTOTP";

	char *outfile_name;
	FILE *infile;
	FILE *outfile;
	QRcode *qrcode;
#ifdef CONFIG_TSS
	TSS_HCONTEXT context;
#endif

	if (generate_key()) {
		return -1;
	}

	pcrvals = malloc(NUM_PCRS * sizeof(uint8_t*));
	CHECK_MALLOC(pcrvals);

	static int base32_flag = 0;
	static int qr_flag = 1;
	static int nvram_flag = 0;
	int option_index = 0;

	static struct option long_options[] = {
	     {"pcrs",  required_argument, 0, 'p'},
	     {"nvram", no_argument, &nvram_flag, 1},
	     {"no-qrcode", no_argument, &qr_flag, 0},
	     {"base32", no_argument, &base32_flag, 1},
	     {"help", no_argument, 0, 'h'},
	     {0,0,0,0}

	};

	if (argc == 1) {
	     print_help();
	     return -1;
	}

	int c;

	while ((c = getopt_long(argc, argv, "p:nbh", long_options, &option_index)) != -1) {

		switch (c) {
		case 0: // Flag only
			break;

		case 'p':
			pcrmask = parse_pcrs(optarg);
			if (pcrmask == (uint32_t) -1)
				return -1;
			break;

		case 'h':
			print_help();
			return 0;

		case 'b':
			base32_flag = 1;
			break;

		case 'n':
			nvram_flag = 1;
			break;

		case 's':
			qr_flag = 0;
			break;

		case '?': // Unrecognized Option
			print_help();
			return -1;

		default:
			print_help();
		}

	}
	
	if (!nvram_flag) {
		if (optind == argc) {
			fprintf(stderr, "Output name required!\n");
			print_help();
			return -1;
		} else {
			outfile_name = argv[optind];
		}
	}

	base32_encode(key, keylen, base32_key);
	base32_key[BASE32_LEN(keylen)] = NULL;

#ifdef CONFIG_TSS
	ret = Tspi_Context_Create(&context);
	if (ret != TSS_SUCCESS) {
		fprintf(stderr, "Unable to create TPM context\n");
		return -1;
	}
	ret = Tspi_Context_Connect(context, NULL);
	if (ret != TSS_SUCCESS) {
		fprintf(stderr, "Unable to connect to TPM\n");
		return -1;
	}
	ret = TSPI_SealCurrPCR(context, // context
			      0x40000000, // SRK
			      pcrmask,
			      wellknown,  // Well-known SRK secret
			      wellknown,  // Well-known SEAL secret
			      key, keylen,	/* data to be sealed */
			      blob, &bloblen);	/* buffer to receive result */
#else
	ret = TPM_SealCurrPCR(
			      0x40000000, // SRK
			      pcrmask,
			      wellknown,  // Well-known SRK secret
			      wellknown,  // Well-known SEAL secret
			      key, keylen,	/* data to be sealed */
			      blob, &bloblen);	/* buffer to receive result */
#endif
	if (ret != 0) {
		fprintf(stderr, "Error %s from TPM_Seal\n",
			TPM_GetErrMsg(ret));
		//goto out;
	}

	sprintf(totpstring, "otpauth://totp/%s?secret=%s", hostname, base32_key);
	//sprintf(totpstring, "%s", base32_key);

	if (base32_flag) {
		printf("%s\n", base32_key);
	}

	printf("%s\n", totpstring);
	if (qr_flag) {
		qrcode = QRcode_encodeString(totpstring, 0, QR_ECLEVEL_L,
					     QR_MODE_8, 1);
		writeANSI(qrcode);
	}

	if (nvram_flag) {
		uint32_t nvindex = 0x00004d47;
		uint32_t permissions = TPM_NV_PER_OWNERREAD|TPM_NV_PER_OWNERWRITE;
#ifdef CONFIG_TSS
		TSS_HNVSTORE nvObject;
		TSS_FLAG nvattrs = 0;

		ret = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV,
						nvattrs, &nvObject);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to create nvram object: %x\n",
				ret);
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject, TSS_TSPATTRIB_NV_INDEX, 0,
					   nvindex);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set index\n");
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject,
					   TSS_TSPATTRIB_NV_PERMISSIONS, 0,
				   permissions);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set permissions\n");
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject, TSS_TSPATTRIB_NV_DATASIZE,
					   0, bloblen);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set size\n");
			goto out;
		}
		ret = Tspi_NV_DefineSpace(nvObject, NULL, NULL);
		if (ret != TSS_SUCCESS && ret != (0x3000 | TSS_E_NV_AREA_EXIST)) {
			fprintf(stderr, "Unable to define space: %x\n", ret);
			goto out;
		}
		ret = Tspi_NV_WriteValue(nvObject, 0, bloblen, blob);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to write to nvram\n");
			goto out;
		}
#else
		unsigned char * ownauth = wellknown;
		unsigned char * areaauth = wellknown;
		TPM_PCR_INFO_SHORT *pcrInfoRead = NULL;
		TPM_PCR_INFO_SHORT *pcrInfoWrite = NULL;

		ret = TPM_NV_DefineSpace2(
			ownauth,
			nvindex,
			bloblen,
			permissions,
			areaauth,
			pcrInfoRead,
			pcrInfoWrite);
		//if (ret != TPM_SUCCESS && ret != (0x3000 | TSS_E_NV_AREA_EXIST)) {
		if (ret != TPM_SUCCESS) {
			fprintf(stderr, "Unable to define space: %x\n", ret);
			goto out;
		}

		ret = TPM_NV_WriteValue(
			nvindex,
			0,
			blob,
			bloblen,
			ownauth
		);
		if (ret != TPM_SUCCESS) {
			fprintf(stderr, "Unable to write to nvram\n");
			goto out;
		}
#endif
	} else {
		outfile = fopen(outfile_name, "w");
		if (outfile == NULL) {
			fprintf(stderr, "Unable to open output file '%s'\n",
				outfile_name);
			goto out;
		}
		if (strncmp(outfile_name, efivarfs, strlen(efivarfs)) == 0) {
			int attributes = 7; // NV, RT, BS
			memcpy(uefiblob, &attributes, sizeof(int));
			memcpy(uefiblob + sizeof(int), blob, bloblen);
			bloblen += sizeof(int);
			ret = fwrite(uefiblob, 1, bloblen, outfile);
		} else {
			ret = fwrite(blob, 1, bloblen, outfile);
		}
		if (ret != bloblen) {
			fprintf(stderr,
				"I/O Error while writing output file '%s'\n",
				outfile_name);
			goto out;
		}
	}

out:

#ifdef CONFIG_TSS
	Tspi_Context_FreeMemory(context, NULL);
	Tspi_Context_Close(context);
#endif

	exit(ret);
}
Esempio n. 22
0
int main( int argc, char *argv[] )
{
	std::string inputfile  = "";
	std::string outputfile = "";
	std::string passphrase = "";
	std::string publicKey  = "";
	bool encrypt = false,
	     decrypt = false,
	     keygen  = false;

	// set up command line options and
	// check for help requests and usage errors
	po::variables_map var_map;

	try
	{
		init_program_options(argc, argv, &var_map);
	}
	catch( po::multiple_occurrences m )
	{
		std::cerr << "Error: Please use each options at most once."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}
	catch( ... )
	{
		std::cerr << "Error: unknown error in command line options."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}

	// no options -> print usage message
	if( argc == 1 )
	{
		print_usage( argv[0] );
		exit( 1 );
	}

	// check command line options
	if( var_map.count("test") > 0 )
	{
		exit( run_tests() );
	}

	encrypt = (var_map.count("encrypt")    > 0);
	decrypt = (var_map.count("decrypt")    > 0);
	keygen  = (var_map.count("create-key") > 0);

	// check that the user only request one out of decrypt/encrypt/keygen
	if( (int)decrypt + (int)encrypt + (int)keygen > 1 )
	{
		std::cerr << "You need to chose one of encrypt, decrypt and key-gen."
			  << std::endl << std::endl;
		print_usage( argv[0] );
		exit( 2 );
	}

	if (var_map.count("pass")   > 0) passphrase = var_map["pass"].as<std::string>();
	if (var_map.count("input")  > 0) inputfile  = var_map["input"].as<std::string>();
	if (var_map.count("output") > 0) outputfile = var_map["output"].as<std::string>();
	if (var_map.count("key")    > 0) publicKey  = var_map["key"].as<std::string>();
	quiet = (var_map.count("quiet") > 0);

	// here comes the program logic
	if( keygen )
	{
		if( passphrase == "" )
			passphrase = prompt_password( "passphrase", true );
	
		uint8_t publicKey[32];
		if( generate_key( publicKey, passphrase ) )
			std::cerr << "Public key: " << b64encode( publicKey );
		else
			std::cerr << "Failed to generate public key" << std::endl;
	}
	else if( encrypt )
	{
		if( inputfile == "" && publicKey == "" )
		{
			std::cerr << "Error: Public key needs to be given on "
				  << "commandline when encrypting from stdin" << std::endl;
			exit( 1 );
		}

		if( publicKey == "" )
			publicKey  = prompt_password( "public key" );

		encryptFile( outputfile, inputfile, passphrase, publicKey );
	}
	else if( decrypt )
	{
		if( inputfile == "" && passphrase == "" )
		{
			std::cerr << "Error: passphrase needs to be given on "
				  << "commandline when decrypting from stdin" << std::endl;
			exit( 1 );
		}

		if( passphrase == "" )
			passphrase = prompt_password( "passphrase", true );

		decryptFile( outputfile, inputfile, passphrase );
	}
	else
	{
		print_usage( argv[0] );
		exit( 0 );
	}

	return 0;
}
Esempio n. 23
0
int main(int argc, char **argv) {
    config_init();

    int c;
    
    while (-1 != (c = getopt(argc, argv, "n:m:k:d:p:h"))) {
        switch(c) {
            case 'n':
                config.num = atoi(optarg);
                break;
            case 'm':
                config.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024;
                break;
            case 'k':
                config.keysize = atoi(optarg);
                break;
            case 'd':
                config.datasize = atoi(optarg);
                break;
            case 'p':
                config.hashpower = atoi(optarg);
                break;
            case 'h':
                usage();
                return EXIT_SUCCESS;
            default:
                usage();
                return EXIT_FAILURE;
        }
    }

    generate_key_init();
    print_env();
    lru *l = lru_init(config.maxbytes, config.hashpower);

    char *bvalue = malloc(config.datasize);
    memset(bvalue, 'x', config.datasize);

    char *key = malloc(config.keysize);
    memset(key, 0, config.keysize);

    int gnum = config.keysize - num_;

    generate_key_reset();
    bench_start("SET");
    int i;
    for (i = 0; i < config.num; i++) {
        snprintf(key, config.keysize, fmt_, gnum, generate_key(gnum), i);
        int r = item_set(l, key, config.keysize, bvalue, config.datasize);
        assert(r == 0);
        process_report();
    }
    bench_stop();
    print_stat(l);

    char *buf = malloc(config.datasize);
    size_t sz;
    generate_key_reset();
    bench_start("GET");
    for (i = 0; i < config.num; i++) {
        snprintf(key, config.keysize, fmt_, gnum, generate_key(gnum), i);
        int r = item_get(l, key, config.keysize, buf, config.datasize, &sz);
        if (!r) {
            assert((int)sz == config.datasize);
            assert(memcmp(bvalue, buf, config.datasize) == 0);
        }
        memset(buf, 0, config.datasize);
        process_report();
    }
    bench_stop();
    print_stat(l);

    generate_key_reset();
    bench_start("DELETE");
    for (i = 0; i < config.num; i++) {
        snprintf(key, config.keysize, fmt_, gnum, generate_key(gnum), i);
        item_delete(l, key, config.keysize);
        process_report();
    }
    bench_stop();
    print_stat(l);
    
    free(buf);
    free(bvalue);
    free(key);
    free(fmt_);
    free(key_);
   
    lru_free(l);
    /*
    printf("print any key to exit...\n");
    getchar();
    */
    return EXIT_SUCCESS;
}
Esempio n. 24
0
void ConvolutionLayerSpatial<Dtype>::load_cached_kernels(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
  // Generates static key_
  std::string previous_key = key_;
  generate_key();
  if (tuned_) {
    if (key_.compare(previous_key) == 0)
      return;
    tuned_ = false;
    viennacl::ocl::current_context().
      delete_program(bestKernelConfig->kernelName);
    delete bestKernelConfig;
    bestKernelConfig = NULL;
  }
  // Initializes unique kernel ID
  kernel_uid_ = 0;

  string outputFile;
  outputFile = CACHE_DIRECTORY + key_;
  std::ifstream cachedKernel(outputFile.c_str());

  if (cachedKernel) {
    int_tp x, y, z, type;
    cachedKernel >> x;
    cachedKernel >> y;
    cachedKernel >> z;
    cachedKernel >> type;
    create_convolution_kernel(bottom, top, type, x, y, z);
    kernel_index_ = kernelQueue.size() - 1;
    if (kernel_index_ == -1) {
      std::cerr << "Failed to get kernel from cached configurations."
                << std::endl;
      std::cerr << "Deleting broken cache file and try tuning again..."
                << std::endl;
      string bakFile = outputFile + ".bak";
      std::rename(outputFile.c_str(), bakFile.c_str());
      return;
    }
    bestKernelConfig = kernelQueue[kernel_index_];
    kernelQueue.clear();
    // As we are using varying image size kernels now, let's skip the
    // cached work group size and local group size here, and we already
    // get correct work/local group size at the create_convolution kernel stage.
    // To not break the previous trained record, for now just skipping them.
    // Will use a totally different cache mechanism in the future.
    size_t foo;  // for deprecated parameters.
    cachedKernel >> foo;
    cachedKernel >> foo;
    cachedKernel >> foo;
    cachedKernel >> bestKernelConfig->local_work_size[0];
    cachedKernel >> bestKernelConfig->local_work_size[1];
    cachedKernel >> bestKernelConfig->local_work_size[2];
    if (bestKernelConfig->kernelType == 1)
      calculate_global_size(1, bestKernelConfig->workItem_output,
                            bestKernelConfig->local_work_size,
                            bestKernelConfig->global_work_size);
    cachedKernel >> bestKernelConfig->swizzle_weights;
    cachedKernel >> foo;
    cachedKernel >> bestKernelConfig->use_null_local;
    tuned_ = true;
  }
  return;
}
Esempio n. 25
0
/** Try to read the identity key from <b>identity_key_file</b>.  If no such
 * file exists and create_identity_key is set, make a new identity key and
 * store it.  Return 0 on success, nonzero on failure.
 */
static int
load_identity_key(void)
{
  file_status_t status = file_status(identity_key_file);
  FILE *f;

  if (make_new_id) {
    open_file_t *open_file = NULL;
    RSA *key;
    if (status != FN_NOENT) {
      log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
              "already exists.", identity_key_file);
      return 1;
    }
    log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
               IDENTITY_KEY_BITS);
    if (!(key = generate_key(IDENTITY_KEY_BITS))) {
      log_err(LD_GENERAL, "Couldn't generate identity key.");
      crypto_log_errors(LOG_ERR, "Generating identity key");
      return 1;
    }
    identity_key = EVP_PKEY_new();
    if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
      log_err(LD_GENERAL, "Couldn't assign identity key.");
      return 1;
    }

    if (!(f = start_writing_to_stdio_file(identity_key_file,
                                          OPEN_FLAGS_REPLACE | O_TEXT, 0400,
                                          &open_file)))
      return 1;

    /* Write the key to the file.  If passphrase is not set, takes it from
     * the terminal. */
    if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
                                       NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
                                       passphrase, (int)passphrase_len,
                                       NULL, NULL)) {
      log_err(LD_GENERAL, "Couldn't write identity key to %s",
              identity_key_file);
      crypto_log_errors(LOG_ERR, "Writing identity key");
      abort_writing_to_file(open_file);
      return 1;
    }
    finish_writing_to_file(open_file);
  } else {
    if (status != FN_FILE) {
      log_err(LD_GENERAL,
              "No identity key found in %s.  To specify a location "
              "for an identity key, use -i.  To generate a new identity key, "
              "use --create-identity-key.", identity_key_file);
      return 1;
    }

    if (!(f = fopen(identity_key_file, "r"))) {
      log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
              identity_key_file, strerror(errno));
      return 1;
    }

    /* Read the key.  If passphrase is not set, takes it from the terminal. */
    identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
    if (!identity_key) {
      log_err(LD_GENERAL, "Couldn't read identity key from %s",
              identity_key_file);
      return 1;
    }
    fclose(f);
  }
  return 0;
}
Esempio n. 26
0
void ConvolutionLayerSpatial<float>::setup_convolution(
    const vector<Blob<float>*>& bottom, const vector<Blob<float>*>& top,
    const Blob<float> &verify_blob) {
  // Generates static key_
  generate_key();
  // Initializes unique kernel ID
  kernel_uid_ = 0;

  viennacl::ocl::context &ctx = viennacl::ocl::get_context(this->device_->id());
  const viennacl::ocl::device &device = ctx.current_device();
  if (device.vendor().find("Intel") != std::string::npos &&
    M_ % 16 == 0) {
    /* IDLF kernels are using Intel specific extension which make
       them intel only. */
    int kernelCnt = 0;
    for (uint32_t width = 14; width > 0; width--) {
      int candidate = 0;
      if (width > output_w_)
        continue;
      for (uint32_t height = 14; height > 0; height--) {
        if (height * width > 32 || height > output_h_)
          continue;
        int tile_x = kernel_w_ + (width - 1) * stride_w_;
        int tile_y = kernel_h_ + (height - 1) * stride_h_;
        int tile_y_stride = 64 / tile_x;

        if (tile_x % 4 != 0 && tile_x <= 16) {
          create_convolution_kernel(bottom, top, 2, width, height, 1);
          candidate++;
        } else if ((tile_x % 4 == 0) &&
                 ((tile_y + tile_y_stride - 1) / tile_y_stride < 4)) {
          create_convolution_kernel(bottom, top, 2, width, height, 1);
          candidate++;
        }
        if (candidate >= 4 && height == 2)
          break;
      }
      kernelCnt += candidate;
      if (kernelCnt >= 12 && width == 2)
        break;
    }
  } else {
    for (int_tp y = 1; y < 4; y += 1)
      for (int_tp z = 1; z < 16 && z < M_; z += 1) {
        if (4 * y * z > 32) continue;
        create_convolution_kernel(bottom, top, 1, 4, y, z);
      }
  }
  for (int_tp x = 0; x < kernelQueue.size(); x++)
    if (tune_local_size(bottom, top, kernelQueue[x])) {
      kernelQueue[x]->executionTime = timed_convolve(bottom, top, bottom_index_,
                                                     num_, kernelQueue[x]);
    } else {
      // skip those kernels without a good local size.
      kernelQueue[x]->verified = false;
      kernelQueue[x]->tested = true;
    }

  int_tp failures = 0;
  bool verification = false;
  if (kernelQueue.size()) {
    while (failures < kernelQueue.size()) {
      int_tp fastestKernel = -1;
      float fastestTime = 999999990000000000000000000.0f;

      for (int_tp x = 0; x < kernelQueue.size(); x++) {
        if (kernelQueue[x]->executionTime < fastestTime
            && kernelQueue[x]->tested == false) {
          fastestKernel = x;
          fastestTime = kernelQueue[x]->executionTime;
        }
      }
      if (fastestKernel < 0) break;
      // Test fastest kernel
      bool verified = verify_result(bottom, top, bottom_index_, num_,
                                    verify_blob, kernelQueue[fastestKernel]);
      if (verified == true) {
        kernelQueue[fastestKernel]->verified = true;
        kernel_index_ = fastestKernel;
        verification = true;
        break;
      } else {
        kernelQueue[fastestKernel]->tested = true;
        dbgPrint(std::cout << "Kernel "
                           << kernelQueue[fastestKernel]->kernelName
                           << " failed verification" << std::endl);
        failures++;
      }
    }
  }
  if (verification) {
    dbgPrint(std::cout << "Kernel <" << kernelQueue[kernel_index_]->kernelName
                       << "> passed verification" << std::endl);
  } else {
    dbgPrint(std::cout << "Verification was not successful, "
                       << "fallback to basic kernel" << std::endl);
    create_basic_kernel(bottom, top, 1, 1, 1);
    kernel_index_ = kernelQueue.size() - 1;
    verification = verify_result(bottom, top, bottom_index_, num_,
                                 verify_blob, kernelQueue[kernel_index_]);
    CHECK_EQ(verification, true) << "Basic kernel failed verification."
                                 << std::endl;
  }
  this->bestKernelConfig = kernelQueue[kernel_index_];

  dbgPrint(std::cout << "Convolution Time:"
                     << kernelQueue[kernel_index_]->executionTime << std::endl);

  for (int_tp x = 0; x < kernelQueue.size(); x++) {
    if (x != kernel_index_) {
      viennacl::ocl::current_context().delete_program(
          kernelQueue[x]->kernelName);
      delete kernelQueue[x];
    }
  }
  kernelQueue.clear();

  tuned_ = true;

  const boost::filesystem::path& path = CACHE_DIRECTORY;
  const boost::filesystem::path& dir =
                   boost::filesystem::unique_path(path).string();
  bool hasCacheDir = false;
  if (!boost::filesystem::exists(dir))
    hasCacheDir = boost::filesystem::create_directory(dir);
  else
    hasCacheDir = boost::filesystem::is_directory(dir);

  if (hasCacheDir != true) {
    std::cout << "Failed to create cache directory,"
              << "will tune again for next running" << std::endl;
    return;
  }

  string outputFile;
  outputFile = CACHE_DIRECTORY + key_;
  std::ifstream cachedKernel(outputFile.c_str());
  std::ofstream outputKernel;
  outputKernel.open(outputFile.c_str());
  outputKernel << bestKernelConfig->workItem_output[0] << " "
               << bestKernelConfig->workItem_output[1] << " "
               << bestKernelConfig->workItem_output[2] << " "
               << bestKernelConfig->kernelType << " "
               << bestKernelConfig->global_work_size[0] << " "
               << bestKernelConfig->global_work_size[1] << " "
               << bestKernelConfig->global_work_size[2] << " "
               << bestKernelConfig->local_work_size[0] << " "
               << bestKernelConfig->local_work_size[1] << " "
               << bestKernelConfig->local_work_size[2] << " "
               << bestKernelConfig->swizzle_weights << " "
               << 0 << " "  // deprecated
               << bestKernelConfig->use_null_local << " ";
  outputKernel.close();
}
Esempio n. 27
0
void
update_keys (FILE * keys)
{
  FILE *privring, *privlock;
  char line[1024];
  long pos;
  unsigned long exp, expmax;
  int sk = 0, pk = 0, tk = 0;

  mix_lock ("secring", &privlock);
  if ((privring = try_open_mix_file (SECRING, "r+")) == NULL)
    mix_unlock ("secring", privlock);
  else
    {
      /* We're a remailer */
      expmax = time (NULL) + KEYOVERLAP * SECONDSPERDAY;
      while ((pos = next_key (privring)) != -1)
	{
	  if (keyheader (privring, pos, KEY_VERSION, line) == -1)
	    pk++;		/* permanent key, old version */
	  if ((keyheader (privring, pos, KEY_TYPE, line) != -1) &&
	      (streq (line, "sig")))
	    sk++;		/* signature key */
	  else if (keyheader (privring, pos, KEY_EXPIRES, line) == -1)
	    pk++;		/* permanent key */
	  else
	    {
	      sscanf (line, "%lu", &exp);
	      if (exp <= (unsigned long) time (NULL))
		{
		  fseek (privring, pos, SEEK_SET);
		  /* OVERWRITE UNTIL END OF KEY */
		}
	      else
		{
		  expmax = exp;
		  tk++;		/* temporary key */
		}
	    }
	}
      fclose (privring);
      mix_unlock ("secring", privlock);

#ifdef NEW
      if (sk == 0)
	generate_key (KEY_TYPE "sig\n");
#endif
      if (pk == 0)
	generate_key ("");

      for (; tk < CREATEKEYS; tk++)
	{
	  sprintf (line, KEY_VALID "%lu\n" KEY_EXPIRES "%lu\n",
		   expmax - KEYOVERLAP * SECONDSPERDAY,
		   expmax + (KEYVALIDITY - KEYOVERLAP) * SECONDSPERDAY);
	  expmax += (KEYVALIDITY - KEYOVERLAP) * SECONDSPERDAY;
	  generate_key (line);
	}
      /* write our public keys to file */
      write_keyfile ();
    }

  if (keys != NULL)
    read_key_file (keys);

  expire_pub_keys ();
}
Esempio n. 28
0
void
initialize_semaphore_set(semian_resource_t* res, const char* id_str, long permissions, int tickets, double quota)
{

  res->key = generate_key(id_str);
  res->strkey = (char*)  malloc((2 /*for 0x*/+ sizeof(uint64_t) /*actual key*/+ 1 /*null*/) * sizeof(char));
  sprintf(res->strkey, "0x%08x", (unsigned int) res->key);
  res->sem_id = semget(res->key, SI_NUM_SEMAPHORES, IPC_CREAT | IPC_EXCL | permissions);

  /*
  This approach is based on http://man7.org/tlpi/code/online/dist/svsem/svsem_good_init.c.html
  which avoids race conditions when initializing semaphore sets.
  */
  if (res->sem_id != -1) {
    // Happy path - we are the first worker, initialize the semaphore set.
    initialize_new_semaphore_values(res->sem_id, permissions);
  } else {
    // Something went wrong
    if (errno != EEXIST) {
      raise_semian_syscall_error("semget() failed to initialize semaphore values", errno);
    } else {
      // The semaphore set already exists, ensure it is initialized
      res->sem_id = wait_for_new_semaphore_set(res->key, permissions);
    }
  }

  set_semaphore_permissions(res->sem_id, permissions);

  /*
    Ensure that a worker for this process is registered.
    Note that from ruby we ensure that at most one worker may be registered per process.
  */
  if (perform_semop(res->sem_id, SI_SEM_REGISTERED_WORKERS, 1, SEM_UNDO, NULL) == -1) {
    rb_raise(eInternal, "error incrementing registered workers, errno: %d (%s)", errno, strerror(errno));
  }

  int state = 0;
  sem_meta_lock(res->sem_id); // Sets otime for the first time by acquiring the sem lock

  configure_tickets_args_t configure_tickets_args = (configure_tickets_args_t){
    .sem_id = res->sem_id,
    .tickets = tickets,
    .quota = quota,
  };
  rb_protect(
    configure_tickets,
    (VALUE)&configure_tickets_args,
    &state);

  sem_meta_unlock(res->sem_id);
  if (state) {
    rb_jump_tag(state);
  }
}

void
set_semaphore_permissions(int sem_id, long permissions)
{
  union semun sem_opts;
  struct semid_ds stat_buf;

  sem_opts.buf = &stat_buf;
  semctl(sem_id, 0, IPC_STAT, sem_opts);
  if ((stat_buf.sem_perm.mode & 0xfff) != permissions) {
    stat_buf.sem_perm.mode &= ~0xfff;
    stat_buf.sem_perm.mode |= permissions;
    semctl(sem_id, 0, IPC_SET, sem_opts);
  }
}

int
perform_semop(int sem_id, short index, short op, short flags, struct timespec *ts)
{
  struct sembuf buf = { 0 };

  buf.sem_num = index;
  buf.sem_op  = op;
  buf.sem_flg = flags;

  if (ts) {
    return semtimedop(sem_id, &buf, 1, ts);
  } else {
    return semop(sem_id, &buf, 1);
  }
}

int
get_sem_val(int sem_id, int sem_index)
{
  int ret = semctl(sem_id, sem_index, GETVAL);
  if (ret == -1) {
    rb_raise(eInternal, "error getting value of %s for sem %d, errno: %d (%s)", SEMINDEX_STRING[sem_index], sem_id, errno, strerror(errno));
  }
  return ret;
}