/*
 *   Digital Signature Algorithm (DSA)
 *
 *   See Communications ACM July 1992, Vol. 35 No. 7
 *   This new standard for digital signatures has been proposed by 
 *   the American National Institute of Standards and Technology (NIST)
 *   under advisement from the National Security Agency (NSA). 
 *
 *   This program verifies a the signature given to a <file> in
 *   <file>.dss generated by program dssign.c
 * 
 */

#include <stdio.h>
#include "miracl.h"
#include <stdlib.h>
#include <string.h>

void strip(char *name)
{ /* strip off filename extension */
    int i;
    for (i=0;name[i]!='\0';i++)
    {
        if (name[i]!='.') continue;
        name[i]='\0';
        break;
    }
}

static void hashing(FILE *fp,big hash)
{ /* compute hash function */
    char h[20];
    sha sh;
    int i,ch;
    shs_init(&sh);
    while ((ch=fgetc(fp))!=EOF) shs_process(&sh,ch);
    shs_hash(&sh,h);
    bytes_to_big(20,h,hash);
}

int main()
{
    FILE *fp;
    char ifname[50],ofname[50];
    big p,q,g,y,v,u1,u2,r,s,hash;
    int bits;
    miracl *mip;
/* get public data */
    fp=fopen("common.dss","rt");
    if (fp==NULL)
    {
        printf("file common.dss does not exist\n");
        return 0;
    }

    fscanf(fp,"%d\n",&bits);
    mip=mirsys(bits/4,16);    /* Use Hex Internally */
    p=mirvar(0);
    q=mirvar(0);
    g=mirvar(0);
    y=mirvar(0);
    v=mirvar(0);
    u1=mirvar(0);
    u2=mirvar(0);
    s=mirvar(0);
    r=mirvar(0);
    hash=mirvar(0);

    innum(p,fp);
    innum(q,fp);
    innum(g,fp);
    fclose(fp);

/* get public key of signer */
    fp=fopen("public.dss","rt");
    if (fp==NULL)
    {
        printf("file public.dss does not exist\n");
        return 0;
    }
    innum(y,fp);
    fclose(fp);
/* get message */
    printf("signed file = ");
    gets(ifname);
    strcpy(ofname,ifname);
    strip(ofname);
    strcat(ofname,".dss");
    if ((fp=fopen(ifname,"rb"))==NULL)
    { /* no message */
        printf("Unable to open file %s\n",ifname);
        return 0;
    }

    hashing(fp,hash);
    fclose(fp);
    fp=fopen(ofname,"rt");
    if (fp==NULL)
    { /* no signature */
        printf("signature file %s does not exist\n",ofname);
        return 0;
    }
    innum(r,fp);
    innum(s,fp);
    fclose(fp);
    if (mr_compare(r,q)>=0 || mr_compare(s,q)>=0)
    {
        printf("Signature is NOT verified\n");
        return 0;
    }
    xgcd(s,q,s,s,s);
    mad(hash,s,s,q,q,u1);
    mad(r,s,s,q,q,u2);
    powmod2(g,u1,y,u2,p,v);
    divide(v,q,q);
    if (mr_compare(v,r)==0) printf("Signature is verified\n");
    else                 printf("Signature is NOT verified\n");
    return 0;
}

