1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include<stdio.h> #include<math.h> #include<stdlib.h> #include"rsa.h"
int64_t p; int64_t q; int64_t d;
int64_t n; int64_t e = 65537;
int64_t gcd(int64_t a, int64_t b) { if(b == 0)return a; else return gcd(b, a % b); }
int64_t e_gcd(int64_t a, int64_t b, int64_t* x, int64_t* y) { if(b == 0) { *x = 1; *y = 0; return a; } int64_t x1, y1; int64_t gcd = e_gcd(b, a % b, &x1, &y1); *x = y1; *y = x1 - (a / b) * y1; return gcd; }
int64_t inv1(int64_t a, int64_t m) { int64_t x0, y0, xs, b; int64_t gcd = e_gcd(a, m, &x0, &y0); if(gcd != 1)return -1; if(x0 < 0) { xs = x0 % m; b = xs + m; } else { b = x0 % m; } return b; }
int64_t pow_mod(int64_t b, int64_t exp, int64_t m) { if(exp == 0)return 1; if(exp % 2 == 1) { return (pow_mod(b, exp - 1, m) * b) % m; } else { int64_t tmp = pow_mod(b, exp / 2, m); return (tmp * tmp) % m; } }
void cal_key_pair() { n = p * q; int64_t Fn = (p - 1) * (q - 1);
d = inv1(e, Fn); if(d == -1) { printf("e, Fn have gcd != 1!\n"); exit(0); } }
void rsa_encrypt(int64_t M, int64_t e, int64_t n, int64_t* C) { *C = pow_mod(M, e, n); }
void rsa_decrypt(int64_t C, int64_t d, int64_t n, int64_t* M) { *M = pow_mod(C, d, n); }
|