當前位置:編程學習大全網 - 源碼下載 - 用C語言實現任意字符串的加密,其中,字母用凱撒加密方法加密,非字母不變

用C語言實現任意字符串的加密,其中,字母用凱撒加密方法加密,非字母不變

我盡量用註釋闡述了思路,希望可以幫到妳!!

#include<stdio.h>

#include<string.h>

#define N 80 //可加密字符串最大長度

char plaintext[N]={0}; //明文,輸入時輸入字符,參與運算時強制轉換成整數

int ciphertext[N]={0}; //密文,保存成整數,輸出時強制轉換成字符

int k; //後(右)移位數,相當於密鑰

void getPlainText() //獲得明文字符串

{

printf("請輸入明文:");

scanf("%s",plaintext);

printf("\n");

}

void getLength() //獲取後(右)移位數(密鑰)

{

printf("請輸入後移的位數:");

scanf("%d",&k);

k%=26; //因為字母只有26個,所以超過26相當於重復

}

void Caesar_cipher() //凱撒加密,本程序采用的是字母循環後(右)移

{

unsigned int i;

for(i=0;i<strlen(plaintext);i++)

{

//兩個bool類型的變量是為了判斷字符是否是字母(包括大寫和小寫)

bool flag1=plaintext[i]>='a'&&plaintext[i]<='z';

bool flag2=plaintext[i]>='A'&&plaintext[i]<='Z';

if(flag1||flag2){ //如果是字母,加密

ciphertext[i]=(int)plaintext[i]+k; //字母在字母表中後(右)移K位

if(ciphertext[i]>(int)'z'){ //保證是循環後(右)移

ciphertext[i]-=26;

}

}

else //非字母字符,不做處理,原樣保存

ciphertext[i]=(int)plaintext[i];

}

}

void printCipherText() //輸出加密後的密文

{

unsigned int i;

printf("\n加密後的密文是:");

for(i=0;i<strlen(plaintext);i++) //把參與計算後是整數強制轉換成對應的字符

printf("%c",(char)ciphertext[i]);

printf("\n");

}

void main()

{

getPlainText(); //明文

getLength(); //後(右)移位數

Caesar_cipher(); //凱撒加密

printCipherText(); //密文

}

  • 上一篇:推送方法的源代碼
  • 下一篇:中國農業銀行的信用卡如何可靠?
  • copyright 2024編程學習大全網