Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #define MAX 512
- char offset(int c, int n)
- {
- int isUpper = 0, off, sign = 1, rez ;
- if (c >= 65 && c <= 90) { isUpper = 1; c += 32; }
- if (n < 0) sign = -1;
- if (n*sign >= 65 && n*sign <= 90) n += sign * 32;
- rez = c;
- off = n % 97;
- rez += off;
- if (rez < 97) rez = 123 + off + (c - 97);
- if (rez > 122) rez = 96 + off - (122 - c);
- if (isUpper) rez -= 32;
- return rez;
- }
- char * encrypt(char *m, char *key)
- {
- int i, j;
- char *cip;
- int mlen = strlen(m), klen = strlen(key);
- cip = (char*) malloc(mlen * sizeof(char));
- for (i = 0, j = 0; i < mlen && j < klen; i++)
- {
- if (isalpha(m[i]))
- {
- cip[i] = offset(m[i], (int) key[j]);
- j++;
- }
- else cip[i] = m[i];
- }
- for (j = 0; i < mlen; i++)
- {
- if (isalpha(m[i]))
- {
- while (!isalpha(m[j])) j++;
- cip[i] = offset(m[i], (int) m[j]);
- j++;
- }
- else cip[i] = m[i];
- if (j > mlen) j = 0;
- }
- cip[i] = '\0';
- return cip;
- }
- char *decrypt(char *cip, char *key)
- {
- int i, j;
- char *m, *tkey;;
- int clen = strlen(cip), klen = strlen(key);
- m = (char*) malloc(clen * sizeof(char));
- tkey = (char*) malloc(klen * sizeof(char));
- for (i = 0, j = 0; i < clen && j < klen; i++)
- {
- if (isalpha(cip[i]))
- {
- m[i] = offset(cip[i], -1 * (int) key[j]);
- j++;
- }
- else m[i] = cip[i];
- }
- for (j = 0; i < clen; i++)
- {
- if (isalpha(cip[i]))
- {
- while (!isalpha(cip[j])) j++;
- m[i] = offset(cip[i], -1 * (int) m[j]);
- j++;
- }
- else m[i] = cip[i];
- if (j > clen) j = 0;
- }
- m[i] = '\0';
- return m;
- }
- void main()
- {
- int i, op;
- char *s[MAX], *c[MAX], *key[MAX];
- FILE *f;
- f = fopen("input.txt", "r");
- fgets(s, MAX, f);
- fclose(f);
- printf("input key: "); gets(key);
- printf("select option: encrypt (1), decrypt (2): "); scanf("%d", &op);
- if (op == 1) strcpy(c, encrypt(s, key));
- else if (op == 2) strcpy(c, decrypt(s, key));
- f = fopen("output.txt", "w");
- fprintf(f, "%s", c);
- fclose(f);
- }
Advertisement
Add Comment
Please, Sign In to add comment