Skip to content

Instantly share code, notes, and snippets.

@vpetrigo
Created August 2, 2017 20:19
Show Gist options
  • Save vpetrigo/527f3e7684593c094f6ea80cb8d58c28 to your computer and use it in GitHub Desktop.
Save vpetrigo/527f3e7684593c094f6ea80cb8d58c28 to your computer and use it in GitHub Desktop.
Verify file with OpenSSL
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <stdio.h>
#include <stddef.h>
#include <inttypes.h>
#include <string.h>
void read_signature(char *buf, size_t buf_len, const char *filename)
{
FILE *filp = fopen(filename, "rb");
if (!filp)
{
printf("Cannot open file\n");
return;
}
size_t offset = 0;
while (buf_len > 0)
{
size_t read_bytes = fread(buf + offset, sizeof *buf, buf_len, filp);
if (read_bytes == EOF)
{
printf("READ ERROR\n");
fclose(filp);
return;
}
buf_len -= read_bytes;
offset += read_bytes;
}
fclose(filp);
}
int main()
{
const char *fname = "./hello.jar";
const char *sign = "./hello.jar.sha256";
const char *certname = "./public.pem";
char buf[512] = {0};
BIO *certbio = NULL;
X509 *cert = NULL;
EVP_PKEY *pkey = NULL;
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
read_signature(buf, 512, sign);
printf("Read signature\n");
certbio = BIO_new(BIO_s_file());
BIO_read_filename(certbio, certname);
cert = PEM_read_bio_X509(certbio, NULL, NULL, NULL);
if (!cert)
{
printf("Cannot load certificate\n");
return -1;
}
pkey = X509_get_pubkey(cert);
int nid = X509_get_signature_nid(cert);
if (!pkey)
{
printf("Cannot load public key\n");
return -1;
}
EVP_MD_CTX *mdctx = EVP_MD_CTX_create();
if (!mdctx)
{
printf("Cannot create MD CTX\n");
return -1;
}
if (EVP_DigestVerifyInit(mdctx, NULL, EVP_get_digestbynid(nid), NULL, pkey) != 1)
{
printf("Cannot init EVP digest\n");
return -1;
}
FILE *file_to_verif = fopen(fname, "rb");
char fbuf[128];
memset(fbuf, 0, 128);
size_t read = 0;
size_t offset = 0;
while ((read = fread(fbuf, sizeof(char), 128, file_to_verif)) != 0)
{
offset += read;
if (EVP_DigestUpdate(mdctx, fbuf, read) != 1)
{
printf("Cannot update EVP digest\n");
return -1;
}
}
printf("Read file: %" PRIu64 "\n", offset);
printf("Verification status: ");
if(EVP_DigestVerifyFinal(mdctx, (unsigned char *) buf, 512) == 1)
{
/* Success */
printf("SUCCESS\n");
}
else
{
/* Failure */
printf("FAILURE\n");
}
EVP_MD_CTX_destroy(mdctx);
EVP_PKEY_free(pkey);
X509_free(cert);
BIO_free_all(certbio);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment