Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <gmp.h>
- mpz_t p, q;
- mpz_t n, eiler;
- mpz_t e, d;
- mpz_t k;
- /*mpz_class power(mpz_class t, mpz_class k)
- {
- // возведение t в степень k
- mpz_class res = 1;
- while (k != 0) {
- if (k & 1) res *= t;
- t *= t;
- k >>= 1;
- }
- return res;
- }*/
- void generateKeys(mpz_t np, mpz_t nq, mpz_t ne, mpz_t k)
- {
- mpz_t temp1, temp2, one;
- mpz_set(p, np);
- mpz_set(q, nq);
- mpz_init(temp1);
- mpz_init(temp2);
- mpz_init(one);
- mpz_set_ui(one, 1);
- mpz_sub(temp1, p, one);
- mpz_sub(temp2, q, one);
- mpz_mul(n, p, q);
- mpz_mul(eiler, temp1, temp2);
- mpz_set(e, ne);
- mpz_mul(temp1, k, eiler);
- mpz_add(temp1, one, temp1);
- mpz_cdiv_q(d, temp1, e);
- mpz_clear(temp1);
- mpz_clear(temp2);
- mpz_clear(one);
- }
- void Pa(mpz_t result, int m)
- {
- //gmp_printf("enc: %d %d %d %d\n", m, e, power(m, e), n);
- mpz_t temp;
- mpz_init_set_si(temp, m);
- mpz_powm (result, temp, e, n);
- mpz_clear(temp);
- //return power(m, e) % n;
- }
- void Sa(mpz_t result, mpz_t c)
- {
- //gmp_printf("dec: %d %d %d %d\n", c, d, power(c, d), n);
- //return power(c, d) % n;
- mpz_powm (result, c, d, n);
- }
- int main(int argc, char *argv[])
- {
- if(argc<6)
- {
- gmp_printf("Usage: rsa_console p q e k \"text\"\n");
- }
- else
- {
- mpz_t result;
- mpz_init(p);
- mpz_init(q);
- mpz_init(n);
- mpz_init(eiler);
- mpz_init(e);
- mpz_init(d);
- mpz_init(k);
- mpz_init(result);
- mpz_set_str(p, argv[1], 10);
- mpz_set_str(q, argv[2], 10);
- mpz_set_str(e, argv[3], 10);
- mpz_set_str(k, argv[4], 10);
- gmp_printf("\np=%s, q=%s, e=%s, k=%s", argv[1], argv[2], argv[3], argv[4]);
- gmp_printf("\np=%d, q=%d, e=%d, k=%d\n\n", p, q, e, k);
- gmp_printf("Generating keys...\n\n");
- generateKeys(p, q, e, k);
- gmp_printf("n=%d, d=%d, e=%d\n\n", n, d, e);
- gmp_printf("Public Key: (%d, %d)\n", e, n);
- gmp_printf("Private Key: (%d, %d)\n", d, n);
- Pa(result, 111111);
- gmp_printf("%d\n", result);
- Sa(result, result);
- gmp_printf("%d\n", result);
- char * text = new char[strlen(argv[5])];
- mpz_t * encoded = new mpz_t[strlen(argv[5])];
- char * decoded = new char[strlen(argv[5])];
- strcpy(text, argv[5]);
- gmp_printf("Original text:\n");
- gmp_printf("%s\n\n", text);
- gmp_printf("Encoded text:\n");
- for(int i=0;i<strlen(text);i++)
- {
- Pa(result, text[i]);
- mpz_set(encoded[i], result);
- }
- gmp_printf("\n\n");
- for(int i=0;i<strlen(text);i++)
- {
- Sa(result, encoded[i]);
- decoded[i] = mpz_get_ui(result);
- }
- gmp_printf("Decoded text:\n");
- gmp_printf("%s\n", decoded);
- delete[] text;
- delete[] encoded;
- delete[] decoded;
- mpz_clear(p);
- mpz_clear(q);
- mpz_clear(n);
- mpz_clear(eiler);
- mpz_clear(e);
- mpz_clear(d);
- mpz_clear(k);
- mpz_clear(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement