RSA加密算法C语言

http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html
RSA算法原理(一)
http://www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html
RSA算法原理(二)

#include <stdio.h>
int candp(int a,int b,int c)//men  m^e = k*n + r
{ 
    int r=1;
    b=b+1;
    while(b!=1)
    {
        r=r*a;
        r=r%c;
        b--;
    }
    printf("%d\n",r);
    return r;
}

void main()
{
    int p,q,e,d,m,n,t,c,r;
    char s;
    printf("please input the p,q: ");
    scanf("%d%d",&p,&q);
    n=p*q;
    printf("the n is %3d\n",n);
    t=(p-1)*(q-1);
    printf("the t is %3d\n",t);
    printf("please input the e: ");
    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 %d\n",d);

    while(1)
    {
        printf("the cipher please input 1\n");
        printf("the plain please input 2\n");
        scanf("%d",&r);
        switch(r)
        {
        case 1: printf("input the m: "); /*输入要加密的明文数字*/
            scanf("%d",&m);
            c=candp(m,e,n);
            printf("the cipher is %d\n",c);break;
        case 2: printf("input the c: "); /*输入要解密的密文数字*/
            scanf("%d",&c);
            m=candp(c,d,n);
            printf("the cipher is %d\n",m);break;
        }
    }
    getch();
}
  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
RSA加密算法是一种非对称加密算法,它需要两个密钥:公钥和私钥。公钥可以公开,任何人都可以使用它来加密消息。私钥则只有该密钥的持有者才能使用它来解密消息。 下面是RSA加密算法C语言实现代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> // 生成公钥和私钥 void rsa_keygen(int p, int q, int *n, int *e, int *d) { int phi = (p - 1) * (q - 1); *n = p * q; *e = 2; while (*e < phi) { if (fmod(phi, *e) == 0) { *e += 1; continue; } int gcd = 0; int i = 2; while (gcd != 1 && i < phi) { gcd = 1; for (int j = 2; j <= i && j <= phi; j++) { if (i % j == 0 && phi % j == 0) { gcd = j; } } i++; } if (gcd == 1 && i == *e) { break; } *e += 1; } int k = 1; while (1) { if ((k * phi + 1) % *e == 0) { *d = (k * phi + 1) / *e; break; } k += 1; } } // 加密 int rsa_encrypt(int m, int e, int n) { int c = 1; for (int i = 0; i < e; i++) { c = (c * m) % n; } return c; } // 解密 int rsa_decrypt(int c, int d, int n) { int m = 1; for (int i = 0; i < d; i++) { m = (m * c) % n; } return m; } int main() { int p = 61, q = 53; // 选择两个质数 int n, e, d; // 定义公钥和私钥 rsa_keygen(p, q, &n, &e, &d); // 生成公钥和私钥 printf("公钥: (%d, %d)\n", e, n); printf("私钥: (%d, %d)\n", d, n); int m = 123; // 要加密的明文 int c = rsa_encrypt(m, e, n); // 加密 printf("密文: %d\n", c); int m2 = rsa_decrypt(c, d, n); // 解密 printf("解密后的明文: %d\n", m2); return 0; } ``` 注意:这只是一个简单的RSA实现,可能不够安全和完整。在实际应用中,请使用更为安全和完整的RSA算法库。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值