/* Author: Pate Williams (c) 1997 Exercise 1.7 "We describe a special case of a Permutation Cipher. Let m, n be positive integers. Write out the plain text, by rows in m by n rectangles. Then form the ciphertext by taking columns of these retangles. For example if m = 4, n = 3, then we would encrypt the plaintext "cryptography" by forming the following rectangle: cryp togr aphy The ciphertext would be "CTAROPYGHPRY". (a) Describe how Bob would decrypt a ciphertext (given values for m and n). (b) Decrypt the following ciphertext, which was obtained by using this method of encryption: MYAMRARUYIQTENCTORAHROYWDSOYEOUARRGDERNOGW" -Douglas R. Stinson- See "Cryptography: Theory and Practice" by Douglas R. Stinson page 42. */ #include #include #include int main(void) { char cipher[2][24] = {"MYAMRARUYIQTENCTORAH", "ROYWDSOYEOUARRGDERNOGW"}; char answer[256], ciphertext[50], grid[50][50]; char test_ciphertext[16] = "CTAROPYGHPRY"; char plain[2][24] = {"MARYMARYQUITECONTRARY", "HOWDOESYOURGARDENGROW"}; char plaintext[50]; int found = 0; long count = 0, i, j, k = 0, m = 4, n = 3; for (j = 0; j < m; j++) for (i = 0; i < n; i++) grid[i][j] = test_ciphertext[k++]; for (i = 0; i < n; i++) for (j = 0; j < m; j++) printf("%c", grid[i][j]); printf("\n"); for (i = 0; i < 2; i++) for (j = 0; j < strlen(cipher[i]); j++) ciphertext[count++] = cipher[i][j]; printf("count = %ld\n", count); for (n = 2; !found && n < count; n++) { if (count % n == 0) { k = 0; m = count / n; for (j = 0; j < m; j++) for (i = 0; i < n; i++) grid[i][j] = ciphertext[k++]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) printf("%c", grid[i][j]); printf("\n"); } for (i = 0; i < n; i++) for (j = 0; j < m; j++) printf("%c", grid[i][j]); printf("\n"); printf("another value of n = %ld (n or y)? ", n); scanf("%s", answer); found = tolower(answer[0] == 'n'); } } count = 0; for (i = 0; i < 2; i++) for (j = 0; j < strlen(plain[i]); j++) plaintext[count++] = plain[i][j]; found = 0; for (n = 2; !found && n < count; n++) { if (count % n == 0) { k = 0; m = count / n; for (i = 0; i < n; i++) for (j = 0; j < m; j++) grid[i][j] = plaintext[k++]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) printf("%c", grid[i][j]); printf("\n"); } for (j = 0; j < m; j++) for (i = 0; i < n; i++) printf("%c", grid[i][j]); printf("\n"); printf("next value of n = %ld (n or y)? ", n); scanf("%s", answer); found = tolower(answer[0]) == 'n'; } } return 0; }