本篇內容主要講解“如何用C語言實現凱撒密碼加密解密”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何用C語言實現凱撒密碼加密解密”吧!
網站建設、做網站介紹好的網站是理念、設計和技術的結合。成都創新互聯公司擁有的網站設計理念、多方位的設計風格、經驗豐富的設計團隊。提供PC端+手機端網站建設,用營銷思維進行網站設計、采用先進技術開源代碼、注重用戶體驗與SEO基礎,將技術與創意整合到網站之中,以契合客戶的方式做到創意性的視覺化效果。
又叫循環移位密碼.它的加密方法是將明文中的每個字母用此字符在字母表中后面第k個字母替代.它的加密過程可以表示為下面的函數:E(m)=m+k(mod n)
其中:m為明文字母在字母表中的位置數;n為字母表中的字母個數;k為密鑰;E(m)為密文字母在字母表中對應的位置數.
#include#include //加密 int encrypt(char* plaintext, char* ciphertext, int k) { int i, z = 0; int l = strlen(plaintext); //獲取明文的長度 for (i = 0; i < l; i++) { //判斷大小寫 if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') { ciphertext[z] = ( (plaintext[i] - 'A') + k) % 26 + 'A'; } else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') { ciphertext[z] = ((plaintext[i] - 'a') + k) % 26 + 'a'; } else { //判斷是否是空格 ciphertext[z] = plaintext[i]; } z++; } return 0; } //解密 int decrypt(char* plaintext, char* ciphertext, int k) { int i, z = 0; int l = strlen(plaintext); //獲取明文的長度 for (i = 0; i < l; i++) { //判斷大小寫 if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') { ciphertext[z] = (((plaintext[i] - 'A') - k)) % 26 + 'A'; if (((plaintext[i] - 'A') - k) < 0) { ciphertext[z] = ciphertext[z] + 26; } } else if (plaintext[i] >= 'a' && plaintext[i] <= 'z') { ciphertext[z] = ( ((plaintext[i] - 'a') - k)) % 26 + 'a'; if (((plaintext[i] - 'a') - k) < 0) { //處理負數 ciphertext[z] = ciphertext[z] + 26; } } else { //判斷是否是空格 ciphertext[z] = plaintext[i]; } z++; } return 0; } int main() { char plaintext[50] = ""; char ciphertext[50] = ""; int k; int type; printf("請填寫明文或者密文:\n"); scanf("%s", plaintext); printf("請選擇加密方式,輸入1加密,輸入2解密\n"); scanf("%d", &type); if (type == 1) { //加密 printf("請輸入密鑰k:\n"); scanf("%d", &k); encrypt(plaintext, ciphertext, k); printf("明文%s的密文為:%s\n", plaintext, ciphertext); } else if (type == 2) { //解密 printf("請輸入密鑰k:\n"); scanf("%d", &k); decrypt(plaintext, ciphertext, k); printf("密文%s的明文為:%s\n", plaintext, ciphertext); } return 0; }
運行結果:
到此,相信大家對“如何用C語言實現凱撒密碼加密解密”有了更深的了解,不妨來實際操作一番吧!這里是創新互聯網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!