HuyPV
Saturday, September 11, 2010
#include <stdio.h>
#include <stdlib.h>
int modulo(int a, int m); /* return a mod m */
int char2int(char c); /* returns ASCII value of c-65 */
char int2char(int a); /* returns ASCII character of a+65 */
long fastexp(int a,int p, int n); /* returns a^p mod n */
long inver(int a, int n); /* returns b: a*b mod n = 1 */
int modulo(int a, int m) {
return (a % m);
}
int char2int(char c) {
return (c - 65);
}
char int2char(int a) {
return (char)(a + 65);
}
long fastexp(int a, int p, int n) {
long x = 1;
while (p != 0) {
while (p % 2 == 0) {
p = p / 2;
a = ((a % n) * (a % n)) % n;
}
p -= 1;
x = ((x % n) * (a % n)) % n;
}
return x;
}
long inver(int a, int n) {
long g[255], u[255], v[255];
long y, i, x;
g[0] = n;
g[1] = a;
u[0] = 1;
u[1] = 0;
v[0] = 0;
v[1] = 1;
i = 1;
while (g[i] != 0) {
y = g[i-1] / g[i];
g[i+1] = g[i-1] - y * g[i];
u[i+1] = u[i-1] - y * u[i];
v[i+1] = v[i-1] - y * v[i];
i++;
}
x = v[i-1];
return ((x >= 0) ? x : (x + n));
}
char *encryptCaesar(char *x, int key, char *y) {
char STR[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, c, d, num;
for (i = 0; i < strlen(x); i++) {
c = x[i];
c = toupper(c);
num = c - 'A';
d = (num + key) % 26;
y[i] = STR[d];
}
y[i] = 0;
return y;
}
char *decryptCaesar(char *y, int key, char *x) {
char STR[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, c, d, num;
for (i = 0; i < strlen(y); i++) {
c = y[i];
c = toupper(c);
num = c - 'A';
if (num - key < 0)
d = 26 - (key - num) % 26;
else
d = (num - key) % 26;
x[i] = STR[d];
}
x[i] = 0;
return x;
}
long decryptRSA(int p, int q, int b, int y) {
// int p = 97, q = 103, b = 1001;
int n = p * q; // public
int phin = (p - 1) * (q - 1); //private
long a = inver(b, phin); // xac dinh duoc khi biet b
// y - ban ma nhan duoc
long x = fastexp(y, a, n);
return x;
}
long encryptRSA(int p, int q, int b, int x) {
int n = p * q; // public
long y = fastexp(x, b, n);
return y;
}
int main() {
/*
printf("%d", fastexp(87, 43, 103));
printf("%d", inver(7, 100));
*/
// De-Encrypt Caesar Example
int key = 3;
printf("Cau 1:\r\n");
char x[] = "ATTACKATDAWN";
char y[1024];
encryptCaesar(x, 3, y);
printf("%s\r\n", y);
printf("Cau 2:\r\n");
char y1[] = "XULTPAAJCXITLTLXAARPJHTIWTGXKTGHIDHIPXCIWTVGTPILPITGHLXIWIWTXGQADDS";
char x1[1024];
int keytry = 0;
for (keytry = 0; keytry < 26; keytry++) {
decryptCaesar(y1, keytry, x1);
printf("[%d]:\t%s\r\n", keytry, x1);
}
// De-Encrypt RSA Example
printf("Cau 3:\r\n");
long y2 = 2709;
long x2 = decryptRSA(97, 101, 1003, y2);
printf("%d", x2);
/*
y2 = encryptRSA(97, 101, 1003, x2);
printf("%d", y2);
*/
getch();
return 1;
}
Title:
Remind C Code Example
Description:
#include <stdio.h> #include <stdlib.h> int modulo(int a, int m); /* return a mod m */ int char2int(char c); ...
...
Rating:
4