对文件摘要进行签名验证

#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;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值