RSA 公钥密码实验1
#include "stdafx.h"
#include<windows.h>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
int Euclid(int a, int n){
int x, y, r;
x = n; y = a;
for (int i = 0;;){
if (y == 0)
return x;
if (y == 1)
return y;
r = x%y;
x = y;
y = r;
}
}
double extenEuclid(double a, double n){
double x1 = 1, x2 = 0, x3 = n, y1 = 0, y2 = 1, y3 = a, Q;
double t1, t2, t3;
for (int i = 0;;){
if (y3 == 0){
return x3;
cout << "no reverse" << endl;
}
if (y3 == 1)
return y2;
Q = int(x3 / y3);
t1 = x1 - Q*y1;
t2 = x2 - Q*y2;
t3 = x3 - Q*y3;
x1 = y1; x2 = y2; x3 = y3;
y1 = t1; y2 = t2; y3 = t3;
}
}
bool Rabin(int a, int n){
vector<int> b;
unsigned int N = n - 1;
for (int i = 0, j = 1;; i++){
if (j>N)
break;
if ((N >> i) & (unsigned int)1){
b.push_back(1);
return true;
}
else{
b.push_back(0);
return false;
}
j *= 2;
}
}
void transfer(char cypher[], double c[]){
int m[100] = { 0 };
for (int i = 0, j = 0; cypher[j] != '\0'; i += 2){
if (cypher[j] == ' '){
m[i] = 0; m[i + 1] = 0;
}
else{
m[i] = cypher[j] - 64;
if (m[i]<10){
m[i + 1] = m[i];
m[i] = 0;
}
else{
m[i + 1] = m[i] % 10;
m[i] = m[i] / 10;
}
}
j++;
}
for (int k2 = 0; k2<2 * strlen(cypher); k2++)
cout << m[k2];
cout << endl;
int n, k;
for (k = 0, n = 0; k<2 * strlen(cypher); k += 4){
c[n] = m[k] * 1000 + m[k + 1] * 100 + m[k + 2] * 10 + m[k + 3];
n++;
}
for (; c[n - 1]<1000;)
c[n - 1] *= 10;
}
double quickindex1(double a, double m, double n){
vector<int>b;
unsigned int N = m;
for (int ii = 0, j = 1;; ii++){
if (j>N)
break;
if ((N >> ii)& (unsigned int)1)
b.push_back(1);
else
b.push_back(0);
j *= 2;
}
double c = 0, d = 1;
for (int i = b.size() - 1; i >= 0; i--){
c *= 2;
d = (d*d) - int((d*d) / n)*n;
if (b[i] == 1){
c += 1;
d = (d*a) - int((d*a) / n)*n;
}
}
return d;
}
int main(){
double c[100] = { 0 };
double a[100] = { 0 };
double b[100] = { 0 };
char cypher[] = "I LOVE THE PEOPLE'S REPUBLIC OF CHINA";
transfer(cypher, c);
for (int k1 = 0; c[k1] != '\0'; k1++)
cout << c[k1] << " ";
double n = 0, fn = 0, p = 563, q = 823, d = 0;
n = p*q; fn = (q - 1)*(p - 1);
double e;
for (e = 2; e<fn; e += 3){
if (Euclid(e, fn) == 1)
break;
}
d = extenEuclid(e, fn);
cout << endl << "密码和密钥e d and n:";
cout << e << " " << d << " " << n << endl;
cout << endl << "加密:";
for (int i = 0; c[i] != '\0'; i++){
a[i] = quickindex1(c[i], e, n);
cout << a[i] << " ";
}
cout << endl << "解密:";
for (int j = 0; a[j] != '\0'; j++){
b[j] = quickindex1(a[j], d, n);
cout << b[j] << " ";
}
cout << endl;
printf("\n");
system("pause");
return 0;
}
![测试1:](https://img-blog.csdn.net/20150613140853240)