Websocket key hashing

时间:2016-04-04 18:30:38

标签: c websocket char buffer

I have a simple function to handle the parsing and hashing of the Sec-WebSocket-Key value in a C websocket program. I had the whole program working but found out I had a bunch of char* without a static location to point to. As you may have guessed this caused some memory issues and needed to be fixed. To fix the issue I made char's of size 100 and pointed the char* at them. Now the values I am getting back from the function are incorrect. Can someone tell me what I am doing wrong. From my understanding this should work. Fyi I am self taught and still have huge gaps in my C understanding.

char* sock_handle_hash(struct sock_data *sockdat, int dataCount) { 
    char EncodeHashbuff[100];
    char key1buff[100];
    char key2buff[100];
    char key3buff[100];
    char *EncodeHash = EncodeHashbuff;
    char *key1 = key1buff;
    char *key2 = key2buff;
    char *key3 = key3buff;


    unsigned char hash[SHA_DIGEST_LENGTH]; // this sets the length to the predefigned length in the SHA standard
    char *testKey = "Sec-WebSocket-Key"; // this is the key for the key value pair of the hash
    char *additionalHashData = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // the magic string used in websockets
    sockdat->buffer[dataCount] = '\0'; // null terminate the buffer
    key1 = strtok(sockdat->buffer, "\n"); // brake up the data by new lines
    key1 = strtok(NULL, "\n"); // skip the first line
    while (key2 != NULL) { //find the key to hash
        key2 = strtok(NULL, ":"); //brake data into the key value pairs
        key3 = strtok(NULL, "\n"); // go to next line
        if(strcmp(key2, testKey) == 0) { // if the correct key
            if( key3[(strlen(key3)-1)] =='\r'){
                key3[(strlen(key3)-1)]='\0';
            }
            key3++;
            char key4[200];
            strcpy(key4, key3); // copy the string to the final key
            strcat(key4, additionalHashData); // concat the magic websocket hash string
            SHA1(key4, strlen(key4), hash); //Hash SHA1 to the correct reply value
            EncodeHash = apssock_base64(hash, sizeof hash); // base 64 encode the value
            break; //Stop looping 
        }                   
    }   

    return EncodeHash; //success retrun the hashed value for the handshake
}

1 个答案:

答案 0 :(得分:0)

正如WhozCraig所说,我引用了一些不再保证现有的东西。为了解决这个问题,我在行中添加了一个静态:

static char EncodeHashbuff[100];