OpenSSL签名生成JWT令牌

时间:2020-11-11 16:30:00

标签: c openssl jwt rsa digital-signature

我必须生成JWT令牌,因此我发现了一些使用OpenSSL dll(libcrypto-1_1.dll)的在线资源。

此方法用于获取rsa密钥

void *getRSAKey(const char *file1, int type, const char *password)
{
    void * file = NULL;
    void *rsa;
    
    file = (void*)BIO_new_file(file1, "r");

    if (file == NULL) return 0;

    if (type == 0) {
        rsa=(void*)d2i_RSAPrivateKey_bio(file, NULL);
    } else if (type == 1) {
        if(password)
            rsa=(void*)PEM_read_bio_RSAPrivateKey(file, NULL, NULL, (void*)password);
        else
            rsa=(void*)PEM_read_bio_RSAPrivateKey(file, NULL, NULL, NULL);
    }
    
    if (rsa == NULL){
        lr_message("ras NULL ");
    }

    BIO_free(file);
    return(rsa);
}

首先,我生成了标头和有效负载,并对其进行了base24编码。我是他们用分隔符“。”连接它们。并保存输入

input = (unsigned char*)calloc(strlen(base24encodedHeader) + strlen(base24encodedPayload) + 1,sizeof(unsigned char));
    strcpy((char*)input,base24encodedHeader);
    strcat(input, ".");
    strcat((char*)input,base24encodedPayload);

然后将此输入传递给RSA_sign以获取符号

private_key = (void*)getRSAKey(private_key_file, X509_FILETYPE_PEM, "abc");
sign = (unsigned char*)calloc(RSA_size(private_key), sizeof(unsigned char));    
RSA_sign(NID_sha256,input, strlen((char*)input), sign, &sign_len, private_key);

printf("private_key = %d",RSA_size(private_key));
printf("signed len = %d\n", sign_len);
printf("signed string = %s\n", sign);

最后我将输入与符号连接

jwt= (char *)calloc(strlen(input) + strlen(sign) + 2,sizeof(unsigned char));
strcpy(jwt,input);
strcat(jwt,".");
strcat(jwt,sign);
printf("%s",jwt);

但是,在返回的jwt字符串中,“ sign”为空。而且RSA_Sign抛出的错误摘要太大

private_key = 512 
input size = 761
Signed len = 5
signed string = 
signed error = error:04075070:rsa routines:RSA_sign:digest too big for rsa key

1 个答案:

答案 0 :(得分:0)

输入字符串(base64)的长度为761个字节,RSA签名为 SHA256应该是256位= 32字节,所以为什么它会引发错误“太大”

所以我基本上需要首先生成输入字符串的SHA256哈希,然后再将其传递给RSA_sign。

相关问题