Ejemplo n.º 1
0
int main(int argc,char **argv)
{
	if(argc != 2)
	{
		perror("\n Error:\nCorrect Usage: Enter Password to be used");
		exit(-1);
	}

	EVP_CIPHER_CTX en,de;					/* The EVP structure which keeps track of all crypt operations see evp.h for details */
	int in, out, fd, dec;					/* fd for input and output files and random dev*/
	unsigned int pwd_len = strlen((const char *)argv[1]);			/* Length of the pwd supplied by the user */
	unsigned char *pwd =(unsigned char*) argv[1];			/* Pointer to the pwd supplied by the user */
	unsigned char salt[8];
	
	if((in = open("plain.txt",O_RDONLY)) == -1) 		 /* Opening a plain text file for encryption */
	{
		perror("\n Error,Opening file for reading::");
		exit(-1);
	}

	if((fd = open("/dev/random", O_RDONLY)) == -1)
	{
		perror("\n Error,Opening /dev/random::");
		exit(-1);
	}
	else{
		if(read(fd,salt,8) == -1)
		{
			perror("\n Error,reading from /dev/random::");
			exit(-1);
		}
	}
	
	if(aes_init(pwd,pwd_len,(unsigned char*) salt,&en,&de))		/* Generating Key and IV and initializing the EVP struct */
	{
		perror("\n Error, Cant initialize key and IV:");
		return -1;
	}

	if((out = open("encrypt.txt",O_RDWR|O_CREAT,0400|0200)) == -1)
	{
		perror("\n Error,Opening the file to be written::");
		exit(-1);
	}	
	if((dec = open("dec22.txt",O_RDWR|O_CREAT,0400|0200)) == -1)
	{
		perror("\n ERROR,Opening the file to write decrypted bytes::");
		exit(-1);
	}
	if(aes_encrypt(&en,in,out))
	{
		perror("\n ERROR,ENCRYPTING:");
		exit(-1);
	}
	else
	{
		if((lseek(out,0,SEEK_SET)) != 0)
		{
			perror("\n ERROR,lseek:");
			exit(-1);
		}
		if(aes_decrypt(&de,out,dec))
		{
			perror("\n ERROR,DECRYPTING DATA:");
			exit(-1);
		}
	}

	close(in);
	close(out);
	close(fd);
	close(dec); 
	EVP_CIPHER_CTX_cleanup(&en);
	EVP_CIPHER_CTX_cleanup(&de);
	return 0;
}
Ejemplo n.º 2
0
/**
 * \brief The main function.
 */
