如何使用openssl库验证摘要?

时间:2015-08-12 06:57:24

标签: c openssl key sha256 digest

我以下列方式构建许可系统。我生成了匹配的公钥和私钥:

openssl genrsa -out mykey.pem 1024
openssl rsa -in mykey.pem -des3 -out prv-key.pem
openssl rsa -in mykey.pem -pubout -out pub-key.pem

现在我收到了一条许可证消息,其中包含有关用户和许可证详细信息的唯一信息。我的产品读取此消息,验证信息,如果一切按计划进行,它将读取许可证策略并相应地运行。

所以我已经使用了我的私钥

获取了该许可文件并使用签名消化了它
openssl dgst -sha256 -sign prv-key.pem -out license.secret license

现在我将许可证和签名的许可证文件都发送给客户。

我的问题是:如何在C程序中使用客户端的公钥(pub-key.pem)验证摘要。 我看过libssl和openssl库,但找不到摘要验证的好例子

1 个答案:

答案 0 :(得分:0)

您将要使用libopenssl-dev或Windows等效程序来构建类似于以下内容的C程序:

#include <stdio.h>
#include <stdlib.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>

// Buffer for file read operations. The buffer must be able to accomodate
// the RSA signature in whole (e.g. 4096-bit RSA key produces 512 byte signature)
#define BUFFER_SIZE 512
static unsigned char buffer[BUFFER_SIZE];

int main(int argc, char *argv[])
{
    if(argc != 4)
    {
        fprintf(stderr, "Usage: %s datafile signature_file public_key\n", argv[0]);
        return -1;
    }
    const char* filename = argv[1];
    const char* sigfile = argv[2];
    const char* pubkeyfile = argv[3];

    unsigned bytes = 0;

    // Calculate SHA256 digest for datafile
    FILE* datafile = fopen(filename , "rb");

    // Buffer to hold the calculated digest
    unsigned char digest[SHA256_DIGEST_LENGTH];
    SHA256_CTX ctx;
    SHA256_Init(&ctx);

    // Read data in chunks and feed it to OpenSSL SHA256
    while((bytes = fread(buffer, 1, BUFFER_SIZE, datafile)))
    {
        SHA256_Update(&ctx, buffer, bytes);
    }

    SHA256_Final(digest, &ctx);
    fclose(datafile);

    // Read signature from file
    FILE* sign = fopen (sigfile , "r");

    bytes = fread(buffer, 1, BUFFER_SIZE, sign);
    fclose(sign);

    // Verify that calculated digest and signature match
    FILE* pubkey = fopen(pubkeyfile, "r"); 

    // Read public key from file
    RSA* rsa_pubkey = PEM_read_RSA_PUBKEY(pubkey, NULL, NULL, NULL);

    // Decrypt signature (in buffer) and verify it matches
    // with the digest calculated from data file.
    int result = RSA_verify(NID_sha256, digest, SHA256_DIGEST_LENGTH,
                            buffer, bytes, rsa_pubkey);
    RSA_free(rsa_pubkey);
    fclose(pubkey);

    if(result == 1)
    {
        printf("Signature is valid\n");
        return 0;
    }
    else
    {
        printf("Signature is invalid\n");
        return 1;
    }
}

您也可以通过使用xxd -i pub-key.pem生成一个漂亮的C样式的密钥头,而不是将公共密钥作为文件参数传递给它,以供程序代替{ {1}}。

示例代码来自:https://pagefault.blog/2019/04/22/how-to-sign-and-verify-using-openssl/