导航:首页 > 源码编译 > rsa算法库c

rsa算法库c

发布时间:2023-04-09 02:56:00

❶ 如何用C语言实现RSA算法

上学期交的作业,已通过老师在运行时间上的测试
#include <stdio.h>
#include <stdlib.h>

unsigned long prime1,prime2,ee;

unsigned long *kzojld(unsigned long p,unsigned long q) //扩展欧几里得算法求模逆
{
unsigned long i=0,a=1,b=0,c=0,d=1,temp,mid,ni[2];
mid=p;
while(mid!=1)
{
while(p>q)
{p=p-q; mid=p;i++;}
a=c*(-1)*i+a;b=d*(-1)*i+b;
temp=a;a=c;c=temp;
temp=b;b=d;d=temp;
temp=p;p=q;q=temp;
i=0;
}
ni[0]=c;ni[1]=d;
return(ni);
}

unsigned long momi(unsigned long a,unsigned long b,unsigned long p) //模幂算法
{
unsigned long c;
c=1;
if(a>p) a=a%p;
if(b>p) b=b%(p-1);
while(b!=0)
{
while(b%2==0)
{
b=b/2;
a=(a*a)%p;
}
b=b-1;
c=(a*c)%p;
}
return(c);
}

void RSAjiami() //RSA加密函数
{
unsigned long c1,c2;
unsigned long m,n,c;
n=prime1*prime2;
system("cls");
printf("Please input the message:\n");
scanf("%lu",&m);getchar();
c=momi(m,ee,n);
printf("The cipher is:%lu",c);
return;
}

void RSAjiemi() //RSA解密函数
{
unsigned long m1,m2,e,d,*ni;
unsigned long c,n,m,o;
o=(prime1-1)*(prime2-1);
n=prime1*prime2;
system("cls");
printf("Please input the cipher:\n");
scanf("%lu",&c);getchar();
ni=kzojld(ee,o);
d=ni[0];
m=momi(c,d,n);
printf("The original message is:%lu",m);
return;
}

void main()
{ unsigned long m;
char cho;
printf("Please input the two prime you want to use:\n");
printf("P=");scanf("%lu",&prime1);getchar();
printf("Q=");scanf("%lu",&prime2);getchar();
printf("E=");scanf("%lu",&ee);getchar();
if(prime1<prime2)
{m=prime1;prime1=prime2;prime2=m;}
while(1)
{
system("cls");
printf("\t*******RSA密码系统*******\n");
printf("Please select what do you want to do:\n");
printf("1.Encrpt.\n");
printf("2.Decrpt.\n");
printf("3.Exit.\n");
printf("Your choice:");
scanf("%c",&cho);getchar();
switch(cho)
{ case '1':RSAjiami();break;
case '2':RSAjiemi();break;
case '3':exit(0);
default:printf("Error input.\n");break;
}
getchar();
}
}

❷ 求正确的RSA加密解密算法C语言的,多谢。

//rsa.h
#include<stdio.h>
#defineMAX_NUM63001
#defineMAX_PRIME251

//!返回代码
#defineOK100
#defineERROR_NOEACHPRIME101
#defineERROR_NOPUBLICKEY102
#defineERROR_GENERROR103

unsignedintMakePrivatedKeyd(unsignedintuiP,unsignedintuiQ);
unsignedintGetPrivateKeyd(unsignedintiWhich);
unsignedintMakePairkey(unsignedintuiP,unsignedintuiQ,unsignedintuiD);
unsignedintGetPairKey(unsignedint&d,unsignedint&e);
voidrsa_encrypt(intn,inte,char*mw,intiLength,int*&cw);
voidrsa_decrypt(intn,intd,int*&cw,intcLength,char*mw);
voidoutputkey();

//rsa.c
#include"rsa.h"
//!保存私钥d集合
structpKeyset
{
unsignedintset[MAX_NUM];
unsignedintsize;
}pset;