int main(void)
{
	uint8_t key;

	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console  */
	configure_console();

	/* Output example information */
	printf("-- AES Example --\r\n");
	printf("-- %s\n\r", BOARD_NAME);
	printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);

	/* Enable the AES module. */
	aes_get_config_defaults(&g_aes_cfg);
	aes_init(AES, &g_aes_cfg);
	aes_enable();

	/* Enable AES interrupt. */
	aes_set_callback(AES, AES_INTERRUPT_DATA_READY,
			aes_callback, 1);

	/* Display menu */
	display_menu();

	while (1) {
		scanf("%c", (char *)&key);

		switch (key) {
		case 'h':
			display_menu();
			break;

		case '1':
			printf("ECB mode encryption and decryption test.\r\n");
			ecb_mode_test();
			break;

		case '2':
			printf("CBC mode encryption and decryption test.\r\n");
			cbc_mode_test();
			break;

		case '3':
			printf("CFB128 mode encryption and decryption test.\r\n");
			cfb128_mode_test();
			break;

		case '4':
			printf("OFB mode encryption and decryption test.\r\n");
			ofb_mode_test();
			break;

		case '5':
			printf("CTR mode encryption and decryption test.\r\n");
			ctr_mode_test();
			break;

		case 'd':
			#if SAM4E
			printf(
					"ECB mode encryption and decryption test with DMA.\r\n");
			ecb_mode_test_dma();
			#else
			printf("This mode is not supported by device.\r\n");
			#endif
			break;

		case 'p':
			#if SAM4C || SAM4CP || SAM4CM
			printf(
					"ECB mode encryption and decryption test with PDC.\r\n");
			ecb_mode_test_pdc();
			#else
			printf("This mode is not supported by device.\r\n");
			#endif
			break;

		default:
			break;
		}
	}
}
Ejemplo n.º 3
0
int
cbctest(int type)
{
	unsigned char test_string[TEST_SIZE];
	char iv[CBC_MAX_IV_SIZE];

	cbc_handle_t ch;
	void *eh;
	int ret;
	int i;

	switch (type) {
	case CBC_DES3_TYPE:
		ret = des3_init(&eh);
		break;
	case CBC_AES_128_TYPE:
		ret = aes_init(&eh);
		break;
	case CBC_AES_192_TYPE:
		ret = aes_init(&eh);
		break;
	case CBC_AES_256_TYPE:
		ret = aes_init(&eh);
		break;
	default:
		(void) printf("Illegal encryption type\n");
		return (-1);
	}

	if (ret != 0) {
		(void) printf("Error initializing encryption algorithm\n");
		return (-1);
	}

	bzero(iv, CBC_MAX_IV_SIZE);

	switch (type) {
	case CBC_DES3_TYPE:
		des3_key(eh, (uint8_t *)DES3_KEY);
		cbc_makehandle(&ch, eh, DES3_KEY_SIZE, DES3_BLOCK_SIZE,
		    DES3_IV_SIZE, des3_encrypt, des3_decrypt);
		break;
	case CBC_AES_128_TYPE:
		aes_key(eh, (uint8_t *)AES_128_KEY, AES_128_KEY_SIZE);
		cbc_makehandle(&ch, eh, AES_128_KEY_SIZE, AES_BLOCK_SIZE,
		    AES_IV_SIZE, aes_encrypt, aes_decrypt);
		break;
	case CBC_AES_192_TYPE:
		aes_key(eh, (uint8_t *)AES_192_KEY, AES_192_KEY_SIZE);
		cbc_makehandle(&ch, eh, AES_192_KEY_SIZE, AES_BLOCK_SIZE,
		    AES_IV_SIZE, aes_encrypt, aes_decrypt);
		break;
	case CBC_AES_256_TYPE:
		aes_key(eh, (uint8_t *)AES_256_KEY, AES_256_KEY_SIZE);
		cbc_makehandle(&ch, eh, AES_256_KEY_SIZE, AES_BLOCK_SIZE,
		    AES_IV_SIZE, aes_encrypt, aes_decrypt);
		break;
	default:
		/* Should not happen */
		(void) printf("Illegal encryption type\n");
		return (-1);
	}

	(void) strcpy((char *)test_string, TEST);

	for (i = 0; i < TEST_SIZE; i += TEST_BLOCK_SIZE) {
		(void) cbc_encrypt(&ch, (uint8_t *)&test_string[i],
		    TEST_BLOCK_SIZE, (uint8_t *)iv);
	}

	if (strcmp((char *)test_string, TEST) == 0) {
		(void) printf("FAILED [Encryption]\n");
		goto out;
	}

	bzero(iv, CBC_MAX_IV_SIZE);

	for (i = 0; i < TEST_SIZE; i += TEST_BLOCK_SIZE) {
		(void) cbc_decrypt(&ch, (uint8_t *)&test_string[i],
		    TEST_BLOCK_SIZE, (uint8_t *)iv);
	}

	if (strcmp((char *)test_string, TEST) == 0) {
		(void) printf("PASSED\n");
	} else {
		(void) printf("FAILED [Decryption]\n");
	}

out:
	switch (type) {
	case CBC_DES3_TYPE:
		des3_fini(eh);
		break;
	case CBC_AES_128_TYPE:
	case CBC_AES_192_TYPE:
	case CBC_AES_256_TYPE:
		aes_fini(eh);
		break;
	default:
		/* Should not happen */
		(void) printf("Illegal encryption type\n");
		return (-1);
	}

	return (0);
}
int EncryptionModule::handshake_out(char *buf, size_t *datalen, size_t *buflen) {

	/* pick up where we left off in the handshake.
	   append the next portion of the handshake to buf, after whatever handshake
	   data may be ther already. */
	switch(handshake_status_) {
		case kSendClientHello:  // client-side
		{
			/* Send CLIENT HELLO */
			int hello_len = sprintf((buf+*datalen), "CLIENT HELLO");
			*datalen += hello_len;

			handshake_status_ = kWaitForServerHello;
			return 0;
		}
		case kSendServerHello:  // server-side
		{
			/* Send SERVER HELLO */
			int hello_len = sprintf((buf+*datalen), "SERVER HELLO");
			*datalen += hello_len;

			/* Send public key + temporary public key signed by long-term private key */
			//
			// Copy the following into buf:
			// keylen || key || tempkeylen || tempkey || siglen || sig
			//
			size_t offset = 0;
			char* base = buf+*datalen;

            
			int base_buflen = *buflen-*datalen;

			uint32_t keybufsize = serialize_rsa_pub_key(master_keypair_, base+sizeof(uint32_t), base_buflen-offset-sizeof(uint32_t));
			uint32_t* keybufsizeptr = (uint32_t*)base;
			*keybufsizeptr = keybufsize;
			offset += (sizeof(uint32_t) + keybufsize);

			uint32_t tempkeybufsize = serialize_rsa_pub_key(session_keypair_, base+sizeof(uint32_t)+offset, base_buflen-offset-sizeof(uint32_t));
			uint32_t* tempkeybufsizeptr = (uint32_t*)(base+offset);
			*tempkeybufsizeptr = tempkeybufsize;
			offset += (sizeof(uint32_t) + tempkeybufsize);

			uint32_t siglen = sign(master_keypair_, base, offset, base+offset+sizeof(uint32_t), base_buflen-offset-sizeof(uint32_t));
			uint32_t* siglenptr = (uint32_t*)(base+offset);
			*siglenptr = siglen;
			offset += sizeof(uint32_t);
			offset += siglen;

			*datalen += offset;

			DBGF("Sent keys (%lu bytes)\n\tkeylen: %d\n\ttempkeylen: %d\n\tsiglen:%d", offset, keybufsize, tempkeybufsize, siglen);


			/* Send SERVER (hello) DONE */
			int done_len = sprintf((buf+*datalen), "SERVER DONE");
			*datalen += done_len;

			handshake_status_ = kWaitForPreMasterSecret;
			return 0;
		}


		case kSendPreMasterSecret:  // client-side
		{
			// We can start adding data at base
			char* base = buf+*datalen;
			int base_buflen = *buflen-*datalen;

			/* Generate pre-master secret and send to server, encrypted with session_pub_key_ */
			unsigned char* pms = (unsigned char*)malloc(PRE_MASTER_SECRET_LENGTH);
    		if (RAND_bytes(pms, PRE_MASTER_SECRET_LENGTH) != 1) {
    		    ERROR("ERROR: Couldn't generate pre-master secret");
				return ERR_GENERIC;
    		}
			if (VERBOSITY >= V_DEBUG) {
				DBG("Pre-Master Secret:");
				//print_bytes(pms, PRE_MASTER_SECRET_LENGTH);
			}

			int ciphertext_len;
			if ( (ciphertext_len = pub_encrypt(session_pub_key_, 
									pms, PRE_MASTER_SECRET_LENGTH, 
									base, base_buflen)) == -1 ) {
				ERROR("ERROR: Unable to encrypt session key");
				return ERR_GENERIC;
			}

			*datalen += ciphertext_len;
    		


			/* Init symmetric session ciphers with pre-master secret.
			   Client encrypt context initialized with same key data as
			   server decrypt context and vice versa. */
			uint32_t salt[] = SALT;
			if (aes_init(pms, PRE_MASTER_SECRET_LENGTH/2, 
						 &pms[PRE_MASTER_SECRET_LENGTH/2], PRE_MASTER_SECRET_LENGTH/2, 
						 (unsigned char *)&salt, en_, de_)) {
				ERROR("ERROR initializing AES ciphers");
				return ERR_GENERIC;
			}
			free(pms);


			/* done with handshake */
			handshake_status_ = kDone;
			handshake_done_ = true;
			ready_ = true;
			return 0;
		}
		default:
			ERROR("Unknown handshake status\n");
            //printf("handshake status: %d\n", handshake_status_);
			return ERR_GENERIC;
	}
}
int EncryptionModule::handshake_in(char *buf, size_t *datalen, size_t *buflen) {
    (void)buflen;

	/* pick up where we left off in the handshake */
	switch(handshake_status_) {
		case kWaitForClientHello: // server-side
		{
			/* make sure the data is a complete client hello */
			if (strncmp("CLIENT HELLO", buf, 12) != 0) {
				ERROR("ERROR: received message was not CLIENT HELLO\n");
				return ERR_NEED_MORE_DATA;
			} else {
				// FIXME: inefficient!
				// int hello_len = strlen("CLIENT HELLO");
				// char* newbuf = (char*)malloc(*buflen);
				// memcpy(newbuf, buf+hello_len, *datalen-hello_len);
				// *datalen -= hello_len;
				// free(buf);
				// buf = newbuf;  // FIXME: need pointer to pointer

				handshake_status_ = kSendServerHello;
				return 0;
			}
			
		}


		case kWaitForServerHello:  // client-side
		{
			/* Wait for SERVER HELLO */
			// Receive public key + temporary public key signed by server's long-term private key
			// Continue receiving until we see "SERVER DONE"
			
			// FIXME: this assumes there's no handshake data after us!
			if (*datalen < 11 || strcmp("SERVER DONE", (buf+*datalen-11)) != 0) {
				ERROR("Did not receive complete SERVER DONE. Waiting for more data\n");
				return ERR_NEED_MORE_DATA;
			}

			/* Parse public keys from SERVER HELLO */
			int offset = strlen("SERVER HELLO");
			char *keys = buf+offset;  // start of signed portion of message

			uint32_t *keybufsizeptr = (uint32_t*)(buf+offset);
			uint32_t keybufsize = *keybufsizeptr; // TODO: error checking here
			offset += sizeof(uint32_t);
			RSA *pubkey = deserialize_rsa_pub_key(buf+offset, keybufsize);
			offset += keybufsize;

			uint32_t *tempkeybufsizeptr = (uint32_t*)(buf+offset);
			uint32_t tempkeybufsize = *tempkeybufsizeptr;
			offset += sizeof(uint32_t);
			session_pub_key_ = deserialize_rsa_pub_key(buf+offset, tempkeybufsize);
			offset += tempkeybufsize;

			uint32_t *siglenptr = (uint32_t*)(buf+offset);
			uint32_t siglen = *siglenptr;
			offset += sizeof(uint32_t);
			char* sig = buf+offset;
			offset += siglen;
			DBGF("Received keys:\n\tkeylen: %d\n\ttempkeylen: %d\n\tsiglen: %d", keybufsize, tempkeybufsize, siglen);

			/* Verify two things:
			 *	1) in the real world, verify the key in the cert
			 *	2) verify the sig so we trust the temp key
			 */
			if (verify(pubkey, keys, keybufsize+tempkeybufsize+2*sizeof(uint32_t), sig, siglen) != 1) {
				WARN("Unable to verify signature on temporary RSA keypair! Closing connection.");
				return ERR_GENERIC;
			}

			// FIXME: inefficient!
			// char* newbuf = (char*)malloc(*buflen);
			// int used_len = offset + strlen("SERVER DONE");
			// memcpy(newbuf, buf+used_len, *datalen-used_len);
			// *datalen -= used_len;
			// free(buf);
			// buf = newbuf; // FIXME need pointer to pointer

			handshake_status_ = kSendPreMasterSecret;
			return 0;
		}


		case kWaitForPreMasterSecret:  // server-side
		{
			/* Receive and decrypt pre-master secret */
			size_t expecting = RSA_size(session_keypair_); // TODO: have client send key size?
			if (*datalen < expecting) {
				WARN("Did not receive full PMS. Waiting for more data.\n");
				return ERR_NEED_MORE_DATA;
			}


			unsigned char* pms = (unsigned char*)malloc(RSA_size(session_keypair_));
			int plaintext_len;
			if ( (plaintext_len = priv_decrypt(session_keypair_, 
									pms, RSA_size(session_keypair_), 
									(unsigned char*)buf, *datalen)) == -1) {  // FIXME what if there's more data for modules above us?
				ERROR("ERROR decrypting session key");
				return ERR_GENERIC;
			}
			if (plaintext_len != PRE_MASTER_SECRET_LENGTH) {
				ERROR("Decrypted key material is not of size PRE_MASTER_SECRET_LENGTH");
				return ERR_GENERIC;
			}
			if (VERBOSITY >= V_DEBUG) {
				DBG("Pre_Master Secret:");
				//print_bytes(pms, PRE_MASTER_SECRET_LENGTH);
			}


			/* Init symmetric session ciphers with pre-master secret.
			   Client encrypt context initialized with same key data as
			   server decrypt context and vice versa. */
			uint32_t salt[] = SALT;
			if (aes_init(&pms[PRE_MASTER_SECRET_LENGTH/2], PRE_MASTER_SECRET_LENGTH/2, 
						 pms, PRE_MASTER_SECRET_LENGTH/2, 
						 (unsigned char *)&salt, en_, de_)) {
				ERROR("ERROR initializing AES ciphers");
				return ERR_GENERIC;
			}
			free(pms);
			

			/* remove our handshake data before next module gets buf */
			// FIXME: inefficient!
			// char* newbuf = (char*)malloc(*buflen);
			// memcpy(newbuf, buf+expecting, *datalen-expecting);
			// *datalen -= expecting;
			// free(buf);
			// buf = newbuf; // FIXME need pointer to pointer


			/* done with handshake */
			handshake_status_ = kDone;
			handshake_done_ = true;
			ready_ = true;
			return 0;
		}
		default:
			ERROR("Unknown handshake status\n");
            //printf("handshake status: %d\n", handshake_status_);
			return ERR_GENERIC;
	}

}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{   int do_cmp, tyf[4], kf[3], ki;
    f_ectx alg[1];

#if defined(DLL_IMPORT) && defined(DLL_DYNAMIC_LOAD)
    HINSTANCE   h_dll;
    if(!(h_dll = init_dll(&fn)))
        return -1;
#else
    aes_init();
#endif

    if(argc == 1)
    {
        printf("\nusage: aes_gav /t:[knec] /k:[468] [/c]");
        printf("\n");
        printf("\nwhere the symbols in square brackets can be used in");
        printf("\nany combination (without the brackets) and have the");
        printf("\nfollowing meanings:");
        printf("\n");
        printf("\n        /t:[knec]   selects which tests are used");
        printf("\n        /k:[468]    selects the key lengths used");
        printf("\n        /c          compares output with reference");
        printf("\nwhere:");
        printf("\n        k: generate ECB Known Answer Test files");
        printf("\n        n: generate ECB Known Answer Test files (new)");
        printf("\n        e: generate ECB Monte Carlo Test files");
        printf("\n        c: generate CBC Monte Carlo Test files");
        printf("\n");
        printf("\nand the characters giving block and key lengths are");
        printf("\ndigits representing the lengths in 32-bit units.\n\n");
        exit(0);
    }

    printf("\nRun tests for the AES algorithm %s",

#if defined(DLL_IMPORT)
    " (DLL Version)\n");
#elif defined(AES_CPP)
    " (CPP Version)\n");
