Websocket密钥散列

Websocket密钥散列,c,websocket,char,buffer,C,Websocket,Char,Buffer,我有一个简单的函数来处理C WebSocket程序中Sec WebSocket键值的解析和散列。我让整个程序工作,但发现我有一堆字符*没有一个静态位置指向。您可能已经猜到,这会导致一些内存问题,需要修复。为了解决这个问题,我制作了大小为100的字符,并将字符*指向它们。现在,我从函数返回的值不正确。有人能告诉我我做错了什么吗。据我理解,这应该行得通。仅供参考,我是自学成才,对C语言的理解仍有很大差距 char* sock_handle_hash(struct sock_data *sockdat

我有一个简单的函数来处理C WebSocket程序中Sec WebSocket键值的解析和散列。我让整个程序工作,但发现我有一堆字符*没有一个静态位置指向。您可能已经猜到,这会导致一些内存问题,需要修复。为了解决这个问题,我制作了大小为100的字符,并将字符*指向它们。现在,我从函数返回的值不正确。有人能告诉我我做错了什么吗。据我理解,这应该行得通。仅供参考,我是自学成才,对C语言的理解仍有很大差距

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
}

正如WhozCraig所说的,我指的是一些无法保证存在的东西。为了解决这个问题,我在行中添加了一个static:

static char EncodeHashbuff[100];

什么是“大小为100的字符”?你是说一个
字符[100]
,即-e。
字符的数组
?请参阅。
returnencodehash
也可以是
返回EncodeHashbuff,返回函数作用域中过期自动变量的地址。因此,调用方使用返回地址时的未定义行为。小心。仅供参考,除非
EncodeHash=apssock\u base64(散列,大小散列)
动态分配生成的base64编码(我们从发布的代码中不知道),该代码路径同样会遭受类似的命运。如果它使用dyna alloc,它可能会工作(至少不会调用上面提到的UB)。这是一个非常有用的链接。不过仍在解决此问题。仅供参考:此解决方案不是线程安全的,因为内存将在线程之间共享。如果您的服务器是多线程的,这将失败。考虑更改函数的原型以接受要写入的缓冲区(这样,可以通过调用函数在堆栈上正常创建<代码> char < /Cord>数组)。i、 e.
char*sock\u handle\u散列(struct sock\u data*sockdat,int dataCount,char*EncodeHash)
。你能提供一个关于这个主题的链接吗?谢谢。这里有一些关于静态变量和线程安全的解释。至于将数据写入现有的字符缓冲区,您可以看到一些答案或答案。