//!保存公、私钥对
structpPairkey
{
unsignedintd;
unsignedinte;
unsignedintn;
}pairkey;

//名称:isPrime
//功能:判断两个数是否互质
//参数:m:数a;n:数b
//返回:m、n互质返回true;否则返回false

boolisPrime(unsignedintm,unsignedintn)
{
unsignedinti=0;
boolFlag=true;

if(m<2||n<2)
returnfalse;

unsignedinttem=(m>n)?n:m;
for(i=2;i<=tem&&Flag;i++)
{
boolmFlag=true;
boolnFlag=true;
if(m%i==0)
mFlag=false;
if(n%i==0)
nFlag=false;
if(!mFlag&&!nFlag)
Flag=false;
}
if(Flag)
returntrue;
else
returnfalse;
}

//名称:MakePrivatedKeyd
//功能:由素数Q、Q生成私钥d
//参数:uiP:素数P;uiQ:素数Q
//返回:私钥d

unsignedintMakePrivatedKeyd(unsignedintuiP,unsignedintuiQ)
{
unsignedinti=0;

//!得到所有与z互质的数(私钥d的集合)
unsignedintz=(uiP-1)*(uiQ-1);
pset.size=0;
for(i=0;i<z;i++)
{
if(isPrime(i,z))
{
pset.set[pset.size++]=i;
}
}

returnpset.size;
}

//名称:MakePairKey
//功能:生成RSA公、私钥对
//参数:uiP:素数P;uiQ:素数Q;uiD:私钥d
//返回:错误代码

unsignedintMakePairkey(unsignedintuiP,unsignedintuiQ,unsignedintuiD)
{
boolbFlag=true;
unsignedinti=0,e;
unsignedintz=(uiP-1)*(uiQ-1);
unsignedintd=pset.set[uiD];
//d=uiD;

if(!isPrime(z,d))
returnERROR_NOEACHPRIME;

for(i=2;i<z;i++)
{
if((i*d)%z==1)
{
e=i;
bFlag=false;
}
}
if(bFlag)
returnERROR_NOPUBLICKEY;

if((d*e)%z!=1)
ERROR_GENERROR;

pairkey.d=d;
pairkey.e=e;
pairkey.n=uiP*uiQ;
returnOK;
}

//名称:GetPairKey
//功能:对外提供接口,获得公、私钥对
//参数:uiP:素数P;uiQ:素数Q;uiD:私钥d
//返回:

unsignedintGetPairKey(unsignedint&d,unsignedint&e)
{
d=pairkey.d;
e=pairkey.e;
returnpairkey.n;
}

//名称:GetPrivateKeyd
//功能:对外提供接口,由用户选择ID得以私钥d
//参数:iWhich:用户选择私钥d的ID
//返回:私钥d值

unsignedintGetPrivateKeyd(unsignedintiWhich)
{
if(pset.size>=iWhich)
returnpset.set[iWhich];
else
return0;
}

//名称:rsa_encrypt
//功能:RSA加密运算
//参数:n:公钥n;e:公钥e;mw:加密明文;iLength:明文长度;cw:密文输出
//返回:无

voidrsa_encrypt(intn,inte,char*mw,intmLength,int*&cw)
{
inti=0,j=0;
__int64temInt=0;

for(i=0;i<mLength;i++)
{
temInt=mw[i];
if(e!=0)
{
for(j=1;j<e;j++)
{
temInt=(temInt*mw[i])%n;
}
}
else
{
temInt=1;
}

cw[i]=(int)temInt;
}
}

//名称:rsa_decrypt
//功能:RSA解密运算
//参数:n:私钥n;d:私钥d;cw:密文;cLength:密文长度;mw:明文输出
//返回:无

