unsigned char *bf_str_encrypt(unsigned char * str)
{

    if(!strlen(str))
        return ".";

    unsigned char *ptr=str;
    unsigned char *encrypt=(unsigned char *)malloc(sizeof(char)*512);
    unsigned char *tmp=(unsigned char *)malloc(sizeof(char)*9);
    unsigned char *out = calloc(9, sizeof(unsigned char *));

    BF_KEY *key = calloc(9, 9);
    BF_set_key(key, SIZE, (const unsigned char*)"TestKey" );

    unsigned int jmp=0,counter=0;

    bzero(encrypt,512);

    while(*ptr != '\0' && counter != 512)
    {
        *(tmp+jmp)=*ptr;
        if(jmp==7)
        {
            BF_ecb_encrypt(tmp, out, key, BF_ENCRYPT);
            strcat(encrypt,out);
            bzero(out,9);
            bzero(tmp,9);
            jmp=-1;
        }
        ptr++;
        jmp++;
        counter++;
    }

    if(strlen(tmp)<=8)
    {
        bzero(out,9);
        while(strlen(tmp)<7)
            strcat(tmp,".");
        BF_ecb_encrypt(tmp, out, key, BF_ENCRYPT);
        strcat(encrypt,out);
    }


    bzero(out,9);
    bzero(tmp,9);
    if(out)
        free(out);
    if(tmp)
        free(tmp);

    fprintf(stdout,"Result %s\n",encrypt);

    return encrypt;
}
Beispiel #2
0
int main(void)
{
    int     i;
    BF_KEY  key;
    BIO*    bio_out;

    static unsigned char key_data[BF_KEY_LENGTH] = {
        0x52,0x69,0xf1,0x49,0xd4,0x1b,0xa0,0x15,
        0x24,0x97,0x57,0x4d,0x7f,0x15,0x31,0x25
    };

    unsigned char   ciphertext[BF_BLOCK];
    unsigned char   plaintext[BF_BLOCK];

    /* Open SSL's DES ECB encrypt/decrypt function only handles 8 bytes of data */
    char* data_to_encrypt = "8 Bytes.";

    /* set the key structure using the predefined key */
    BF_set_key(&key, BF_KEY_LENGTH, key_data);

    BF_ecb_encrypt(data_to_encrypt, ciphertext, &key, BF_ENCRYPT); 

    bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);

    BIO_printf(bio_out, "Original plaintext: %s\n", data_to_encrypt);

    BIO_printf(bio_out, "Ciphertext: ");

    /* print out the ciphertext */
    for (i = 0; i < BF_BLOCK; i++)
        BIO_printf(bio_out, "%02x", ((unsigned char*)ciphertext)[i]);

    BIO_printf(bio_out, "\n");

    /* start the decryption process */
    BF_ecb_encrypt(ciphertext, plaintext, &key, BF_DECRYPT);

    BIO_printf(bio_out, "Recovered plaintext: ");
    
    /* print out the plaintext */
    for (i = 0; i < BF_BLOCK; i++)
        BIO_printf(bio_out, "%c", ((unsigned char*)plaintext)[i]);

    BIO_printf(bio_out, "\n");

    BIO_free(bio_out);

	free(ciphertext);
	free(plaintext);
   
    return 0;

}
unsigned char *bf_str_decrypt(unsigned char * str)
{
    if(!strlen(str))
        return ".";

    unsigned char *ptr=str;
    unsigned char *decrypt=(unsigned char *)malloc(sizeof(char)*512);
    unsigned char *tmp=(unsigned char *)malloc(sizeof(char)*9);
    unsigned char *out = calloc(9, sizeof(unsigned char *));


    BF_KEY *key = calloc(9, 9);
    BF_set_key(key, SIZE, (const unsigned char*)"TestKey" );

    unsigned int jmp=0,counter=0;

    bzero(decrypt,512);

    while(*ptr != '\0' && counter != 511)
    {
        *(tmp+jmp)=*ptr;
        if(jmp==7)
        {
            BF_ecb_encrypt(tmp, out, key, BF_DECRYPT);
            strcat(decrypt,out);
            bzero(out,9);
            bzero(tmp,9);
            jmp=-1;
        }
        ptr++;
        jmp++;
        counter++;
    }

    if( jmp > 0 && jmp < 8)
    {
        BF_ecb_encrypt(tmp, out, key, BF_DECRYPT);
        strcat(decrypt,out);
    }

    bzero(out,9);
    bzero(tmp,9);

    if(out)
        free(out);
    if(tmp)
        free(tmp);

    return decrypt;

}
void SRNG_bytes(
	struct SRNG_st *st,
	void *buf,
	unsigned int n)
{
	unsigned char *out = buf, *src, *dst;

	while(1) {
		/*
		 * this swaps src and dst to point to differenct halves of st->rnd on
		 * each iteration. st->idx is either 0 or BLOCK_SIZE. it is initialized
		 * to 0 in SRNG_init.
		 */
		src = st->rnd + st->idx;
		dst = st->rnd + (BLOCK_SIZE - st->idx);
		st->idx = BLOCK_SIZE - st->idx;

		BF_ecb_encrypt(src, dst, &st->key, BF_ENCRYPT);

		if(n < BLOCK_SIZE) {
			memcpy(out, dst, n);
			break;
		}

		memcpy(out, dst, BLOCK_SIZE);
		n -= BLOCK_SIZE; out += BLOCK_SIZE;
	}
}
Beispiel #5
0
/*
 * Check if strong crypto is supported. Some openssl installations
 * support only short keys and unfortunately BF_set_key does not return any
 * error value. This function tests if is possible to use strong key.
 */