#else
    "");
#endif

    do_cmp = test_args(argc, argv, 'c', '\0');

    tyf[0] = test_args(argc, argv, 't', 'k');
    tyf[1] = test_args(argc, argv, 't', 'n');
    tyf[2] = test_args(argc, argv, 't', 'e');
    tyf[3] = test_args(argc, argv, 't', 'c');

    kf[0] = test_args(argc, argv, 'k', '4');
    kf[1] = test_args(argc, argv, 'k', '6');
    kf[2] = test_args(argc, argv, 'k', '8');

    if(!(kf[0] || kf[1] || kf[2]))
    {
        kf[0] = kf[1] = kf[2] = TRUE;   // AES key sizes if not specified
    }

    for(ki = 0; ki < 3; ++ki) if(kf[ki])
    {
        do_tests(do_cmp, tyf, alg, 16, 16 + 8 * ki);
    }

#if defined(DLL_IMPORT) && defined(DLL_DYNAMIC_LOAD)
    if(h_dll) FreeLibrary(h_dll);
#endif
    printf("\n\n");
    return 0;
}
Ejemplo n.º 7
0
int main( int argc, char *argv[] )
{
    int keysize, i;
    unsigned char tmp[200];
    char title[TITLE_LEN];
    todo_list todo;

    if( argc == 1 )
        memset( &todo, 1, sizeof( todo ) );
    else
    {
        memset( &todo, 0, sizeof( todo ) );

        for( i = 1; i < argc; i++ )
        {
            if( strcmp( argv[i], "md4" ) == 0 )
                todo.md4 = 1;
            else if( strcmp( argv[i], "md5" ) == 0 )
                todo.md5 = 1;
            else if( strcmp( argv[i], "ripemd160" ) == 0 )
                todo.ripemd160 = 1;
            else if( strcmp( argv[i], "sha1" ) == 0 )
                todo.sha1 = 1;
            else if( strcmp( argv[i], "sha256" ) == 0 )
                todo.sha256 = 1;
            else if( strcmp( argv[i], "sha512" ) == 0 )
                todo.sha512 = 1;
            else if( strcmp( argv[i], "arc4" ) == 0 )
                todo.arc4 = 1;
            else if( strcmp( argv[i], "des3" ) == 0 )
                todo.des3 = 1;
            else if( strcmp( argv[i], "des" ) == 0 )
                todo.des = 1;
            else if( strcmp( argv[i], "aes_cbc" ) == 0 )
                todo.aes_cbc = 1;
            else if( strcmp( argv[i], "aes_gcm" ) == 0 )
                todo.aes_gcm = 1;
            else if( strcmp( argv[i], "aes_ccm" ) == 0 )
                todo.aes_ccm = 1;
            else if( strcmp( argv[i], "camellia" ) == 0 )
                todo.camellia = 1;
            else if( strcmp( argv[i], "blowfish" ) == 0 )
                todo.blowfish = 1;
            else if( strcmp( argv[i], "havege" ) == 0 )
                todo.havege = 1;
            else if( strcmp( argv[i], "ctr_drbg" ) == 0 )
                todo.ctr_drbg = 1;
            else if( strcmp( argv[i], "hmac_drbg" ) == 0 )
                todo.hmac_drbg = 1;
            else if( strcmp( argv[i], "rsa" ) == 0 )
                todo.rsa = 1;
            else if( strcmp( argv[i], "dhm" ) == 0 )
                todo.dhm = 1;
            else if( strcmp( argv[i], "ecdsa" ) == 0 )
                todo.ecdsa = 1;
            else if( strcmp( argv[i], "ecdh" ) == 0 )
                todo.ecdh = 1;
            else if( strcmp( argv[i], "tts" ) == 0 )
                todo.tts = 1;
            else if( strcmp( argv[i], "rainbow" ) == 0 )
                todo.rainbow = 1;
            else
            {
                printf( "Unrecognized option: %s\n", argv[i] );
                printf( "Available options: " OPTIONS );
            }
        }
    }

    printf( "\n" );

    memset( buf, 0xAA, sizeof( buf ) );
    memset( tmp, 0xBB, sizeof( tmp ) );

#if defined(POLARSSL_MD4_C)
    if( todo.md4 )
        TIME_AND_TSC( "MD4", md4( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_MD5_C)
    if( todo.md5 )
        TIME_AND_TSC( "MD5", md5( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_RIPEMD160_C)
    if( todo.ripemd160 )
        TIME_AND_TSC( "RIPEMD160", ripemd160( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA1_C)
    if( todo.sha1 )
        TIME_AND_TSC( "SHA-1", sha1( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA256_C)
    if( todo.sha256 )
        TIME_AND_TSC( "SHA-256", sha256( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_SHA512_C)
    if( todo.sha512 )
        TIME_AND_TSC( "SHA-512", sha512( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_ARC4_C)
    if( todo.arc4 )
    {
        arc4_context arc4;
        arc4_init( &arc4 );
        arc4_setup( &arc4, tmp, 32 );
        TIME_AND_TSC( "ARC4", arc4_crypt( &arc4, BUFSIZE, buf, buf ) );
        arc4_free( &arc4 );
    }
#endif

#if defined(POLARSSL_DES_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.des3 )
    {
        des3_context des3;
        des3_init( &des3 );
        des3_set3key_enc( &des3, tmp );
        TIME_AND_TSC( "3DES",
                des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
        des3_free( &des3 );
    }

    if( todo.des )
    {
        des_context des;
        des_init( &des );
        des_setkey_enc( &des, tmp );
        TIME_AND_TSC( "DES",
                des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
        des_free( &des );
    }
#endif

#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.aes_cbc )
    {
        aes_context aes;
        aes_init( &aes );
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            aes_setkey_enc( &aes, tmp, keysize );

            TIME_AND_TSC( title,
                aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
        }
        aes_free( &aes );
    }
#endif
#if defined(POLARSSL_GCM_C)
    if( todo.aes_gcm )
    {
        gcm_context gcm;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-GCM-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            gcm_init( &gcm, POLARSSL_CIPHER_ID_AES, tmp, keysize );

            TIME_AND_TSC( title,
                    gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp,
                        12, NULL, 0, buf, buf, 16, tmp ) );

            gcm_free( &gcm );
        }
    }
#endif
#if defined(POLARSSL_CCM_C)
    if( todo.aes_ccm )
    {
        ccm_context ccm;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-CCM-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            ccm_init( &ccm, POLARSSL_CIPHER_ID_AES, tmp, keysize );

            TIME_AND_TSC( title,
                    ccm_encrypt_and_tag( &ccm, BUFSIZE, tmp,
                        12, NULL, 0, buf, buf, tmp, 16 ) );

            ccm_free( &ccm );
        }
    }
#endif
#endif

#if defined(POLARSSL_CAMELLIA_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.camellia )
    {
        camellia_context camellia;
        camellia_init( &camellia );
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "CAMELLIA-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            camellia_setkey_enc( &camellia, tmp, keysize );

            TIME_AND_TSC( title,
                    camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT,
                        BUFSIZE, tmp, buf, buf ) );
        }
        camellia_free( &camellia );
    }
#endif

#if defined(POLARSSL_BLOWFISH_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.blowfish )
    {
        blowfish_context blowfish;
        blowfish_init( &blowfish );

        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "BLOWFISH-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            blowfish_setkey( &blowfish, tmp, keysize );

            TIME_AND_TSC( title,
                    blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE,
                        tmp, buf, buf ) );
        }

        blowfish_free( &blowfish );
    }
#endif

#if defined(POLARSSL_HAVEGE_C)
    if( todo.havege )
    {
        havege_state hs;
        havege_init( &hs );
        TIME_AND_TSC( "HAVEGE", havege_random( &hs, buf, BUFSIZE ) );
        havege_free( &hs );
    }
#endif

#if defined(POLARSSL_CTR_DRBG_C)
    if( todo.ctr_drbg )
    {
        ctr_drbg_context ctr_drbg;

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        TIME_AND_TSC( "CTR_DRBG (NOPR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON );
        TIME_AND_TSC( "CTR_DRBG (PR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );
        ctr_drbg_free( &ctr_drbg );
    }
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
	void* handle;
	char* error;
	EVP_CIPHER_CTX en, de;
	unsigned int salt[] = {12345, 54321};
	unsigned char *key_data;
	FILE *fp;
	int key_data_len, i;
	char *input[] = {"Welcome Back Master! Unlocking.",NULL};
	char *plaintext;
	unsigned char *ciphertext;
	int olen, len;
	long (*ReaderOpen)(void);
	long (*ReaderClose)(void);
	long (*LinearWrite)(PBYTE, short, short, short*, unsigned char, unsigned char); 

	if (argc != 2) 
	{
		printf("Please enter a 32-byte key string as parameter\n");
		return -1;
	}
	if (strlen(argv[1]) != 32)
	{
		printf("Please enter a 32-byte key string as parameter\n");
		return -1;
	}
	
	key_data = (unsigned char *)argv[1];
	key_data_len = strlen(argv[1]);
  
	if (aes_init(key_data, key_data_len, (unsigned char *)&salt, &en, &de)) 
	{
		printf("Couldn't initialize AES cipher\n");
		return -1;
	}

	olen = len = strlen(input[0])+1;
   	ciphertext = aes_encrypt(&en, (unsigned char *)input[0], &len);

    	fp = fopen("/etc/MyAuth", "w");
	if (!fp)
	{
		printf("Failed to open MyAuth file. Are you running as root?\n");
		return -1;
	}

	fwrite(ciphertext, 1, 48, fp);
	fclose(fp);
	
	printf("MyAuth file has been created successfully\n");

	handle = dlopen ("/usr/local/lib/libuFCoder1x64.so", RTLD_LAZY);
	error = dlerror ();
	if (error) 
	{
		printf("libuFCoder1x64 library not found.\n");
		return -1;
	}

	ReaderOpen = dlsym (handle, "ReaderOpen");
	error = dlerror ();
	if (error)
	{
		printf ("Unable to find ReaderOpen function. Wrong library?\n", error);
		return -1;
	}


	i = ReaderOpen();
	if (i != 0)
	{	
		printf("\nUnable to open reader, error: %d\n", i);
		return -1;
	}

	LinearWrite = dlsym (handle, "LinearWrite");
	
	error = dlerror ();
	if (error)
	{
		printf ("Unable to find LinearWrite function. Wrong library?\n", error);
		return -1;
	}
	short bytesret;
	BYTE DataBuf[753];
	for (i=0;i<32;i++)
		DataBuf[i] = argv[1][i];
	DataBuf[32]=0x00;
	i = LinearWrite(DataBuf, 0, 32, &bytesret, 0x60, 0);
	if (i== 0)
	{
		printf("\nKey written to RFID card successfully!\n");
		printf("\nNow compile and install NFCMyAuth module\n");
		printf("\nThen add \"auth required NFCMyAuth.so\" into PAM file\n");
	}
	else
		printf("\nFailed to write to card! Error: %d\n", i);
	ReaderClose = dlsym (handle, "ReaderClose");
	ReaderClose();
	free(ciphertext);

	EVP_CIPHER_CTX_cleanup(&en);
	EVP_CIPHER_CTX_cleanup(&de);
	return 0;
}