|
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <math.h>
- #include <time.h>
- char s[100], * c;
- int n, e, d, i, C, j, k = 0, len;
- int str[100], b[30];
- unsigned gcd(unsigned a, unsigned b)
- {
- if (a % b == 0)
- return b;
- else
- return gcd(b, a % b);
- }
- void Egcd(int a, int b, int& x, int& y)
- { //ax-by=1
- if (b == 0 || a == 0)
- {
- x = 1;
- y = 0;
- return;
- }
- if (a < b)
- {
- Egcd(a, b % a, x, y);
- x = (int)(b * y + 1) / a;
- }
- else
- {
- Egcd(a % b, b, x, y);
- y = (int)(a * x - 1) / b;
- }
- }
- void RSA()
- {
- int p, q, N, Y;
- printf(" 请输入 p , q的值:");
- scanf_s("%d %d", &p, &q);
- n = p * q;
- N = (p - 1) * (q - 1);
- srand((unsigned)time(NULL)); // 初始化随机数
- while ( ) // 产生随机整数 e , e 与 N 互质
- {
- e = rand() % N;
- if (e == 0)
- continue;
- if (gcd(N, e) == 1)
- {
- break;
- }
- }
- Egcd(e, N, d, Y);
- printf(" 公钥为 PU={e=%d,n=%d}\n", e, n);
- printf(" 私钥为 PR={d=%d,n=%d}\n", d, n);
- }
- void encrypt() // 加密函数
- {
- len = strlen(s);
- for (i = 0; i < len; i++) // 去掉 s[100] 中的空格
- {
- if (s[i] < 97 || s[i]>122)
- {
- b[k] = i;
- k++;
- for (j = i; j < len - 1; j++)
- {
- s[j] = s[j + 1];
- }
- len--;
- }
- }
- s[len] = '\0'; // 结束符
- printf(" 密文是 : ");
- for (i = 0; i < len; i++)
- {
- C = 1;
- for (int j = 0; j < e; j++)
- {
- C = (C * (s[i] - 97)) % n;
- }
- str[i] = C;
- printf("%d ", str[i]);
- }
- printf("\n");
- }
- void decrypt() // 解密函数
- {
- c = (char*)malloc(len * sizeof(int));
- for (i = 0; i < len; i++) // 实现解密
- {
- C = 1;
- for (int j = 0; j < d; j++)
- {
- C = (C * (str[i])) % n;
- }
- c[i] = C + 97;
- }
- c[i] = '\0';
- for (int z = 0; z < k; z++) // 加空格
- {
- for (i = 0; i < len; i++)
- {
- if (i == b[z])
- {
- for (j = len; j > i; j--)
- {
- c[j] = c[j - 1];
- }
- c[i] = ' ';
- len++;
- b[z + 1] = b[z + 1] + (z + 1);
- break;
- }
- }
- }
- c[len] = '\0';
- printf(" 明文 : ");
- puts(c);
- }
- int main()
- {
- int function();
- int fc;
- printf(" 请输入初始的明文 : ");
- gets_s(s);
- RSA(); // 提供私钥和公钥
- while ( )
- {
- fc = function();
-
- encrypt();
-
- decrypt();
-
- }
- return 0;
- }
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|