⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lab1_solution.c

📁 Tasks Read the textbook about the details of Vigenére Cipher. Implement the algorithm by C or C++.
💻 C
字号:
/*  Computer Security
    lab1  ---  Explore Vigenere Cipher

    File name : lab1_solution.c
    Writen by : Jie Hu
    Date      : August 14, 2004
*/

#include<stdio.h>
#include<string.h>
#include<math.h>

#define MAX_LEN 1024       /* Maximal number of letters to analyse */
#define LETTERS 26         /* Number of letters in the English alphabet */

/* ---  encrypt_vigenere  ---
  Encrypts a plain test string, using the periodic substitution cipher
  Vigene`re.
  Pre  plain text, key
  Post cipher text
*/

void encrypt_vigenere(char* plain, char* key, char* cipher)
{
  int max = strlen(plain)-1,
      d = strlen(key)-1,
      i;

  for(i=0;i<max;i++)
    cipher[i] = 'a'+(plain[i] -'a' + key[i % d] - 'a'+ LETTERS) % LETTERS;
  //adding LETTERS to avoid the result is negative
  cipher[i] = '\0';
}


/* ---  decrypt_vigenere  ---
  Decrypts a cipher text string, using the periodic substitution cipher
  Vigene`re.
  Pre  Cipher text, key
  Post Plain text
*/

void decrypt_vigenere(char* cipher, char* key, char* plain)
{
  int max = strlen(cipher),
      d = strlen(key)-1,
      i;

  for(i=0;i<max;i++)
    plain[i] ='a'+(cipher[i]-'a'-(key[i % d] - 'a')+LETTERS) % LETTERS;

  plain[i] = '\0';
}


main() {
  char cipher[MAX_LEN],key[MAX_LEN],plain[MAX_LEN];

  printf("--> Please input the key: \n");
  fgets(key,sizeof(key),stdin);         /* Get key from stdin */

  printf("\n--> Please input the plain text: \n");
  fgets(plain,sizeof(plain),stdin);     /* Get plain text from stdin */

  encrypt_vigenere(plain,key,cipher);   /* Encrypt text */
  printf("\n--> The cipher text is : \n");
  printf("%s\n",cipher);

  decrypt_vigenere(cipher, key, plain); /* Decrypt the cipher*/
  printf("\n-->The original message is: \n");
  printf("%s\n",plain);

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -