c語(yǔ)言怎么進(jìn)行加密解密
2026-05-04 19:02:41 點(diǎn)擊:796
C語(yǔ)言進(jìn)行加密解密的語(yǔ)言進(jìn)方法有很多,這里我將介紹兩種常見(jiàn)的行加??加密解密方法:凱撒密碼和異或加密。
(圖片來(lái)源網(wǎng)絡(luò ),密解密侵刪)1、語(yǔ)言進(jìn)凱撒密碼
凱撒密碼是行加一種簡(jiǎn)單的替換加密方法,它將明文中的ヽ(′▽?zhuān)?ノ密解密每個(gè)字符按照一個(gè)固定的偏移量進(jìn)行替換,當偏移量為3時(shí),語(yǔ)言進(jìn)(jin)明文"A??BC"將被替換為&(′?`*)quot;DEF"。行加
下面是密解密一個(gè)簡(jiǎn)單的C語(yǔ)言實(shí)現凱撒密碼加密解密的示例:
#include <stdio.h>#include <string.h>void caesar_encrypt(char *plaintext, int shift) { int len = strlen(plaintext); for (int i = 0; i < len; i++) { char c = pla??intext[i]; if (c >= 'A' && c <= 'Z') { plaintext[i] = (c 'A' + shift) % 26 + 'A'; } else if (c >= 'a' && c <= 'z') { plaintext[i] = (c 'a' + shift) % 26 + 'a'??; } }}void caesar_decrypt(char *ciphertext??, int shift) { int len = strl(?⊿?)en(′?`)(cip??hertext); for (int i = 0; i < len; i++) { char c = ciphertext[i]; if (c >= 'A' && c <= 'Z') { ciphertext[i] = (c 'A' shift + 26) % 26 + 'A'; } else if (c >= 'a' && c <= 'z'(???)) { ciphertext[i] = (c 'a' shift + 26) % 26 + 'a'; } }}int main() { char plaintext[] = "Hello, World!"; printf("┐(′?`)┌;Plaintext: %s", plaintext); caesar_encrypt(plaintext, 3); printf("Ciphertext: %s", plaintext); caesar_decrypt(plaintext, 3); printf("Decrypted text: %s", plaintext); return 0;}2、異或加密
異或加密是語(yǔ)言進(jìn)一種基于異或運算的簡(jiǎn)單加密方法,它將明文中的行加每個(gè)字符與一個(gè)密鑰進(jìn)行異或運算,得到密文,密解密由于異或運算具有可逆性,語(yǔ)言進(jìn)因此可以通過(guò)再次進(jìn)行異或運算來(lái)恢復原始明文。行加
下面是密解密一個(gè)簡(jiǎn)單的C語(yǔ)言實(shí)現異或加密解密的示例:
#include <stdio.h>#include <string.h>void xor_encrypt(cha??r *plaintext, char *key, char *ciphertext) { int len = strlen(plaintext); for (int i = 0; i < len; i++) { ciphertext[i??] = plaintext[i] ^ key[i % strlen(key)]; }}void xor_decrypt(char *ciphertext,?? char *key, char *decrypted) { int len = strlen(ciphertext); for (int i = 0; i < len; i++) { decrypted[i] = cip(′-ι_-`)h??(′?`)ertext[i] ^ key[i % strlen(key)]; }}int main() { char plaintext[] = "Hello, World!"; char key[] = "SecretKey"; char ciphertext[strlen(plaintext) + 1]; char decrypted[str??len(plaintext)?? + 1]; me??mset(ciphertext, 0, sizeof(ciphertext)); memset(decrypted, 0, sizeof(decryヽ(′ー`)ノpted)); xor_encrypt(plaintext, key, ciphertext); printf("Ciphertext: %s", ciphertext); xor_decrypt(ciphertext, key, decrypted); printf("Decrypted text: %s", decrypted); return 0;}以上兩種方法都是非常簡(jiǎn)單的加密解密方法,僅適用于教學(xué)演示和簡(jiǎn)單的應(ying)用場(chǎng)景,在實(shí)際(ji)應用中,建議使??用更安全的加密算法,如AES、RSA等。





