Class: EdgeCastToken

Inherits:
Object
  • Object
show all
Defined in:
ext/ECToken/ECToken.c

Class Method Summary collapse

Class Method Details

.encrypt(k, t) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'ext/ECToken/ECToken.c', line 94

static VALUE encrypt(VALUE self, VALUE k, VALUE t) {
    char *key = StringValueCStr(k);
    char *string = StringValueCStr(t);
    char estr[kMAX_TOKEN_LENGTH*4];    
    
	if (strlen(string)+1 > kMAX_TOKEN_LENGTH)	// this line should protect us from the sprintf
	{
		int token_length = kMAX_TOKEN_LENGTH;
		printf("Only max of %i char is allowed\n", token_length);
		exit(0);
	}
    
	// For backward compatibility, check if somebody already passed in ec_secure=1
    
	// search for ec_secure in string
	// delete any previous instance of ec_secure=1 that resides within the string
	// this application will now prepend ec_secure=LENGTH_OF_STRING
	// so a valid string may end up being encrypted as ec_secure=033&ec_clientip=1.1.1.1
	char* ecsecure_check_ptr = strstr(string, "ec_secure=1");
    
	// buffer we will hold the new modified string
	char newBuff[(kMAX_TOKEN_LENGTH*2)-1];
	memset(newBuff,0,sizeof(newBuff));
    
	if(ecsecure_check_ptr > 0)	// we found ec_secure within the string
	{
		if(string == ecsecure_check_ptr)
			strcpy(newBuff,ecsecure_check_ptr+=12);	// found at beginning, skip over and copy the rest of the string
		else	// it's somewhere else in the string, scrub it out
		{
			*ecsecure_check_ptr = 0;	// break the string into two parts, first string null terminate where we found ec_secure
			sprintf(newBuff,"%s%s", string,ecsecure_check_ptr+11);
			// above we combine what was before ec_secure with what is after ec_secure's start position plus 11 octets
		}
	}
	else	// there was no ec_secure found within the string, so we just copy the string
		strcpy(newBuff,string);
    
	// setup the buffer we will pass off to blowfish
	char newbuffer[(kMAX_TOKEN_LENGTH*2)-1];
	memset(newbuffer,0,sizeof(newbuffer));
	// prepend with ec_secure=032, for example
	sprintf(newbuffer, "ec_secure=%03d&%s",(int)(strlen(newBuff)+14), newBuff);

	// encrypt the new buffer
	bfencrypt((unsigned char*)key, strlen(key), (unsigned char*)newbuffer,
              (unsigned char*)estr, strlen(newbuffer)+1);

	// convert to hex string
	unsigned int i = 0;
	char final_token[strlen(newbuffer)];
	char* current_ptr = &final_token[0];
    for(i=0; i<strlen(newbuffer); i++) {
       sprintf(current_ptr,"%02x",estr[i]&0xff);
       // increment pointer by 2 (2 chars in hex decimal)
       current_ptr += 2 * sizeof(char);
    }

	return rb_str_new2(final_token);

}