voidrsa_decrypt(intn,intd,int*&cw,intcLength,char*mw)
{
inti=0,j=-1;
__int64temInt=0;

for(i=0;i<cLength/4;++i)
{
mw[i]=0;
temInt=cw[i];

if(d!=0)
{
for(j=1;j<d;j++)
{
temInt=(__int64)(temInt*cw[i])%n;
}
}
else
{
temInt=1;
}

mw[i]=(char)temInt;
}
}
voidoutputkey()
{
printf("PublicKey(e,n):(%d,%d) ",pairkey.e,pairkey.n);
printf("PrivateKey(d,n):(%d,%d) ",pairkey.d,pairkey.n);
}

//main.c
//工程:RSA
//功能:RSA加、解密文件
//作者:jlcss|ExpNIS


#include<stdio.h>
#include<afxwin.h>
#include<math.h>
#include"rsa.h"

#defineDECRYPT_FILE"RSA加密密文.txt"
#defineENCRYPT_FILE"RSA解密明文.txt"
//!约束文件最大2M
#defineMAX_FILE1024*1024*2

//名称:usage
//功能:帮助信息
//参数:应用程序名称
//返回:提示信息

voidUsage(constchar*appname)
{
printf(" usage:rsa-k素数P素数Q ");
printf(" usage:rsa-e明文文件公钥e公钥n ");
printf(" usage:rsa-d密文文件私钥d私钥n ");
}

//名称:IsNumber
//功能:判断数字字符数组
//参数:strNumber:字符数组
//返回:数字字组数组返回true,否则返回false;

boolIsNumber(constchar*strNumber)
{
unsignedinti;

if(!strNumber)
returnfalse;

for(i=0;i<strlen(strNumber);i++)
{
if(strNumber[i]<'0'||strNumber[i]>'9')
returnfalse;
}

returntrue;
}

//名称:IsPrimeNumber
//功能:判断素数
//参数:num:输入整数
//返回:素数返回true,否则返回false;

boolIsPrimeNumber(unsignedintnum)
{
unsignedinti;
if(num<=1)
returnfalse;

unsignedintsqr=(unsignedint)sqrt((double)num);
for(i=2;i<=sqr;i++)
{
if(num%i==0)
returnfalse;
}

returntrue;
}

//名称:FileIn
//功能:读取磁盘文件到内存
//参数:strFile:文件名称;inBuff:指向文件内容缓冲区
//返回:实际读取内容大小(字节)

intFileIn(constchar*strFile,unsignedchar*&inBuff)
{
intiFileLen=0,iBuffLen=0;

//!打开密文文件
CFilefile(strFile,CFile::modeRead);
iFileLen=(int)file.GetLength();
if(iFileLen>MAX_FILE)
{
printf("文件长度不能大于%dM,! ",MAX_FILE/(1024*1024));
gotoout;
}
iBuffLen=iFileLen;

inBuff=newunsignedchar[iBuffLen];
if(!inBuff)
gotoout;

ZeroMemory(inBuff,iBuffLen);

file.Read(inBuff,iFileLen);
file.Close();

out:
returniBuffLen;
}

//名称:FileOut
//功能:加/解密结果输出到当前目录磁盘文件中
//参数:strOut指向输出字符缓冲区,输出大小len,strFile为输出文件
//返回:无

voidFileOut(constvoid*strOut,intlen,constchar*strFile)
{
//!输出到文件
CFileoutfile(strFile,CFile::modeCreate|CFile::modeWrite);
outfile.Write(strOut,len);
outfile.Close();
}

//名称:CheckParse
//功能:校验应用程序入口参数
//参数:argc等于main主函数argc参数,argv指向main主函数argv参数
//返回:若参数合法返回true,否则返回false
//备注:简单的入口参数校验

