Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* terrible signature verification code */
- #include <openssl/evp.h>
- #include <openssl/pem.h>
- #include <openssl/bio.h>
- #include <openssl/ec.h>
- #include <openssl/err.h>
- #define SIGNATURE_FILE "sig.dat"
- #define DATA_FILE "data.dat"
- #define CERTIFICATE_FILE "cert.pem"
- int load_cert(const char *file, EVP_PKEY **key)
- {
- if (file == NULL || key == NULL)
- return 0;
- FILE *fh = fopen(file, "r");
- if (fh == NULL){
- perror("Can't open certificate file");
- return 0;
- }
- X509 *x509 = X509_new();
- if (! PEM_read_X509(fh, &x509, NULL, NULL)){
- fprintf(stderr, "ERROR: PEM_read_X509\n");
- return 0;
- }
- *key = X509_get_pubkey(x509);
- if (*key == NULL){
- fprintf(stderr, "ERROR: X509_get_pubkey\n");
- return 0;
- }
- if (fh) fclose(fh);
- if (x509) X509_free(x509);
- return 1;
- }
- int load_data(const char *file, unsigned char **data, size_t *sz)
- {
- FILE *fh = fopen(file, "rb");
- if (fh == NULL){
- perror("Can't open data file.");
- return -1;
- }
- fseek(fh, 0, SEEK_END);
- long len = ftell(fh);
- rewind(fh);
- unsigned char *buf = malloc(len);
- if (buf == NULL){
- perror("Can't read data file into memory");
- fclose(fh);
- return -1;
- }
- long nbytes = fread(buf, 1, len, fh);
- *data = buf;
- *sz = (size_t) len;
- if(fh) fclose(fh);
- return nbytes;
- }
- int verify_signature(EVP_PKEY *pubkey,
- unsigned char *sig,
- size_t sig_len,
- unsigned char *data,
- size_t data_len)
- {
- if (pubkey == NULL || sig == NULL || data == NULL){
- return -1;
- }
- /* Assumes ecdsa_sha1 for brevity */
- const EVP_MD *dgst = EVP_get_digestbyname("ecdsa-with-SHA1");
- EVP_MD_CTX ctx;
- EVP_MD_CTX_init(&ctx);
- int rc = 0;
- if (! (rc = EVP_VerifyInit(&ctx, dgst)))
- return rc;
- if (! (rc = EVP_VerifyUpdate(&ctx, data, data_len)))
- return rc;
- rc = EVP_VerifyFinal(&ctx, sig, sig_len, pubkey);
- printf("Signature verification: ");
- switch (rc){
- case 0:
- printf("FAILED\n");
- break;
- case 1:
- printf("SUCCEEDED\n");
- break;
- default:
- printf("ERROR\n");
- }
- return rc;
- }
- int main(int argc, char *argv[])
- {
- unsigned char *sig = NULL;
- size_t sig_len;
- unsigned char *data = NULL;
- size_t data_len;
- EVP_PKEY *pubkey = NULL;
- if (load_data(SIGNATURE_FILE, &sig, &sig_len) > 0 &&
- load_data(DATA_FILE, &data, &data_len) > 0 &&
- load_cert(CERTIFICATE_FILE, &pubkey)){
- verify_signature(pubkey, sig, sig_len, data, data_len);
- } else {
- printf("Bad input.\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement