Tuesday, 31 May 2016

C code to Encrypt & Decrypt Message using Transposition Cipher



C-code-to-encrypt-and-decrypt-a-message-using-Transposition-cipher
C-code-to-encrypt-and-decrypt-a-message-using-Transposition-cipher-2

C Program

  1. #include<stdio.h>
  2. #include<string.h>
  3. void cipher(int i,int c);
  4. int findMin();
  5. void makeArray(int,int);
  6. char arr[22][22],darr[22][22],emessage[111],retmessage[111],key[55];
  7. char temp[55],temp2[55];
  8. int k=0;
  9. int main() {
  10. char *message,*dmessage;
  11. int i,j,klen,emlen,flag=0;
  12. int r,c,index,min,rows;
  13. clrscr();
  14. printf("Enetr the key\n");
  15. fflush(stdin);
  16. gets(key);
  17. printf("\nEnter message to be ciphered\n");
  18. fflush(stdin);
  19. gets(message);
  20. strcpy(temp,key);
  21. klen=strlen(key);
  22. k=0;
  23. for (i=0; ;i++) {
  24. if(flag==1)
  25. break;
  26. for (j=0;key[j]!=NULL;j++) {
  27. if(message[k]==NULL) {
  28. flag=1;
  29. arr[i][j]='-';
  30. } else {
  31. arr[i][j]=message[k++];
  32. }
  33. }
  34. }
  35. r=i;
  36. c=j;
  37. for (i=0;i<r;i++) {
  38. for (j=0;j<c;j++) {
  39. printf("%c ",arr[i][j]);
  40. }
  41. printf("\n");
  42. }
  43. k=0;
  44. for (i=0;i<klen;i++) {
  45. index=findMin();
  46. cipher(index,r);
  47. }
  48. emessage[k]='\0';
  49. printf("\nEncrypted message is\n");
  50. for (i=0;emessage[i]!=NULL;i++)
  51. printf("%c",emessage[i]);
  52. printf("\n\n");
  53. //deciphering
  54. emlen=strlen(emessage);
  55. //emlen is length of encrypted message
  56. strcpy(temp,key);
  57. rows=emlen/klen;
  58. //rows is no of row of the array to made from ciphered message
  59. rows;
  60. j=0;
  61. for (i=0,k=1;emessage[i]!=NULL;i++,k++) {
  62. //printf("\nEmlen=%d",emlen);
  63. temp2[j++]=emessage[i];
  64. if((k%rows)==0) {
  65. temp2[j]='\0';
  66. index=findMin();
  67. makeArray(index,rows);
  68. j=0;
  69. }
  70. }
  71. printf("\nArray Retrieved is\n");
  72. k=0;
  73. for (i=0;i<r;i++) {
  74. for (j=0;j<c;j++) {
  75. printf("%c ",darr[i][j]);
  76. //retrieving message
  77. retmessage[k++]=darr[i][j];
  78. }
  79. printf("\n");
  80. }
  81. retmessage[k]='\0';
  82. printf("\nMessage retrieved is\n");
  83. for (i=0;retmessage[i]!=NULL;i++)
  84. printf("%c",retmessage[i]);
  85. getch();
  86. return(0);
  87. }
  88. void cipher(int i,int r) {
  89. int j;
  90. for (j=0;j<r;j++) { {
  91. emessage[k++]=arr[j][i];
  92. }
  93. }
  94. // emessage[k]='\0';
  95. }
  96. void makeArray(int col,int row) {
  97. int i,j;
  98. for (i=0;i<row;i++) {
  99. darr[i][col]=temp2[i];
  100. }
  101. }
  102. int findMin() {
  103. int i,j,min,index;
  104. min=temp[0];
  105. index=0;
  106. for (j=0;temp[j]!=NULL;j++) {
  107. if(temp[j]<min) {
  108. min=temp[j];
  109. index=j;
  110. }
  111. }
  112. temp[index]=123;
  113. return(index);
  114. }