static int
bf_check_supported_key_len(void)
{
	static const uint8 key[56] = {
		0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69,
		0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, 0x00, 0x11, 0x22, 0x33,
		0x44, 0x55, 0x66, 0x77, 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd,
		0x3b, 0x2f, 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76,
		0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e, 0xff, 0xff,
		0xff, 0xff, 0xff, 0xff, 0xff, 0xff
	};

	static const uint8 data[8] = {0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};
	static const uint8 res[8] = {0xc0, 0x45, 0x04, 0x01, 0x2e, 0x4e, 0x1f, 0x53};
	static uint8 out[8];

	BF_KEY		bf_key;

	/* encrypt with 448bits key and verify output */
	BF_set_key(&bf_key, 56, key);
	BF_ecb_encrypt(data, out, &bf_key, BF_ENCRYPT);

	if (memcmp(out, res, 8) != 0)
		return 0;				/* Output does not match -> strong cipher is
								 * not supported */
	return 1;
}
Beispiel #6
0
/* Returned string must be freed when done with it! */
int encrypt_string(const char *key, const char *str, char *dest, int len)
{
	BF_KEY bf_key;

	if ( !key || !key[0] )
		return 0;

	BF_set_key(&bf_key, strlen(key), (const unsigned char *)key);

	while( len > 0 ) {
		const size_t blocksize = len < 8 ? len : BF_BLOCK;
		unsigned char block[BF_BLOCK] = {0}; /* pad with zero */
		uint32_t v;
		size_t i;

		memcpy(block, str, blocksize);
		BF_ecb_encrypt(block, block, &bf_key, BF_ENCRYPT);

		for(v = load32_be(block + 4), i = 0; i < 6; ++i) {
			*dest++ = B64[v&0x3f];
			v >>= 6;
		}

		for(v = load32_be(block + 0), i = 0; i < 6; ++i) {
			*dest++ = B64[v&0x3f];
			v >>= 6;
		}

		len -= blocksize;
		str += blocksize;
	}

	*dest++ = 0;
	return 1;
}
Beispiel #7
0
//-------------------------------------------------------------------------------------
int KBEBlowfish::decrypt( const unsigned char * src, unsigned char * dest,
	int length )
{
	if (length % BLOCK_SIZE != 0)
	{
		ERROR_MSG(fmt::format("Blowfish::decrypt:"
			"Input stream size ({}) is not a multiple of the block size ({})\n",
			length, (int)(BLOCK_SIZE)));

		return -1;
	}

	uint64 * pPrevBlock = NULL;
	for (int i=0; i < length; i += BLOCK_SIZE)
	{
		BF_ecb_encrypt(src + i, dest + i, this->pBlowFishKey(), BF_DECRYPT);

		if (pPrevBlock)
		{
			*(uint64*)(dest + i) ^= *pPrevBlock;
		}

		pPrevBlock = (uint64*)(dest + i);
	}

	return length;
}
Beispiel #8
0
//-------------------------------------------------------------------------------------
int KBEBlowfish::encrypt( const unsigned char * src, unsigned char * dest,
	int length )
{
	// BLOCK_SIZEµÄÕûÊý±¶
	if(length % BLOCK_SIZE != 0)
	{
		CRITICAL_MSG(fmt::format("Blowfish::encrypt: "
			"Input length ({}) is not a multiple of block size ({})\n",
			length, (int)(BLOCK_SIZE)));
	}

	uint64 * pPrevBlock = NULL;
	for (int i=0; i < length; i += BLOCK_SIZE)
	{
		if (pPrevBlock)
		{
			*(uint64*)(dest + i) = *(uint64*)(src + i) ^ (*pPrevBlock);
		}
		else
		{
			*(uint64*)(dest + i) = *(uint64*)(src + i);
		}

		BF_ecb_encrypt(dest + i, dest + i, this->pBlowFishKey(), BF_ENCRYPT);
		pPrevBlock = (uint64*)(src + i);
	}

	return length;
}
Beispiel #9
0
void BlowfishFilter::encrypt(uint8 *buf, MessageLengthEx len)
{
	if (len % BLOCK_SIZE != 0)
	{
		ERROR_MSG("BlowfishFilter::encrypt: Input length (%d) is not a multiple of block size ", len);
		return;
	}

	uint8* data = buf;
	uint64 prevBlock = 0;
	for (uint32 i = 0; i < len; i += BLOCK_SIZE)
	{
		if (prevBlock != 0)
		{
			uint64 oldValue = *(uint64*)(data + i);
			*(uint64*)(data + i) = *(uint64*)(data + i) ^ (prevBlock);
			prevBlock = oldValue;
		}
		else
		{
			prevBlock = *(uint64*)(data + i);
		}

		BF_ecb_encrypt(data + i, data + i, this->pBlowFishKey(), BF_ENCRYPT);
	}
}
Beispiel #10
0
void makeEncryptKey(CFStringRef pass)
{
	UInt32				passLen;
	unsigned char		*passData;

	SecKeychainItemRef	itemRef=NULL;
	SecKeychainRef		sysChain;
	OSStatus			secRes;
	
	BF_KEY				temp_key;
	unsigned char		encrypt_key[8];	
	
	if ((secRes = SecKeychainOpen(SYSTEM_KEYCHAIN, &sysChain)) != 0)
	{
		syslog(LOG_ERR,"Couldn't get system keychain: %d\n",secRes);
		exit(-1);
	}

	if ((secRes = SecKeychainFindGenericPassword(sysChain, strlen(SECRET_SERVICENAME), SECRET_SERVICENAME, 0, NULL, &passLen, (void**)&passData, &itemRef))!=0)
	{
		syslog(LOG_ERR,"Error finding secret in keychain (%d). Failing",secRes);
		exit(-1);
	}
	
	BF_set_key(&temp_key,passLen,passData);
	BF_ecb_encrypt((const unsigned char*)CFStringGetCStringPtr(pass,CFStringGetFastestEncoding(pass)),encrypt_key,&temp_key,BF_ENCRYPT);
	BF_set_key(&encrypt_bf_key,8,encrypt_key);	
	return;
}
Beispiel #11
0
static int
esp_blowfish_blockencrypt(const struct esp_algorithm *algo,
                          struct secasvar *sav, u_int8_t *s, u_int8_t *d)
{

    BF_ecb_encrypt(s, d, (BF_KEY *)sav->sched, 1);
    return 0;
}
Beispiel #12
0
 void Blowfish::crypt(unsigned char * data, size_t len, MODE mode) const {
     unsigned char * _data = new unsigned char[BLOCK_LENGHT];
     for (int i = 0; i < len; i+=BLOCK_LENGHT) {
         BF_ecb_encrypt(data + i, _data, m_key, mode == ENCRYPT ? BF_ENCRYPT : BF_DECRYPT);
         memcpy(data + i, _data, BLOCK_LENGHT);
     }
     delete [] _data;
 }
Beispiel #13
0
static int test_bf_ecb(int n)
{
    int ret = 1;
    BF_KEY key;
    unsigned char out[8];

    BF_set_key(&key, 8, ecb_data[n]);

    BF_ecb_encrypt(&(plain_data[n][0]), out, &key, BF_ENCRYPT);
    if (!TEST_mem_eq(&(cipher_data[n][0]), BF_BLOCK, out, BF_BLOCK))
        ret = 0;

    BF_ecb_encrypt(out, out, &key, BF_DECRYPT);
    if (!TEST_mem_eq(&(plain_data[n][0]), BF_BLOCK, out, BF_BLOCK))
        ret = 0;

    return ret;
}
Beispiel #14
0
void decrypt_chal(char *chal, char *pwd)
{ 
   register int i;
   BF_KEY key;

   BF_set_key(&key, 16, MD5(pwd,strlen(pwd),NULL));

   for(i=0; i < VTUN_CHAL_SIZE; i += 8 )
      BF_ecb_encrypt(chal + i,  chal + i, &key, BF_DECRYPT);
}
int main()
{
    unsigned char *in = (unsigned char *)"TestData";
    unsigned char *out = calloc(1024, sizeof(unsigned char *));
    unsigned char *out2 = calloc(1024, sizeof(unsigned char *));

    unsigned char *out3 = calloc(1024, sizeof(unsigned char *));
    BF_KEY *key = calloc(256, 256);

    /* set up a test key */
    BF_set_key(key, SIZE, (const unsigned char*)"TestKey" );

    /* test out encryption */
    BF_ecb_encrypt(in, out, key, BF_ENCRYPT);
    printf("%s\n", out);

    /* test out decryption */
    BF_ecb_encrypt(out, out2, key, BF_DECRYPT);
    printf("%s\n", out2);

//  printf ("result %s \n",bf_str_encrypt("Linux"));
    unsigned char *out4=bf_str_encrypt("seu madruga na vila");

    printf ("result %s \n",out4);
    puts("OK!");
    unsigned char *out5=bf_str_decrypt(out4);

    printf ("result decrypt %s \n",out5);

    if(out)
        free(out);

    if(out2)
        free(out2);

    if(out4)
        free(out4);

    if(out5)
        free(out5);

    return 0;
}
Beispiel #16
0
static int
bf_ecb_decrypt(PX_Cipher *c, const uint8 *data, unsigned dlen, uint8 *res)
{
	unsigned	bs = gen_ossl_block_size(c),
				i;
	ossldata   *od = c->ptr;

	for (i = 0; i < dlen / bs; i++)
		BF_ecb_encrypt(data + i * bs, res + i * bs, &od->u.bf.key, BF_DECRYPT);
	return 0;
}
Beispiel #17
0
void write_buffer(CFStringRef inData)
{
	#ifdef DEBUG
		syslog(LOG_ERR,"Writing buffer to file.");
	#endif

	if (CFWriteStreamGetStatus(logStream)!=kCFStreamStatusOpen)
	{
		CFWriteStreamSetProperty(logStream,kCFStreamPropertyAppendToFile,kCFBooleanTrue);
		CFWriteStreamOpen(logStream);
	}

	if (!CFBooleanGetValue(doEncrypt))
	{
		CFWriteStreamWrite(logStream,(const UInt8*)CFStringGetCStringPtr(inData,CFStringGetFastestEncoding(inData)),CFStringGetLength(inData));
		return;
	}

	int buff_pos = 0;
	while (1)
	{	
		int avail_space =	8-CFDataGetLength(encrypt_buffer);					//space rem in buffer
		int rem_to_copy =	CFStringGetLength(inData)-buff_pos;					//stuff in data that needs to be copied
		int to_copy =		rem_to_copy<avail_space?rem_to_copy:avail_space;	//amount left to encryp, or avail space
		
		if (avail_space)
		{	
			UInt8 tmp_buff[8];
			CFStringGetBytes(inData,CFRangeMake(buff_pos,to_copy),kCFStringEncodingNonLossyASCII,0,false,tmp_buff,8,NULL);
			CFDataAppendBytes(encrypt_buffer,tmp_buff,to_copy);
			
			avail_space -= to_copy;
			if (avail_space>0)			// small buffer? still space left?
				break;
			buff_pos += to_copy;			//move along the buffer
		}
		
		UInt8 enc_buff[8];
		BF_ecb_encrypt(CFDataGetBytePtr(encrypt_buffer),enc_buff,&encrypt_bf_key,BF_ENCRYPT);
		CFWriteStreamWrite(logStream,enc_buff,8);

		CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,8));
		
		if (buff_pos==CFStringGetLength(inData))				//just in case buffer happens to fit perfectly
			break;
	}
	
	return;

}
Beispiel #18
0
static int test_bf_set_key(int n)
{
    int ret = 1;
    BF_KEY key;
    unsigned char out[8];

    BF_set_key(&key, n+1, key_test);
    BF_ecb_encrypt(key_data, out, &key, BF_ENCRYPT);
    /* mips-sgi-irix6.5-gcc  vv  -mabi=64 bug workaround */
    if (!TEST_mem_eq(out, 8, &(key_out[n][0]), 8))
        ret = 0;

    return ret;
}
Beispiel #19
0
static void bf_chunk(unsigned char *dst, const unsigned char *src,
		const unsigned char *secret, int enc)
{
	BF_KEY bf_key;
	int i;

	BF_set_key(&bf_key, CHUNK_SIZE, secret);

	/* BF_ecb_encrypt works with 64bits at a time */
	for (i = 0; i < CHUNK_SIZE/8; i ++) {
		BF_ecb_encrypt(src, dst, &bf_key, enc);
		src += 8;
		dst += 8;
	}
}
Beispiel #20
0
    int
