假定用户A要发送消息m给用户B,1)用户B要产生两个素数p和q;2)用户B计算n=pq和φ(n)=(p-1)(q-1);3)用户B选着一个数e(0#include typedef int Elemtype;Elemtype p,q,e;Elemtype fn;Elemtype m,c;int flag = 0;typedef void (*Msghandler) (void);struct MsgMap { char ch; Msghandler handler;};/* 公钥 */struct PU { Elemtype e; Elemtype n;} pu;/* 私钥 */struct PR { Elemtype d; Elemtype n;} pr;/* 判定一个数是否为素数 */bool test_prime(Elemtype m) { if (m0) {bin[n] = b % 2;n++;b /= 2; } }/* 候选菜单,主界面 */void Init() { cout in2 ? in1 : in2); Elemtype b = ( in1 =0; i--) {f = (f * f) % n;if(bin == 1) { f = (f * a) % n;} } return f;}/* 产生密钥 */void produce_key() { cout>p>>q; while (!(test_prime(p)&&test_prime(q))){cout>p>>q; }; pr.n = p * q; pu.n = p * q; fn = (p - 1) * (q - 1); cout>e; while((gcd(fn,e)!=1)) {cout>e; } pr.d = (extend_euclid(fn,e) + fn) % fn; pu.e = e; flag = 1; cout>m; c = modular_multiplication(m,pu.e,pu.n); cout>c; m = modular_multiplication(c,pr.d,pr.n); cout<<"m is:"<<m<<endl;}/* 版权信息 */void about() { cout<<"*********************************************"<<endl; cout<<"***
by Terry
***"<<endl; cout<<"*** copyright 2010,All rights reserved by ***"<<endl; cout<<"*** Terry,technology supported by weizuo !***"<<endl; cout<<"*** If you have any question, please mail ***"<<endl; cout<<"*** to [email protected] !
***"<<endl; cout<<"*** Computer of science and engineering ***"<<endl; cout<<"*** XiDian University
2010-4-29
***"<<endl; cout<<"*********************************************"<<endl; cout<<endl<<endl; Init();}/* 消息映射 */MsgMap Messagemap[] = { {'a',about}, {'s',produce_key}, {'d',decrypt}, {'e',encrypt}, {'q',NULL}};/* 主函数,提供循环 */void main() { Init(); char d; while((d = getchar())!='q') {int i = 0;while(Messagemap.ch) { if(Messagemap.ch == d) {
Messagemap.handler();
break; } i++;} }}
|