boolCheckParse(intargc,char**argv)
{
boolbRes=false;

if(argc!=4&&argc!=5)
gotoout;

if(argc==4&&argv[1][1]=='k')
{
//!生成公、私钥对
if(!IsNumber(argv[2])||
!IsNumber(argv[3])||
atoi(argv[2])>MAX_PRIME||
atoi(argv[3])>MAX_PRIME)
gotoout;
}
elseif((argc==5)&&(argv[1][1]=='e'||argv[1][1]=='d'))
{
//!加密、解密操作
if(!IsNumber(argv[3])||
!IsNumber(argv[4])||
atoi(argv[3])>MAX_NUM||
atoi(argv[4])>MAX_NUM)
gotoout;
}
else
Usage(*argv);
bRes=true;

out:
returnbRes;
}

//名称:kOption1
//功能:程序k选项操作:由素数P、Q生成私钥d集合
//参数:uiP:程序入口参数P;uiQ:程序入口参数Q
//返回:执行正确返回生成私钥数目,否则返回0

unsignedintkOption1(unsignedintuiP,unsignedintuiQ)
{
unsignedintuiRes=0;

if(!IsPrimeNumber(uiP))
{
printf("P输入错误,P必须为(0,%d]素数",MAX_PRIME);
returnuiRes;
}
if(!IsPrimeNumber(uiQ))
{
printf("Q输入错误,Q必须为(0,%d]素数",MAX_PRIME);
returnuiRes;
}
if(uiP==uiQ)
{
printf("素数P与素数Q相同,很容易根据公钥n开平方得出素数P和Q,这种加密不安全,请更换素数! ");
returnuiRes;
}
printf("正在生成私钥d集合...... ");
uiRes=MakePrivatedKeyd(uiP,uiQ);

returnuiRes;
}

//!程序主函数
intmain(intargc,char**argv)
{
unsignedintp,q,d,n,e;//twoprimep&q,publickey(n,e),privatekey(n,d)
CheckParse(argc,argv);

d=4828;//uid
if(argc==4)
{
p=atoi(argv[2]);
q=atoi(argv[3]);
MakePrivatedKeyd(p,q);
MakePairkey(p,q,d);
outputkey();
}
elseif(argc==5)
{
charFileName[20];
strcpy(FileName,argv[2]);
intlen;
if(argv[1][1]=='e')
{
unsignedchar*inBuffer=(unsignedchar*)malloc(MAX_FILE);//输入缓冲区
int*cw=(int*)malloc(MAX_FILE);
len=FileIn(FileName,inBuffer);
e=atoi(argv[3]);
n=atoi(argv[4]);
rsa_encrypt(n,e,(char*)inBuffer,len,cw);
FileOut(cw,4*len,DECRYPT_FILE);
}
elseif(argv[1][1]=='d')
{
char*Buffer=(char*)malloc(MAX_FILE);//输入缓冲区
int*cw=(int*)malloc(MAX_FILE);
len=FileIn(FileName,(unsignedchar*&)cw);
d=atoi(argv[3]);
n=atoi(argv[4]);
rsa_decrypt(n,d,cw,len,Buffer);
FileOut(Buffer,len/4,ENCRYPT_FILE);
}
}

return0;
}

❸ 求RSA算法的源代码(c语言)