decrypt_string (const char *key, const char *str, char *dest, int len)
{
    BF_KEY bf_key;
    uint32_t v;
    size_t i;

    /* Pad encoded string with 0 bits in case it's bogus */
    if (!key || !key[0])
        return 0;

    /* length must be a multiple of BF_BLOCK encoded in base64 */
    if (len % (BF_BLOCK * 6 / 4) != 0)
        return 0;

    BF_set_key (&bf_key, strlen (key), (const unsigned char *) key);
    while (len > 0)
    {
        unsigned char block[BF_BLOCK] = { 0 };

        for (i = v = 0; i < 6; ++i)
            v |= base64dec (*str++) << (i * 6);
        store32_be (block + 4, v);

        for (i = v = 0; i < 6; ++i)
            v |= base64dec (*str++) << (i * 6);
        store32_be (block + 0, v);

        BF_ecb_encrypt (block, block, &bf_key, BF_DECRYPT);

        memcpy (dest, block, BF_BLOCK);
        dest += BF_BLOCK;
        len -= BF_BLOCK * 6 / 4;
    }

    *dest++ = 0;
    return 1;
}
Beispiel #21
0
int main()
{
	unsigned char outbuf[1024] = {0};
	int outlen = 1024;

	const unsigned char key[] = {0x6B, 0x60, 0xCB, 0x5B, 0x82, 0xCE, 0x90, 0xB1, 0xCC, 0x2B, 0x6C, 0x55, 0x6C, 0x6C, 0x6C, 0x6C};
	unsigned char intext[] = {0xb2, 0xfb, 0xda, 0x4f, 0xc9, 0x23, 0x47, 0xa0, 0x10, 0xb3, 0x37, 0x67, 0x9b, 0x2f,\
	0xb4, 0x3e, 0x69, 0xb7, 0x13, 0xef, 0x6b, 0x5c, 0xd0, 0xb9, 0x16, 0x1c, 0x71, 0x5d, 0x0a, 0x0d,\
	0x96, 0x9b, 0x09, 0x3e, 0x3f, 0xd9, 0x42, 0x82, 0xc6, 0x54, 0xd7, 0x9b, 0x5f, 0x10, 0x1d, 0xdb,\
	0x26, 0xa0, 0x6d, 0x7d, 0xcd, 0xcc, 0xf8, 0x01, 0xfc, 0xd8, 0x43, 0xf6, 0xdd, 0xc0, 0x9c, 0x41,\
	0x98, 0xc8, 0x0c, 0x94, 0x87, 0x44, 0xf7, 0xc3, 0xf7, 0xba, 0xf3, 0xc9, 0x46, 0x45, 0xd0, 0x49,\
	0xde, 0x4d, 0x33, 0xee, 0x6b, 0x3a, 0x8c, 0x18, 0xce, 0xe0, 0x82, 0x97, 0x4c, 0xd8, 0x91, 0xf7,\
	0xdf, 0xbe, 0x7c, 0xf6, 0x59, 0x2c, 0xee, 0x5a, 0x95, 0xb3, 0xcd, 0xeb, 0x86, 0xa0, 0xd9, 0x05,\
	0x16, 0x41, 0xa3, 0x90, 0x58, 0xcf, 0x0d, 0xba, 0x87, 0x90, 0x91, 0xe6, 0x08, 0xfd, 0xbc, 0x6d,\
	0xff, 0x51, 0xcf, 0xe0, 0xf9, 0xc6, 0x71, 0x3b, 0xa0, 0xcc, 0x14, 0x3d, 0x46, 0x79, 0xd4, 0x9b,\
	0x0c, 0x37, 0x01, 0x77, 0x99, 0x87, 0xcc, 0x6c, 0x25, 0x01, 0x31, 0x01, 0xea, 0xfc, 0xac, 0xe1,\
	0x57, 0x4d, 0xa5, 0xa2, 0xda, 0xa3, 0x98, 0xc4, 0x83, 0x7a, 0x72, 0x8c, 0xcb, 0x52, 0xbd, 0x16,\
	0x1c, 0x77, 0xb6, 0x7c, 0x52, 0xf7, 0x72, 0xab, 0xee, 0xba, 0x56, 0xb5, 0x76, 0xbf, 0xfa, 0xc5,\
	0x6c, 0xe6};
	int inlen = sizeof(intext);

	printf("keylen= %d\n", sizeof(key));
	printf("inlen = %d\n", inlen);

	BF_KEY bf_key;
	BF_set_key(&bf_key, sizeof(key), key);
	
	unsigned int temp[2] = {0};
	for (int i = 0; i < inlen; i += 8)
	{
		temp[0] = GetInt32BE(&intext[i]);
		temp[1] = GetInt32BE(&intext[i+4]);
		BF_ecb_encrypt((unsigned char*)&temp, &outbuf[i], &bf_key, BF_DECRYPT); 
	}

	
	outlen = inlen;

	int i = 0;
	while (i < outlen)
	{
		printf("%02X ", outbuf[i]);
		i++;
		if (i % 16 == 0) printf("\n");
	}

	printf("\n");

	int ecx = GetInt32BE(&outbuf[outlen-4]);
	*(int*)(&outbuf[outlen-4]) = ecx;
	int edx = 0;
	for (int i = outlen-8; i >= 0; i-=4)
	{
		edx = GetInt32BE(&outbuf[i]);
		edx ^= ecx;
		ecx -= edx;
		*(int*)(&outbuf[i]) = edx;
	}

	i = 0;
	while (i < outlen)
	{
		printf("%02X ", outbuf[i]);
		i++;
		if (i % 16 == 0) printf("\n");
	}

	printf("\n");

	return 0;
}
Beispiel #22
0
	bool AuthenticateBlowfish(const CString& sLine) {
		/* Encrypt our sasl password with blowfish
		 * 
		 * Our response should look something like:
		 *
		 *   base64(
		 *     our public key length (2 bytes)
		 *     our public key
		 *     sasl username + \0
		 *     blowfish(
		 *       sasl password
		 *     )
		 *   )
		 */
		CString::size_type length;

		/* Our DH params */
		DHCommon dh;
		if (!dh.ParseDH(sLine))
			return false;

		// TODO for passwords with length 8, 16, 24, 32, etc. this will have 8 additional zero bytes at the end...
		// But it works when treated as null-terminated string anyway, and if it works I don't want to touch it right now.
		CString::size_type password_length = GetNV("password").size() + (8 - (GetNV("password").size() % 8));
		unsigned char *encrypted_password = (unsigned char *)malloc(password_length);
		char *plaintext_password = (char *)malloc(password_length);

		memset(encrypted_password, 0, password_length);
		memset(plaintext_password, 0, password_length);
		memcpy(plaintext_password, GetNV("password").c_str(), GetNV("password").size());

		BF_KEY key;
		BF_set_key(&key, dh.key_size, dh.secret);

		char *out_ptr = (char *)encrypted_password;
		char *in_ptr = (char *)plaintext_password;
		for (length = password_length; length; length -= 8, in_ptr += 8, out_ptr += 8) {
			BF_ecb_encrypt((unsigned char *)in_ptr, (unsigned char *)out_ptr, &key, BF_ENCRYPT);
		}

		free(plaintext_password);

		/* Build our response */
		length = 2 + BN_num_bytes(dh.dh->pub_key) + password_length + GetNV("username").size() + 1;
		char *response = (char *)malloc(length);
		out_ptr = response;

		/* Add our key to the response */
		uint16_t size16 = htons((uint16_t)BN_num_bytes(dh.dh->pub_key));
		memcpy(out_ptr, &size16, sizeof(size16));
		out_ptr += 2;
		BN_bn2bin(dh.dh->pub_key, (unsigned char *)out_ptr);
		out_ptr += BN_num_bytes(dh.dh->pub_key);

		/* Add sasl username to response */
		memcpy(out_ptr, GetNV("username").c_str(), GetNV("username").length() + 1); // +1 for zero byte in the end
		out_ptr += GetNV("username").length() + 1;

		/* Finally add the encrypted password to the response */
		memcpy(out_ptr, encrypted_password, password_length);
		free(encrypted_password);

		/* Base 64 encode and send! */
		PutIRC("AUTHENTICATE " + CString((const char *)response, length).Base64Encode_n());

		free(response);
		return true;
	}
