首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用libtomcrypt计算websocket Sec-WebSocket-接受值

使用libtomcrypt计算websocket Sec-WebSocket-接受值
EN

Stack Overflow用户
提问于 2015-03-27 23:28:25
回答 1查看 124关注 0票数 0

RFC6455指定了从Sec-WebSocket-Accept头的值计算Sec-WebSocket-Accept响应头的方法。该方法基于SHA-1散列和based 64编码结果.

如何使用唇裂隐窝为SHA-1和Base64在普通C中实现此方法?

注:这个问题故意没有表现出任何的努力,因为我自己立即回答了它。我的努力见下文。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-27 23:28:25

下面是一个完整的可编译示例,它只使用libtomcrypt,不需要任何动态内存分配,并成功地从RFC6455中计算引用示例:

代码语言:javascript
复制
//This file is licensed under CC0 1.0 Universal (public domain)
//Compile like this: gcc -o wsencodetest wsencodetest.c -ltomcrypt
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <tomcrypt.h>

#define SHA1_HASHSIZE 20

//Magic GUID as defined in RFC6455 section 1.3
static const char magicGUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

/**
 * Compute the value of the Sec-WebSocket-Accept response header
 * from the value of the Sec-WebSocket-Key header.
 * @param key The whitespace or NUL terminated Sec-WebSocket-Key value
 * @param out Where to store the base64-encoded output. Must provide 29 bytes of memory.
 * The 29 bytes starting at out contain the resulting value (plus a terminating NUL byte)
 */
void computeWebsocketSecAccept(const char* key, char* dst) {
    /**
     * Determine start & length of key minus leading/trailing whitespace
     * See RFC6455 section 1.3
     */
    //Skip leading whitespace
    while(isspace(*key)) {
        key++;
    }
    //Determine key size.
    size_t keySize = 0;
    while(!isspace(key[keySize]) && key[keySize] != 0) {
        keySize++;
    }
    //Compute SHA1 hash. See RFC6455 section 1.3
    char hashOut[SHA1_HASHSIZE];
    hash_state md;

    sha1_desc.init(&md);
    sha1_desc.process(&md, key, keySize);
    sha1_desc.process(&md, magicGUID, sizeof(magicGUID));
    sha1_desc.done(&md, hashOut);
    //Encode hash to output buffer
    size_t outlen = 29; //We know the output is 28 in size
    base64_encode(hashOut, SHA1_HASHSIZE, dst, &outlen);
}

/**
 * Usage example
 */
int main(int argc, char** argv) {
    //Whitespace needs to be removed according to RFC6455
    //Example from RFC6455
    const char* key = " dGhlIHNhbXBsZSBub25jZQ== ";
    char buf[29];
    //Perform computation
    computeWebsocketSecAccept(key, buf);
    //Should print s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
    printf("%s\n", buf);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29311791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档