这个是我帮个朋友写的,写的时候发现其实这个没那么复杂,不过,时间复杂度要高于那些成型了的,为人所熟知的rsa算法的其他语言实现.
#include
int
candp(int
a,int
b,int
c)
{
int
r=1;
b=b+1;
while(b!=1)
{
r=r*a;
r=r%c;
b--;
}
printf("%d",r);
return
r;
}
void
main()
{
int
p,q,e,d,m,n,t,c,r;
char
s;
{printf("input
the
p:\n");
scanf("%d\n",&p);
printf("input
the
q:\n");
scanf("%d%d\n",&p);
n=p*q;
printf("so,the
n
is
%3d\n",n);
t=(p-1)*(q-1);
printf("so,the
t
is
%3d\n",t);
printf("please
intput
the
e:\n");
scanf("%d",&e);
if(e<1||e>t)
{printf("e
is
error,please
input
again;");
scanf("%d",&e);}
d=1;
while
(((e*d)%t)!=1)
d++;
printf("then
caculate
out
that
the
d
is
%5d",d);
printf("if
you
want
to
konw
the
cipher
please
input
1;\n
if
you
want
to
konw
the
plain
please
input
2;\n");
scanf("%d",&r);
if(r==1)
{
printf("input
the
m
:"
);/*输入要加密的明文数字*/
scanf("%d\n",&m);
c=candp(m,e,n);
printf("so
,the
cipher
is
%4d",c);}
if(r==2)
{
printf("input
the
c
:"
);/*输入要解密的密文数字*/
scanf("%d\n",&c);
m=candp(c,d,n);
printf("so
,the
cipher
is
%4d\n",m);
printf("do
you
want
to
use
this
programe:yes
or
no");
scanf("%s",&s);
}while(s=='y');
}
}

❹ RSA加密解密算法示例(C语言)

#include <stdlib.h>

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <time.h>

#define PRIME_MAX 200   // 生成素数范围

#define EXPONENT_MAX 200 // 生成指数e范围

#define Element_Max 127    // 加密单元的最大值,这里为一个char, 即1Byte

char str_read[100]="hello world !";  // 待加密的原文

int str_encrypt[100];                // 加密后的内容

char str_decrypt[100];              // 解密出来的内容

int str_read_len;                    // str_read 的长度

int prime1, prime2;                  // 随机生成的两个质数

int mod, eular;                      // 模数和欧拉数

int pubKey, priKey;                  // 公钥指数和私钥指数

// 生成随机素数,实际应用中,这两个质数越大,就越难破解。

int randPrime()

{

int prime, prime2, i;

next:

prime = rand() % PRIME_MAX;   // 随机产生数

if (prime <= 1) goto next;      // 不是质数,生成下一个随机数

if (prime == 2 || prime == 3) return prime;

prime2 = prime / 2;              // prime>=4, prime2 的平方必定大于 prime , 因此只检查小于等于prime2的数

for (i = 2; i <= prime2; i++)   // 判断是否为素数

{

if (i * i > prime) return prime;

if (prime % i == 0) goto next;  // 不是质数,生成下一个随机数

}

}

// 欧几里德算法,判断a,b互质

int gcd(int a, int b)

{

int temp;

while (b != 0) {

temp = b;

b = a % b;

a = temp;

}

return a;

}

//生成公钥指数,条件是 1< e < 欧拉数,且与欧拉数互质。

int randExponent()

{

int e;

while (1)

{

e = rand() % eular; if (e < EXPONENT_MAX) break;

}

while (1)

{

if (gcd(e, eular) == 1) return e; e = (e + 1) % eular; if (e == 0 || e > EXPONENT_MAX) e = 2;

}

}

//生成私钥指数

int inverse()

{

int d, x;

while (1)

{

d = rand() % eular;

x = pubKey * d % eular;

if (x == 1)

{

return d;

}

}

}

//加密函数

void jiami()           

{

str_read_len = strlen(str_read);      //从参数表示的地址往后找,找到第一个'\0',即串尾。计算'\0'至首地址的“距离”,即隔了几个字符,从而得出长度。

printf("密文是:");

for (int i = 0; i < str_read_len; i++)

{

int C = 1; int a = str_read[i], b = a % mod;

for (int j = 0; j < pubKey; j++) //实现加密

{

C = (C*b) % mod;

}

str_encrypt[i] = C;

printf("%d ", str_encrypt[i]);

}

printf("\n");

}

//解密函数

void jiemi()         

{

int i=0;  for (i = 0; i < str_read_len; i++)

{

int C = 1; int a = str_encrypt[i], b=a%mod;

for (int j = 0; j < priKey; j++)

{

C = (C * b) % mod;

}

str_decrypt[i] = C;

}

str_decrypt[i] = '\0'; printf("解密文是:%s \n", str_decrypt);

}

int main()

{

srand(time(NULL));

while (1)

{

prime1 = randPrime(); prime2 = randPrime(); printf("随机产生两个素数:prime1 = %d , prime2 = %d ", prime1, prime2);

mod = prime1 * prime2; printf("模数:mod = prime1 * prime2 = %d \n", mod); if (mod > Element_Max) break; // 模数要大于每个加密单元的值

}

eular = (prime1 - 1) * (prime2 - 1);  printf("欧拉数:eular=(prime1-1)*(prime2-1) = %d \n", eular);

pubKey = randExponent(); printf("公钥指数:pubKey = %d\n", pubKey);

priKey = inverse(); printf("私钥指数:priKey = %d\n私钥为 (%d, %d)\n", priKey, priKey, mod);

jiami(); jiemi();

return 0;

}

❺ RSA加密算法怎样用C语言实现 急急急!!!

/*数据只能是大写字母组成的字符串。
加密的时候,输入Y,然后输入要加密的文本(大写字母)
解密的时候,输入N,然后输入一个整数n表示密文的个数,然后n个整数表示加密时候得到的密文。
*/
/*RSA algorithm */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MM 7081
#define KK 1789
#define PHIM 6912
#define PP 85
typedef char strtype[10000];
int len;
long nume[10000];
int change[126];
char antichange[37];

void initialize()
{ int i;
char c;
for (i = 11, c = 'A'; c <= 'Z'; c ++, i ++)
{ change[c] = i;
antichange[i] = c;
}
}
void changetonum(strtype str)
{ int l = strlen(str), i;
len = 0;
memset(nume, 0, sizeof(nume));
for (i = 0; i < l; i ++)
{ nume[len] = nume[len] * 100 + change[str[i]];
if (i % 2 == 1) len ++;
}
if (i % 2 != 0) len ++;
}
long binamod(long numb, long k)
{ if (k == 0) return 1;
long curr = binamod (numb, k / 2);
if (k % 2 == 0)
return curr * curr % MM;
else return (curr * curr) % MM * numb % MM;
}
long encode(long numb)
{ return binamod(numb, KK);
}
long decode(long numb)
{ return binamod(numb, PP);
}
main()
{ strtype str;
int i, a1, a2;
long curr;
initialize();
puts("Input 'Y' if encoding, otherwise input 'N':");
gets(str);
if (str[0] == 'Y')
{ gets(str);
changetonum(str);
printf("encoded: ");
for (i = 0; i < len; i ++)
{ if (i) putchar('-');
printf(" %ld ", encode(nume[i]));
}
putchar('\n');
}
else
{ scanf("%d", &len);
for (i = 0; i < len; i ++)
{ scanf("%ld", &curr);
curr = decode(curr);
a1 = curr / 100;
a2 = curr % 100;
printf("decoded: ");
if (a1 != 0) putchar(antichange[a1]);
if (a2 != 0) putchar(antichange[a2]);
}
putchar('\n');
}
putchar('\n');
system("PAUSE");
return 0;
}

/*
测试:
输入:
Y
FERMAT
输出:
encoded: 5192 - 2604 - 4222
输入
N
3 5192 2604 4222
输出
decoded: FERMAT
*/

❻ 求RSA加密解密算法,c++源代码

//下面程序由520huiqin编写,已在VC++ 6.0下编译通过

#include <iostream.h>
#include <math.h>
#include <stdio.h>

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 (m <= 1) {
return false;
}
else if (m == 2) {
return true;
}
else {
for(int i=2; i<=sqrt(m); i++) {
if((m % i) == 0) {
return false;
break;
}
}
return true;
}
}
/* 将十进制数据转化为二进制数组 */
void switch_to_bit(Elemtype b, Elemtype bin[32]) {
int n = 0;
while( b > 0) {
bin[n] = b % 2;
n++;
b /= 2;
}
}
/* 候选菜单,主界面 */
void Init() {
cout<<"*********************************************"<<endl;
cout<<"*** Welcome to use RSA encoder ***"<<endl;
cout<<"*** a.about ***"<<endl;
cout<<"*** e.encrypt ***"<<endl;
cout<<"*** d.decrypt ***"<<endl;
cout<<"*** s.setkey ***"<<endl;
cout<<"*** q.quit ***"<<endl;
cout<<"**********************************by*Terry***"<<endl;
cout<<"press a key:"<<endl;
}
/* 将两个数排序,大的在前面*/
void order(Elemtype &in1, Elemtype &in2) {
Elemtype a = ( in1 > in2 ? in1 : in2);
Elemtype b = ( in1 < in2 ? in1 : in2);
in1 = a;
in2 = b;
}
/* 求最大公约数 */
Elemtype gcd(Elemtype a, Elemtype b) {
order(a,b);
int r;
if(b == 0) {
return a;
}
else {
while(true) {
r = a % b;
a = b;
b = r;
if (b == 0) {
return a;
break;
}
}
}

}
/* 用扩展的欧几里得算法求乘法逆元 */
Elemtype extend_euclid(Elemtype m, Elemtype bin) {
order(m,bin);
Elemtype a[3],b[3],t[3];
a[0] = 1, a[1] = 0, a[2] = m;
b[0] = 0, b[1] = 1, b[2] = bin;
if (b[2] == 0) {
return a[2] = gcd(m, bin);
}
if (b[2] ==1) {
return b[2] = gcd(m, bin);
}
while(true) {
if (b[2] ==1) {
return b[1];
break;
}
int q = a[2] / b[2];
for(int i=0; i<3; i++) {
t[i] = a[i] - q * b[i];
a[i] = b[i];
b[i] = t[i];
}
}
}
/* 快速模幂算法 */
Elemtype molar_multiplication(Elemtype a, Elemtype b, Elemtype n) {
Elemtype f = 1;
Elemtype bin[32];
switch_to_bit(b,bin);
for(int i=31; i>=0; i--) {
f = (f * f) % n;
if(bin[i] == 1) {
f = (f * a) % n;
}
}
return f;
}
/* 产生密钥 */
void proce_key() {
cout<<"input two primes p and q:";
cin>>p>>q;
while (!(test_prime(p)&&test_prime(q))){
cout<<"wrong input,please make sure two number are both primes!"<<endl;
cout<<"input two primes p and q:";
cin>>p>>q;
};
pr.n = p * q;
pu.n = p * q;
fn = (p - 1) * (q - 1);
cout<<"fn = "<<fn<<endl;
cout<<"input e :";
cin>>e;
while((gcd(fn,e)!=1)) {
cout<<"e is error,try again!";
cout<<"input e :";
cin>>e;
}
pr.d = (extend_euclid(fn,e) + fn) % fn;
pu.e = e;
flag = 1;
cout<<"PR.d: "<<pr.d<<" PR.n: "<<pr.n<<endl;
cout<<"PU.e: "<<pu.e<<" PU.n: "<<pu.n<<endl;
}
/* 加密 */
void encrypt() {
if(flag == 0) {
cout<<"setkey first:"<<endl;
proce_key();
}
cout<<"input m:";
cin>>m;
c = molar_multiplication(m,pu.e,pu.n);
cout<<"c is:"<<c<<endl;
}
/* 解密 */
void decrypt() {
if(flag == 0) {
cout<<"setkey first:"<<endl;
proce_key();
}
cout<<"input c:";
cin>>c;
m = molar_multiplication(c,pr.d,pr.n);
cout<<"m is:"<<m<<endl;
}
/* 版权信息 */
void about() {
cout<<"*********************************************"<<endl;
cout<<"*** by Terry ***"<<endl;
cout<<"*** right 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',proce_key},
{'d',decrypt},
{'e',encrypt},
{'q',NULL}
};
/* 主函数,提供循环 */
void main() {
Init();
char d;
while((d = getchar())!='q') {
int i = 0;
while(Messagemap[i].ch) {
if(Messagemap[i].ch == d) {
Messagemap[i].handler();
break;
}
i++;
}
}
}

//欢迎分享,盗窃可耻

❼ 如何用C++实现RSA算法

基础
RSA算法非常简单,概述如下:
找两素数p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一个数e,要求满足eperl -Mbigint -e "print 465**63%2773"
244
即用e对c解密后获得m=244 , 该值和原始信息M相等.
字符串加密
把上面的过程集成一下我们就能实现一个对字符串加密解密的示例了.
每次取字符串中的一个字符的ascii值作为M进行计算,其输出为加密后16进制
的数的字符串形式,按3字节表示,如01F
代码如下:
#!/usr/bin/perl -w
#RSA 计算过程学习程序编写的测试程序
#watercloud 2003-8-12
#
use strict;
use Math::BigInt;
my %RSA_CORE = (n=>2773,e=>63,d=>847); #p=47,q=59
my $N=new Math::BigInt($RSA_CORE{n});

❽ C++实现RSA加密解密算法

#include <iostream>
using namespace std;

template <class HugeInt>
HugeInt Power( const HugeInt & x, const HugeInt & n, // 求x^n mod p
const HugeInt & p )
{
if( n == 0 )
return 1;

HugeInt tmp = Power( ( x * x ) % p, n / 2, p );

if( n % 2 != 0 )
tmp = ( tmp * x ) % p;

return tmp;
}

template <class HugeInt>
void fullGcd( const HugeInt & a, const HugeInt & b, //
HugeInt & x, HugeInt & y )
{
HugeInt x1, y1;

if( b == 0 )
{
x = 1;
y = 0;
}
else
{
fullGcd( b, a % b, x1, y1 );
x = y1;
y = x1 - ( a / b ) * y1;
}
}

template <class HugeInt>
HugeInt inverse( const HugeInt & p, const HugeInt & q, // 求d
const HugeInt & e )
{
int fyn = ( 1 - p ) * ( 1 - q );
HugeInt x, y;

fullGcd( fyn, e, x, y );
return x > 0 ? x : x + e;
}

int main( )
{
cout << "Please input the plaintext: " << endl;
int m;
cin >> m;
cout << "Please input p,q and e: " << endl;
int p, q, e;
cin >> p >> q >> e;
int n = p * q;
int d = inverse( p, q, e );
int C = Power( m, e, n );
cout << "The ciphertext is: " << C << endl;
cout << "\n\nPlease input the ciphertext: " << endl;
cin >> C;
cout << "\n\nPlease input p, q and d: " << endl;
cin >> p >> q >> d;
n = p * q;
m = Power( C, d, n );
cout <<"The plaintext is: " << m << endl << endl;

system( "pause" );
return 0;
}

这就是RSA加密解密算法

阅读全文

与rsa算法库c相关的资料

热点内容
单片机的功能模块 浏览:771
安卓手机如何录制视频长时间 浏览:285
安全问题app哪个好 浏览:445
压缩水会变冰吗 浏览:526
小说配音app哪个靠谱 浏览:820
编译iso 浏览:944
照片生成pdf格式 浏览:194
病历转pdf 浏览:835
云服务器配硬件 浏览:978
服务器10k什么意思 浏览:21
pdfeditor汉化 浏览:884
新科学pdf 浏览:746
现在还有c语言编译吗 浏览:675
哪里买到单片机 浏览:480
linux文件打开数量 浏览:510
编译原理中什么是l属性文法 浏览:372
硬盘加密时出现的问题 浏览:61
如何退域命令 浏览:108
看书的app哪里看 浏览:291
服务器怎么调大 浏览:4