KGC_TEST/miracl/source/ecsign2.cpp

126 lines
3.1 KiB
C++

/*
* Digital Signature Standard (DSS)
*
* Elliptic Curve variation GF(2^m) - See Dr. Dobbs Journal, April 1997
*
* This program asks for the name of a <file>, computes its message digest,
* signs it, and outputs the signature to a file <file>.ecs. It is assumed
* that curve parameters are available from a file common.ecs, as well as
* the private key of the signer previously generated by the ecsgen program
*
* The curve is y^2+xy = x^3+Ax^2+B over GF(2^m) using a trinomial or
* pentanomial basis (t^m+t^a+1 or t^m+t^a+t^b+t^c+1). These parameters
* can be generated using the findbase.cpp example program, or taken from tables
* provided, for example in IEEE-P1363 Annex A
*
* The file common2.ecs is presumed to exist and contain
* {m,A,B,q,x,y,a,b,c} where A and B are parameters of the equation
* above, (x,y) is an initial point on the curve, {m,a,b,c} are the field
* parameters, (b is zero for a trinomial) and q is the order of the
* (x,y) point, itself a large prime. The number of points on the curve is
* cf.q where cf is the "co-factor", normally 2 or 4.
*
* Requires: big.cpp ec2.cpp
*/
#include <iostream>
#include <cstring>
#include <fstream>
#include "ec2.h"
using namespace std;
Miracl precision(200,256);
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 Big Hash(ifstream &fp)
{ /* compute hash function */
char ch,s[20];
Big h;
sha sh;
shs_init(&sh);
forever
{ /* read in bytes from message file */
fp.get(ch);
if (fp.eof()) break;
shs_process(&sh,ch);
}
shs_hash(&sh,s);
h=from_binary(20,s);
return h;
}
int main()
{
ifstream common("common2.ecs"); /* construct file I/O streams */
ifstream private_key("private.ecs");
ifstream message;
ofstream signature;
char ifname[50],ofname[50];
EC2 G;
Big a2,a6,q,x,y,h,r,s,d,k;
long seed;
int m,a,b,c;
miracl *mip=&precision;
/* randomise */
cout << "Enter 9 digit random number seed = ";
cin >> seed;
irand(seed);
/* get common data */
common >> m;
mip->IOBASE=16;
common >> a2 >> a6 >> q >> x >> y;
mip->IOBASE=10;
common >> a >> b >> c;
/* calculate r - this can be done off-line,
and hence amortized to almost nothing */
ecurve2(m,a,b,c,a2,a6,FALSE,MR_PROJECTIVE);
G=EC2(x,y);
k=rand(q);
G*=k; /* see ebrick2.cpp for technique to speed this up */
G.get(r);
r%=q;
/* get private key of recipient */
private_key >> d;
/* get message */
cout << "file to be signed = " ;
cin >> ifname;
strcpy(ofname,ifname);
strip(ofname);
strcat(ofname,".ecs");
message.open(ifname,ios::binary|ios::in);
if (!message)
{
cout << "Unable to open file " << ifname << "\n";
return 0;
}
h=Hash(message);
/* calculate s */
k=inverse(k,q);
s=((h+d*r)*k)%q;
signature.open(ofname);
mip->IOBASE=10;
signature << r << endl;
signature << s << endl;
return 0;
}