Beispiel #23
0
string PacketCenter::process_encryption(PacketType type, PacketType translation)
{
	PacketType other_type = type == ENCRYPTED ? DECRYPTED : ENCRYPTED;
	HungryVector<Packet*>* read = &packets[type];
	HungryVector<Packet*>* write = &packets[other_type];

	/* Guard against repeated calls, and makes sure that a key
	 * was handed to this object.
	 */
	if (_key == 0 || processed[other_type]) return "";

	/* Determine how many packets we'll be sending for encryption. */
	int num_to_process = read->size();

	/* Iterate over the packets we've created */
	for (int i = 0; i < num_to_process; i++)
	{
		/* Allocate memory for the CharArray that will hold the
		* encrypted ciphertext.
		*/
		CharArray out = (CharArray) calloc(Packet::SIZE+1, sizeof(char));

		/* Extract the CharArray from the packet to be encrypted. */
		CharArray in = read->at(i)->getData();

		/* Send the data for encryption at last! */
		BF_ecb_encrypt (in, out, _key, (int) other_type);

		/* As always, trim the vector we've created to guard against extra
		* data mucking things up, and make sure that we are not allowed
		* to call this method again.
		*/
		write->add(new Packet(out));
	}
	write->trim();
	std::stringstream strm;
	int num_packets = write->size();
	for (int i = 0; i < num_packets; i++)
	{
		string str;
		if (other_type == ENCRYPTED)
		{
			str = write->at(i)->int_str();
		}
		else
		{
			str = write->at(i)->str();
		}
		int len = str.length();
		for (int c =0; c < len; c++)
		{
			char ch = str.at(c);
			if (ch == ' ')
			{
				char o = (translation == DO_TRANSLATION) ? '_' : ' ';
				strm << o;
			}

			else
			{
				strm << ch;
			}
		}
	}
	return strm.str();
}
Beispiel #24
0
int main(void)
{
	int i, t, keylen;
	long length;
	BF_KEY bfkey;
  struct timeval start, end;
  long mtime, seconds, useconds;

	/* open the given text file */
	t = open("blowfish.bin", O_RDONLY);
	if (t < 0) {
		perror("blowfish.bin");
		return 1;
	}
	length = 512;
  keylen=16;
	/* read 512 bytes from file descriptor t */
	read(t, input, length);
	/* brute-force attack with known plaintext */
	for (i = 0; i < 0x10000; i++) {
		/* REPLACE THE FOLLOWING FIVE COMMENTS BY CODE */
		/* set key[0] and key[1] */
    if(i==0)
     gettimeofday(&start, NULL);
    key[0]=i&0xff;
    key[1]=(i>>8)&0xff;
		/* use BF_set_key to initialise bfkey */
    BF_set_key(&bfkey, keylen, key);
		/* call BF_ecb_encrypt with parameter BF_DECRYPT */
    BF_ecb_encrypt(&input[504], &output[0], &bfkey, BF_DECRYPT);
		/* Did it work? (Look for expected plain text.) */
    if(memcmp(output, expected, keylen)==0)
      break;
		/* pseudo code: IF key is correct THEN leave the loop; */
    if(i==0)
    {
     gettimeofday(&end, NULL);
     seconds  = end.tv_sec  - start.tv_sec;
     useconds = end.tv_usec - start.tv_usec;

     mtime = ((seconds) * 1000000 + useconds);

     printf("Elapsed time: %ld microseconds\n", mtime);
    }
  }
  if (i == 0x10000) {
    printf("key not found\n");
    return 1;
  }
  /* show the key that we just determined */
  printf("key = {\n\t%d", key[0]);
  for (i = 1; i < sizeof(key); i++) {
    printf(", %d", key[i]);
  }
  printf("\n};\n");
  /* decrypt input */
  for (i = 0; i < length; i += 8)
    BF_ecb_encrypt(input + i, output + i, &bfkey, BF_DECRYPT);
  /* show decrypted text on stdout */
  printf("%s\n", output);

  return 0;
}
static int test(void)
	{
	unsigned char cbc_in[40],cbc_out[40],iv[8];
	int i,n,err=0;
	BF_KEY key;
	BF_LONG data[2]; 
	unsigned char out[8]; 
	BF_LONG len;

#ifdef CHARSET_EBCDIC
	ebcdic2ascii(cbc_data, cbc_data, TINYCLR_SSL_STRLEN(cbc_data));
#endif

	TINYCLR_SSL_PRINTF("testing blowfish in raw ecb mode\n");
	for (n=0; n<2; n++)
		{
#ifdef CHARSET_EBCDIC
		ebcdic2ascii(bf_key[n], bf_key[n], TINYCLR_SSL_STRLEN(bf_key[n]));
#endif
		BF_set_key(&key,TINYCLR_SSL_STRLEN(bf_key[n]),(unsigned char *)bf_key[n]);

		data[0]=bf_plain[n][0];
		data[1]=bf_plain[n][1];
		BF_encrypt(data,&key);
		if (TINYCLR_SSL_MEMCMP(&(bf_cipher[n][0]),&(data[0]),8) != 0)
			{
			TINYCLR_SSL_PRINTF("BF_encrypt error encrypting\n");
			TINYCLR_SSL_PRINTF("got     :");
			for (i=0; i<2; i++)
				TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)data[i]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expected:");
			for (i=0; i<2; i++)
				TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)bf_cipher[n][i]);
			err=1;
			TINYCLR_SSL_PRINTF("\n");
			}

		BF_decrypt(&(data[0]),&key);
		if (TINYCLR_SSL_MEMCMP(&(bf_plain[n][0]),&(data[0]),8) != 0)
			{
			TINYCLR_SSL_PRINTF("BF_encrypt error decrypting\n");
			TINYCLR_SSL_PRINTF("got     :");
			for (i=0; i<2; i++)
				TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)data[i]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expected:");
			for (i=0; i<2; i++)
				TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)bf_plain[n][i]);
			TINYCLR_SSL_PRINTF("\n");
			err=1;
			}
		}

	TINYCLR_SSL_PRINTF("testing blowfish in ecb mode\n");

	for (n=0; n<NUM_TESTS; n++)
		{
		BF_set_key(&key,8,ecb_data[n]);

		BF_ecb_encrypt(&(plain_data[n][0]),out,&key,BF_ENCRYPT);
		if (TINYCLR_SSL_MEMCMP(&(cipher_data[n][0]),out,8) != 0)
			{
			TINYCLR_SSL_PRINTF("BF_ecb_encrypt blowfish error encrypting\n");
			TINYCLR_SSL_PRINTF("got     :");
			for (i=0; i<8; i++)
				TINYCLR_SSL_PRINTF("%02X ",out[i]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expected:");
			for (i=0; i<8; i++)
				TINYCLR_SSL_PRINTF("%02X ",cipher_data[n][i]);
			err=1;
			TINYCLR_SSL_PRINTF("\n");
			}

		BF_ecb_encrypt(out,out,&key,BF_DECRYPT);
		if (TINYCLR_SSL_MEMCMP(&(plain_data[n][0]),out,8) != 0)
			{
			TINYCLR_SSL_PRINTF("BF_ecb_encrypt error decrypting\n");
			TINYCLR_SSL_PRINTF("got     :");
			for (i=0; i<8; i++)
				TINYCLR_SSL_PRINTF("%02X ",out[i]);
			TINYCLR_SSL_PRINTF("\n");
			TINYCLR_SSL_PRINTF("expected:");
			for (i=0; i<8; i++)
				TINYCLR_SSL_PRINTF("%02X ",plain_data[n][i]);
			TINYCLR_SSL_PRINTF("\n");
			err=1;
			}
		}

	TINYCLR_SSL_PRINTF("testing blowfish set_key\n");
	for (n=1; n<KEY_TEST_NUM; n++)
		{
		BF_set_key(&key,n,key_test);
		BF_ecb_encrypt(key_data,out,&key,BF_ENCRYPT);
		/* mips-sgi-irix6.5-gcc  vv  -mabi=64 bug workaround */
		if (TINYCLR_SSL_MEMCMP(out,&(key_out[i=n-1][0]),8) != 0)
			{
			TINYCLR_SSL_PRINTF("blowfish setkey error\n");
			err=1;
			}
		}

	TINYCLR_SSL_PRINTF("testing blowfish in cbc mode\n");
	len=TINYCLR_SSL_STRLEN(cbc_data)+1;

	BF_set_key(&key,16,cbc_key);
	TINYCLR_SSL_MEMSET(cbc_in,0,sizeof cbc_in);
	TINYCLR_SSL_MEMSET(cbc_out,0,sizeof cbc_out);
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,sizeof iv);
	BF_cbc_encrypt((unsigned char *)cbc_data,cbc_out,len,
		&key,iv,BF_ENCRYPT);
	if (TINYCLR_SSL_MEMCMP(cbc_out,cbc_ok,32) != 0)
		{
		err=1;
		TINYCLR_SSL_PRINTF("BF_cbc_encrypt encrypt error\n");
		for (i=0; i<32; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
		}
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
	BF_cbc_encrypt(cbc_out,cbc_in,len,
		&key,iv,BF_DECRYPT);
	if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,TINYCLR_SSL_STRLEN(cbc_data)+1) != 0)
		{
		TINYCLR_SSL_PRINTF("BF_cbc_encrypt decrypt error\n");
		err=1;
		}

	TINYCLR_SSL_PRINTF("testing blowfish in cfb64 mode\n");

	BF_set_key(&key,16,cbc_key);
	TINYCLR_SSL_MEMSET(cbc_in,0,40);
	TINYCLR_SSL_MEMSET(cbc_out,0,40);
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
	n=0;
	BF_cfb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,
		&key,iv,&n,BF_ENCRYPT);
	BF_cfb64_encrypt((unsigned char *)&(cbc_data[13]),&(cbc_out[13]),len-13,
		&key,iv,&n,BF_ENCRYPT);
	if (TINYCLR_SSL_MEMCMP(cbc_out,cfb64_ok,(int)len) != 0)
		{
		err=1;
		TINYCLR_SSL_PRINTF("BF_cfb64_encrypt encrypt error\n");
		for (i=0; i<(int)len; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
		}
	n=0;
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
	BF_cfb64_encrypt(cbc_out,cbc_in,17,
		&key,iv,&n,BF_DECRYPT);
	BF_cfb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,
		&key,iv,&n,BF_DECRYPT);
	if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,(int)len) != 0)
		{
		TINYCLR_SSL_PRINTF("BF_cfb64_encrypt decrypt error\n");
		err=1;
		}

	TINYCLR_SSL_PRINTF("testing blowfish in ofb64\n");

	BF_set_key(&key,16,cbc_key);
	TINYCLR_SSL_MEMSET(cbc_in,0,40);
	TINYCLR_SSL_MEMSET(cbc_out,0,40);
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
	n=0;
	BF_ofb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,&key,iv,&n);
	BF_ofb64_encrypt((unsigned char *)&(cbc_data[13]),
		&(cbc_out[13]),len-13,&key,iv,&n);
	if (TINYCLR_SSL_MEMCMP(cbc_out,ofb64_ok,(int)len) != 0)
		{
		err=1;
		TINYCLR_SSL_PRINTF("BF_ofb64_encrypt encrypt error\n");
		for (i=0; i<(int)len; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
		}
	n=0;
	TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
	BF_ofb64_encrypt(cbc_out,cbc_in,17,&key,iv,&n);
	BF_ofb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,&key,iv,&n);
	if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,(int)len) != 0)
		{
		TINYCLR_SSL_PRINTF("BF_ofb64_encrypt decrypt error\n");
		err=1;
		}

	return(err);
	}
Beispiel #26
0
int main(int argc, char *argv[]) {
    FILE *fin, *fout;

    uint8_t pw[PW_SIZE];
    uint8_t buf_in[BF_BLOCK_SIZE], buf_out[BF_BLOCK_SIZE];
    uint8_t keystream[BF_BLOCK_SIZE];
    uint8_t last_block_size;
    int read_count, write_count;
    time_t tm;
    IVec iv;

    struct termios term, term_orig;
    FILE *kb;
    int kbfd;
    BF_KEY key;

    uint8_t c;
    int mode, i;

    /* Check correct argument count */
    if (argc != 4) {
        fprintf(stderr, "Usage: filelock <mode> <input file> <output file>\n");
        return -1;
    }

    /* Check and get mode */
    if ((c = getopt(argc, argv, "de")) < 0) {
        fprintf(stderr, "Usage: available modes are e, d");
        return -1;
    }
    mode = (c == 'e') ? BF_ENCRYPT : BF_DECRYPT;

    /* Open input stream from stdin or file */
    if (argv[2][0] != '\0' && argv[2][0] == '-' && argv[2][1] == '\0') {
        /* Use stdin */
        fin = stdin;
    } else {
        /* Open file for reading */
        fin = fopen(argv[2], "r");
        if (fin == NULL) {
            fprintf(stderr, "Error: unable to open %s for reading\n", argv[2]);
            return -1;
        }
    }

    /* Set output stream to stdout or file */
    if (argv[3][0] == '-' && argv[3][1] == '\0') {
        /* Use stdout */
        fout = stdout;
    } else {
        /* Open file for writing */
        fout = fopen(argv[3], "w+");
        if (fout == NULL) {
            fprintf(stderr, "Error: unable to open %s for writing\n", argv[3]);
            fclose(fin);
            return -1;
        }
    }

    /* Open input stream from keyboard */
    kb = fopen("/dev/tty", "r");
    if (kb != NULL) {
        kbfd = fileno(kb);
        if (kbfd < 0) {
            fprintf(stderr, "Error: unable to open tty\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            fclose(kb);
            return -1;
        }
    } else {
        fprintf(stderr, "Error: unable to open tty\n");
        fclose(fin);
        fclose(fout);
        remove(argv[3]);
        return -1;
    }

    /* Disable terminal echo */
    tcgetattr(kbfd, &term);
    term_orig = term;
    term.c_lflag &= ~ECHO;
    tcsetattr(kbfd, TCSANOW, &term);

    /* Get password */
    fprintf(stderr, "Enter password: "******"\n");

    /* Restore terminal echo and close input stream */
    tcsetattr(kbfd, TCSANOW, &term_orig);
    fclose(kb);

    /* Initialize the key */
    BF_set_key(&key, strlen((char *)pw), pw);

    /*  Generate and write initialization vector */
    if (mode == BF_ENCRYPT) {
        /* Write dummy 0 byte first. We overwrite it later after we know last block size */
        c = 0;
        if (fwrite(&c, sizeof(uint8_t), 1, fout) != 1) {
            fprintf(stderr, "Error: unable to write initialization vector\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            return -1;
        }

        /* Seed random number generator with unix time and pass random number to IV */
        tm = time(NULL);
        srandom(tm);

        /* Use all 64 bits of initialization vector by ORing 2 32-bit random ints */
        iv.iv64 = ((uint64_t)random() << 32) | random();

        /* Write initialization vector */
        if (fwrite(iv.iv8, sizeof(uint8_t), IV_SIZE, fout) != IV_SIZE) {
            fprintf(stderr, "Error: unable to write initialization vector\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            return -1;
        }
    } else if (mode == BF_DECRYPT) {
        /* Recover offset information */
        if (fread(&last_block_size, sizeof(uint8_t), 1, fin) < 0) {
            fprintf(stderr, "Error: unable to read offset\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            return -1;
        }

        /* Recover initialization vector */
        if (fread(iv.iv8, sizeof(uint8_t), IV_SIZE, fin) < 0) {
            fprintf(stderr, "Error: unable to read initialization vector\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            return -1;
        }
    }

    /* Delay write by skipping first iteration */
    write_count = 0;

    /* Main loop */
    while ((read_count = fread(buf_in, sizeof(uint8_t), BF_BLOCK_SIZE, fin)) > 0) {
        /* Add necessary padding and record offset on last block */
        if (mode == BF_ENCRYPT) {
            last_block_size = read_count;
            for (; read_count < BF_BLOCK_SIZE; read_count++)
                buf_in[read_count] = 0;
        }

        /* Write previous block */
        if (fwrite(buf_out, sizeof(uint8_t), write_count, fout) != write_count) {
            fprintf(stderr, "Error: write error\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            break;
        }

        /* Encrypt or decrypt block */
        BF_ecb_encrypt(iv.iv8, keystream, &key, BF_ENCRYPT);
        iv.iv64++;
        for (i = 0; i < BF_BLOCK_SIZE; i++)
            buf_out[i] = keystream[i] ^ buf_in[i];
        write_count = BF_BLOCK_SIZE;
    }

    /* Must write last block since reads lead writes by 1 iteration */
    write_count = ((mode == BF_ENCRYPT) ? BF_BLOCK_SIZE : last_block_size);
    if (fwrite(buf_out, sizeof(uint8_t), write_count, fout) != write_count) {
        fprintf(stderr, "Error: write error\n");
        fclose(fin);
        fclose(fout);
        remove(argv[3]);
        return -1;
    }

    /* Rewind to beginning and overwrite dummy byte with last_block_size */
    if (mode == BF_ENCRYPT) {
        rewind(fout);
        if (fwrite(&last_block_size, sizeof(uint8_t), 1, fout) != 1) {
            fprintf(stderr, "Error: unable to write initialization vector\n");
            fclose(fin);
            fclose(fout);
            remove(argv[3]);
            return -1;
        }
    }

    /* Clean up */
    fclose(fin);
    fclose(fout);

    return 0;
}
Beispiel #27
0
static int test(void)
	{
	unsigned char cbc_in[40],cbc_out[40],iv[8];
	int i,n,err=0;
	BF_KEY key;
	BF_LONG data[2]; 
	unsigned char out[8]; 
	BF_LONG len;

	printf("testing blowfish in raw ecb mode\n");
	for (n=0; n<2; n++)
		{
		BF_set_key(&key,strlen(bf_key[n]),(unsigned char *)bf_key[n]);

		data[0]=bf_plain[n][0];
		data[1]=bf_plain[n][1];
		BF_encrypt(data,&key);
		if (memcmp(&(bf_cipher[n][0]),&(data[0]), sizeof data) != 0)
			{
			printf("BF_encrypt error encrypting\n");
			printf("got     :");
			for (i=0; i<2; i++)
				printf("%08lX ",(unsigned long)data[i]);
			printf("\n");
			printf("expected:");
			for (i=0; i<2; i++)
				printf("%08lX ",(unsigned long)bf_cipher[n][i]);
			err=1;
			printf("\n");
			}

		BF_decrypt(&(data[0]),&key);
		if (memcmp(&(bf_plain[n][0]),&(data[0]),8) != 0)
			{
			printf("BF_encrypt error decrypting\n");
			printf("got     :");
			for (i=0; i<2; i++)
				printf("%08lX ",(unsigned long)data[i]);
			printf("\n");
			printf("expected:");
			for (i=0; i<2; i++)
				printf("%08lX ",(unsigned long)bf_plain[n][i]);
			printf("\n");
			err=1;
			}
		}

	printf("testing blowfish in ecb mode\n");

	for (n=0; n<NUM_TESTS; n++)
		{
		BF_set_key(&key,8,ecb_data[n]);

		BF_ecb_encrypt(&(plain_data[n][0]),out,&key,BF_ENCRYPT);
		if (memcmp(&(cipher_data[n][0]),out,8) != 0)
			{
			printf("BF_ecb_encrypt blowfish error encrypting\n");
			printf("got     :");
			for (i=0; i<8; i++)
				printf("%02X ",out[i]);
			printf("\n");
			printf("expected:");
			for (i=0; i<8; i++)
				printf("%02X ",cipher_data[n][i]);
			err=1;
			printf("\n");
			}

		BF_ecb_encrypt(out,out,&key,BF_DECRYPT);
		if (memcmp(&(plain_data[n][0]),out,8) != 0)
			{
			printf("BF_ecb_encrypt error decrypting\n");
			printf("got     :");
			for (i=0; i<8; i++)
				printf("%02X ",out[i]);
			printf("\n");
			printf("expected:");
			for (i=0; i<8; i++)
				printf("%02X ",plain_data[n][i]);
			printf("\n");
			err=1;
			}
		}

	printf("testing blowfish set_key\n");
	for (n=1; n<KEY_TEST_NUM; n++)
		{
		BF_set_key(&key,n,key_test);
		BF_ecb_encrypt(key_data,out,&key,BF_ENCRYPT);
		if (memcmp(out,&(key_out[n-1][0]),8) != 0)
			{
			printf("blowfish setkey error\n");
			err=1;
			}
		}

	printf("testing blowfish in cbc mode\n");
	len=strlen(cbc_data)+1;

	BF_set_key(&key,16,cbc_key);
	memset(cbc_in,0,sizeof cbc_in);
	memset(cbc_out,0,sizeof cbc_out);
	memcpy(iv,cbc_iv,sizeof iv);
	BF_cbc_encrypt((unsigned char *)cbc_data,cbc_out,len,
		&key,iv,BF_ENCRYPT);
	if (memcmp(cbc_out,cbc_ok,32) != 0)
		{
		err=1;
		printf("BF_cbc_encrypt encrypt error\n");
		for (i=0; i<32; i++) printf("0x%02X,",cbc_out[i]);
		}
	memcpy(iv,cbc_iv,8);
	BF_cbc_encrypt(cbc_out,cbc_in,len,
		&key,iv,BF_DECRYPT);
	if (memcmp(cbc_in,cbc_data,strlen(cbc_data)+1) != 0)
		{
		printf("BF_cbc_encrypt decrypt error\n");
		err=1;
		}

	printf("testing blowfish in cfb64 mode\n");

	BF_set_key(&key,16,cbc_key);
	memset(cbc_in,0,40);
	memset(cbc_out,0,40);
	memcpy(iv,cbc_iv,8);
	n=0;
	BF_cfb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,
		&key,iv,&n,BF_ENCRYPT);
	BF_cfb64_encrypt((unsigned char *)&(cbc_data[13]),&(cbc_out[13]),len-13,
		&key,iv,&n,BF_ENCRYPT);
	if (memcmp(cbc_out,cfb64_ok,(int)len) != 0)
		{
		err=1;
		printf("BF_cfb64_encrypt encrypt error\n");
		for (i=0; i<(int)len; i++) printf("0x%02X,",cbc_out[i]);
		}
	n=0;
	memcpy(iv,cbc_iv,8);
	BF_cfb64_encrypt(cbc_out,cbc_in,17,
		&key,iv,&n,BF_DECRYPT);
	BF_cfb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,
		&key,iv,&n,BF_DECRYPT);
	if (memcmp(cbc_in,cbc_data,(int)len) != 0)
		{
		printf("BF_cfb64_encrypt decrypt error\n");
		err=1;
		}

	printf("testing blowfish in ofb64\n");

	BF_set_key(&key,16,cbc_key);
	memset(cbc_in,0,40);
	memset(cbc_out,0,40);
	memcpy(iv,cbc_iv,8);
	n=0;
	BF_ofb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,&key,iv,&n);
	BF_ofb64_encrypt((unsigned char *)&(cbc_data[13]),
		&(cbc_out[13]),len-13,&key,iv,&n);
	if (memcmp(cbc_out,ofb64_ok,(int)len) != 0)
		{
		err=1;
		printf("BF_ofb64_encrypt encrypt error\n");
		for (i=0; i<(int)len; i++) printf("0x%02X,",cbc_out[i]);
		}
	n=0;
	memcpy(iv,cbc_iv,8);
	BF_ofb64_encrypt(cbc_out,cbc_in,17,&key,iv,&n);
	BF_ofb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,&key,iv,&n);
	if (memcmp(cbc_in,cbc_data,(int)len) != 0)
		{
		printf("BF_ofb64_encrypt decrypt error\n");
		err=1;
		}

	return(err);
	}
Beispiel #28
0
int main(int argc, char *argv[])
{
	/* Variabili e strutture standard per la gestione della connessione */
	int ret;
	int cl_sk;
	int cl_ret;
	struct sockaddr_in sv_addr;

	/* Passare, oltre a indirizzo IP e porta (del server), anche la password condivisa con il server */
	if(argc != 4) {
		cerr << "Errore: sintassi del comando errata" << endl;
		cout << "Digitare: ./client <indirizzo_IP> <porta> <password_condivisa>" << endl;
		exit(1);
	}

	SERVER_IP_ADD = argv[1];
	SERVER_PORT = atoi(argv[2]);
	CLIENT_PWD = argv[3];

	cout << endl;
	cout << "********* INIZIO FASE DI CONNESSIONE ********" << endl;

	int np = strlen(CLIENT_PWD); //Numero di caratteri che compongono la password

	if(np < 8) {
		cerr << "Errore: inserire una password di almeno 8 caratteri alfanumerici e/o caratteri speciali" << endl;	
		exit(1);
	}

	if(SERVER_PORT <= 1023) {
		cerr << "Porta <" << SERVER_PORT << "> non utilizzabile :: Well Known Port" << endl;
		return -1;
	}

	if(SERVER_PORT <= 65535 && SERVER_PORT >= 49152)
		cout << "Fare attenzione nella scelta della porta <" << SERVER_PORT << "> :: Dynamic and/or Private Port" << endl;

	/* Creazione del socket lato client */	
	cl_sk = socket(AF_INET, SOCK_STREAM, 0);
	if(cl_sk == -1) {
    		cerr << "Errore: funzione <socket> non eseguita correttamente sul client" << endl;
    		exit(0);
	}

	/* Inizializzazione struttura dati */
	bzero(&sv_addr, sizeof(struct sockaddr_in)); /* Azzera il contenuto della struttura */
	sv_addr.sin_family = AF_INET;
	sv_addr.sin_port = htons(SERVER_PORT);
	inet_pton(AF_INET, SERVER_IP_ADD, &sv_addr.sin_addr.s_addr); /* Converte l'indirizzo da stringa a valore numerico */
	
	cl_ret = connect(cl_sk, (struct sockaddr *)(&sv_addr), sizeof(struct sockaddr_in));
	if(cl_ret == -1) {
		cerr << "Errore: funzione <connect> non eseguita correttamente sul client" << endl;
    		exit(0);
	}
	
	cout << endl;
	cout << "\033[32mCONNESSIONE CLIENT-SERVER EFFETTUATA\033[0m" << endl;
	cout << "\033[32mIndirizzo IP server: " << SERVER_IP_ADD << "\033[0m" << endl;
	cout << "\033[32mPorta server: " << SERVER_PORT << "\033[0m" << endl;
	cout << "\033[32mDescrittore del soket lato client in ascolto: " << cl_sk << "\033[0m" << endl;	
	cout << endl;
	cout << "********** FINE FASE DI CONNESSIONE *********" << endl;
	cout << endl;
	cout << "---------------------------------------------" << endl;
	cout << endl; 
	cout << "****** INIZIO FASE DI SCAMBIO MESSAGGI ******" << endl;
	cout << endl;
	
	/* Setto l'identificatore del client e del server */
	CLIENT = 'C';		
	SERVER = 'S';

	/* Costrutisco il messaggio M1 */
	msg1 m1;		
	m1.client = CLIENT;
	m1.server = SERVER;

	/* Invio al server il messaggio M1 */
	int dim1 = sizeof(msg1);
	ret = send(cl_sk, &m1, dim1, 0);
	if(ret == -1) {
		cerr << "Errore: messaggio M1 non inviato correttamente" << endl;
		return -1;
	}

	cout << "\033[32m:: C -> S\033[0m" << endl;
	cout << "\033[34m:: Messaggio in chiaro M1 inviato al server\033[0m" << endl;
	cout << endl;

	/* Ricevo dal server il messaggio M2 */
	msg2 m2;
	int dim2 = sizeof(msg2);
	ret = recv(cl_sk, &m2, dim2, MSG_WAITALL);
	if(ret == -1) {
		cerr << "Errore: messaggio M2 non ricevuto correttamente" << endl;
		return -1;
	}

	/* Memorizzo il nounce ricevuto dal server */
	NOUNCE = m2.nounce;

	cout << "\033[32m:: S -> C\033[0m" << endl;
	cout << "\033[34m:: Messaggio in chiaro M2 ricevuto correttamente\033[0m" << endl;
	cout << endl;

	/* Setto la chiave pubblica con cui criptare M3 */
	FILE *pub = fopen(PUB_KEY, "r");
	RSA *pub_key = RSA_new();
	PEM_read_RSA_PUBKEY(pub, &pub_key, NULL, NULL);

	/* Converto il nounce in una stringa per poterlo inserire nel messaggio da cifrare */
	char tmp[50];
	int n; //Numero di caratteri che compongono il nounce
	n = sprintf(tmp, "%i", NOUNCE); //Converto il nounce in una stringa
	char nounce[n];
	strcpy(nounce, tmp);
	
	/* Genero le componenti della chiave di sessione in maniera random */
	int part1 = rand();
	char tmp1[50];
	int t1 = sprintf(tmp1, "%i", part1);
	char p1[t1];
	strcpy(p1, tmp1);

	int part2 = rand();
	char tmp2[50];
	int t2 = sprintf(tmp2, "%i", part2);
	char p2[t2];
	strcpy(p2, tmp2);

	int part3 = rand();
	char tmp3[50];
	int t3 = sprintf(tmp3, "%i", part3);
	char p3[t3];
	strcpy(p3, tmp3);
	
	/* Costruisco la chiave di sessione */
	int dim_ses = t1 + t2 + t3; //Numero di caratteri della chiave di sessione
	char *ses_key = (char*) malloc (dim_ses);
	bzero(ses_key, dim_ses);
	strcpy(ses_key, p1);
	strcat(ses_key, p2);
	strcat(ses_key, p3);

	/* Setto la chiave di sessione */
	BF_KEY kcs;
	BF_set_key(&kcs, dim_ses, (const unsigned char*)ses_key);	

	/* Costruisco il messaggio M3 da criptare e inviare al client */
	int sep3 = 4; //Numero di separatori da inserire nel messaggio M3
	int ids3 = 2; //Numero di identificatori da inserire nel messaggio M3
	int dim3 = ids3 + n + np + dim_ses + sep3;
	char *m3 = (char*) malloc(dim3 + 1);
	bzero(m3, dim3 + 1);
	strcpy(m3, "C");
	strcat(m3, " ");
	strcat(m3, "S");
	strcat(m3, " ");
	strcat(m3, nounce);
	strcat(m3, " ");
	strcat(m3, CLIENT_PWD);
	strcat(m3, " ");
	strcat(m3, ses_key);
	
	/* Cripto il messaggio M3 con la chiave pubblica */
	unsigned char *m3c = (unsigned char*) malloc(RSA_size(pub_key));
	bzero(m3c, RSA_size(pub_key));
	int nc; //Numero di byte restituiti dalla cifratura
	nc = RSA_public_encrypt(dim3, (unsigned char*)m3, m3c, pub_key, RSA_PKCS1_OAEP_PADDING);
	if(nc == -1) {
		cerr << "Errore: funzione <RSA_public_encrypt> sul messaggio M3 non effettuata con successo" << endl;
		exit(1);
	}
	if(nc == 0) {
		cerr << "Errore: messaggio M3 non criptato correttamente" << endl;
		exit(1);	
	}

	/* Invio al server la dimensione del messaggio cifrato */
	int dim3c = RSA_size(pub_key);
	ret = send(cl_sk, &dim3c, 4, 0);
	if(ret == -1) {
		cerr << "Errore: dimensione del messaggio cifrato M3 non inviata correttamente" << endl;
		return -1;
	}

	/* Invio al server il messaggio cifrato M3 */
	ret = send(cl_sk, m3c, dim3c, 0);
	if(ret == -1) {
		cerr << "Errore: messaggio cifrato M3 non inviato correttamente" << endl;
		return -1;
	}

	cout << "\033[32m:: C -> S\033[0m" << endl;
	cout << "\033[34m:: Messaggio cifrato M3 inviato al server\033[0m" << endl;
		cout << endl;	

	/* Ricevo dal server la dimensione il messaggio criptato M4 */
	int dim4c;	
	ret = recv(cl_sk, &dim4c, 4, MSG_WAITALL);
	if(ret == -1) {
		cerr << "Errore: dimensione del messaggio cifrato M4 non ricevuta correttamente" << endl;
		return -1;
	}

	/* Imposto la dimensione del messaggio criptato M4 */
	double b = 8.0; //Numero di byte -> dimensione del blocco cifrato
	int dim4cb = (int)ceil(dim4c / b) * 8;
	dim4cb++;
	
	/* Ricevo dal server il messaggio criptato M4 */
	unsigned char *m4c = (unsigned char*) malloc(dim4cb);
	bzero(m4c, dim4cb);
	ret = recv(cl_sk, m4c, dim4cb, MSG_WAITALL);
	if(ret == -1) {
		cerr << "Errore: dimensione del messaggio cifrato M4 non ricevuta correttamente" << endl;
		return -1;
	}

	cout << "\033[32m:: S -> C\033[0m" << endl;
	cout << "\033[34m:: Messaggio cifrato M4 ricevuto correttamente\033[0m" << endl;

	/* Decifro il messaggio criptato M4 */
	unsigned char *m4 = (unsigned char*) malloc(dim4c);
	bzero(m4, dim4c);
	int off = 0; //Offeset		
	for(int i = 0; i < (int)ceil(dim4c / b); i++) {
		BF_ecb_encrypt(m4c + off, &m4[off], &kcs, BF_DECRYPT);
		off+=b;
	}

	cout << "\t\033[31m:: Messaggio cifrato M4 decriptato correttamente\033[0m" << endl;

	/* Analizzo il messaggio decriptato M4 */
	char *s4 = strtok((char*)m4, " "); //Memorizzo l'id del server
	char *c4 = strtok(NULL, " "); //Memorizzo l'id del client
	char *p4 = strtok(NULL, " "); //Memorizzo la password

	/* Controllo che la password sia quella attesa */
	if(strcmp(p4, CLIENT_PWD) != 0) {
		cout << "La password non coincide con quella attesa" << endl;
		exit(0);		
	}
	else {
		cout << "\033[31m\t:: Controllo Password -> OK\033[0m" << endl;
	}

	cout << endl;
	cout << "******* FINE FASE DI SCAMBIO MESSAGGI *******" << endl;
	cout << endl;
	cout << "---------------------------------------------" << endl;
	cout << endl;

	/* Pulizia delle variabili inutilizzate per evitare warning */	
	strcpy(c4, "");
	strcpy(s4, "");
 
	cout << "************ INIZIO FASE DI TEST ************" << endl;
	cout << endl;

	/* Apertura del file per effettuare il test */
	fstream ft;
	ft.open(TEST, ios::in);
	if(!ft) {
		cerr << "Errore nell'apertura del file di test" << endl;
    		exit(0);
  	}
	 
	/* Memorizzo il file di test in una stringa */	
	char *test_tmp = (char*) malloc(MAX_FILE_LEN);
	bzero(test_tmp, MAX_FILE_LEN);
	char line[MAX_LINE_LEN];
	while(ft.getline(line, MAX_LINE_LEN)) {
		strcat(test_tmp, line);		
	}

	/* Alloco lo spazio effettivamente utilizzato dal file di test */
	int dimtest = strlen(test_tmp) + 1;
	char *test = (char*) malloc(dimtest+1);
	bzero(test, dimtest);
	strcpy(test,test_tmp);

	/* Invio al server la dimensione del messaggio in chiaro */
	ret = send(cl_sk, &dimtest, 4, 0);
	if(ret == -1) {
		cerr << "Errore: dimensione del messaggio di test in chiaro non inviata correttamente" << endl;
		return -1;
	}

	/* Imposto la dimensione del messaggio di test criptato */
	int dimtestc = (int)ceil(dimtest / b) * 8;
	dimtestc++;

	/* Cripto la stringa del file di test */
	unsigned char *testc = (unsigned char*) malloc(dimtestc);
	bzero(testc, dimtestc);	
	int offtest = 0;
	for(int j = 0; j < (int)ceil(dimtest / b); j++) {
		BF_ecb_encrypt((const unsigned char*)test + offtest, &testc[offtest], &kcs, BF_ENCRYPT);
		offtest += b;	
	}

	/* Invio al server la dimensione della stringa di test cifrata */
	ret = send(cl_sk, &dimtestc, 4, 0);
	if(ret == -1) {
		cerr << "Errore: dimensione del messaggio di test cifrato non inviata correttamente" << endl;
		return -1;
	}

	/* Invio al server la stringa di test cifrata */
	ret = send(cl_sk, testc, dimtestc, 0);
	if(ret == -1) {
		cerr << "Errore: messaggio di test cifrato non inviato correttamente" << endl;
		return -1;
	}

	cout << "\033[32m:: C -> S\033[0m" << endl;
	cout << "\033[34m:: Messaggio di test cifrato e inviato al server\033[0m" << endl;

	cout << endl;
	cout << "************* FINE FASE DI TEST *************" << endl;
	cout << endl;

	/* Libero la memoria */
	RSA_free(pub_key);
	fclose(pub);
	free(m3);
	free(m3c);
	free(ses_key);
	free(m4c);
	free(m4);
	free(test_tmp);
	free(test);
	free(testc);
	
	return 0;
}
Beispiel #29
0
static int mech_step(sasl_session_t *p, char *message, size_t len, char **out, size_t *out_len)
{
	DH *dh = NULL;
	BF_KEY key;
	BIGNUM *their_key = NULL;
	myuser_t *mu;
	char *ptr, *secret = NULL, *password = NULL;
	int ret = ASASL_FAIL;
	uint16_t size;
	int secret_size;

	if (!p->mechdata)
		return ASASL_FAIL;
	dh = (DH*)p->mechdata;

	/* Their pub_key */
	if (len < 2)
		goto end;
	size = ntohs(*(uint16_t *)message);
	message += 2;
	len -= 2;
	if (size > len)
		goto end;
	if ((their_key = BN_bin2bn((unsigned char *)message, size, NULL)) == NULL)
		goto end;
	message += size;
	len -= size;

	/* Username */
	size = strlen(message);
	if (size >= NICKLEN) /* our base64 routines null-terminate - how polite */
		goto end;
	p->username = strdup(message);
	message += size + 1;
	len -= size + 1;
	if ((mu = myuser_find_by_nick(p->username)) == NULL)
		goto end;
	/* AES-encrypted password remains */

	/* Compute shared secret */
	secret = (char*)malloc(DH_size(dh));
	secret_size = DH_compute_key((unsigned char *)secret, their_key, dh);
	if (secret_size <= 0)
		goto end;

	/* Data must be multiple of block size, and let's be reasonable about size */
	if (len == 0 || len % 8 || len > 128)
		goto end;

	/* Decrypt! */
	BF_set_key(&key, secret_size, (unsigned char *)secret);
	ptr = password = (char*)malloc(len + 1);
	password[len] = '\0';
	while (len)
	{
		BF_ecb_encrypt((unsigned char *)message, (unsigned char *)ptr, &key, BF_DECRYPT);
		message += 8;
		ptr += 8;
		len -= 8;
	}

	if (verify_password(mu, password))
		ret = ASASL_DONE;

end:
	if (their_key)
		BN_free(their_key);
	free(secret);
	free(password);
	return ret;
}
Beispiel #30
0
static void
blf_decrypt(void *key, u_int8_t *blk)
{

	BF_ecb_encrypt(blk, blk, (BF_KEY *)key, 0);
}