文件加解密程序怎么写

时间:2025-01-28 23:00:31 单机游戏

编写文件加解密程序可以通过多种方法实现,包括使用自定义算法、第三方库等。下面我将提供两种常见的实现方法:

方法一:使用自定义算法

加密和解密函数

加密时,将每个字符的ASCII码加上一个密钥值,如果结果超过ASCII码表的限制,则进行模运算。

解密时,将每个字符的ASCII码减去密钥值,如果结果小于0,则加上ASCII码表的最大值。

```c

include

define KEY 49632873

void encrypt_char(char *ch, int key) {

*ch = (*ch + key) % 123; // ASCII码表范围是0-122

}

void decrypt_char(char *ch, int key) {

*ch = (*ch - key + 123) % 123; // 确保结果非负

}

void encrypt_file(const char *input_file, const char *output_file) {

FILE *fin = fopen(input_file, "rb");

FILE *fout = fopen(output_file, "wb");

if (fin == NULL || fout == NULL) {

perror("Error opening file");

return;

}

char ch;

while ((ch = fgetc(fin)) != EOF) {

encrypt_char(&ch, KEY);

fputc(ch, fout);

}

fclose(fin);

fclose(fout);

}

void decrypt_file(const char *input_file, const char *output_file) {

FILE *fin = fopen(input_file, "rb");

FILE *fout = fopen(output_file, "wb");

if (fin == NULL || fout == NULL) {

perror("Error opening file");

return;

}

char ch;

while ((ch = fgetc(fin)) != EOF) {

decrypt_char(&ch, KEY);

fputc(ch, fout);

}

fclose(fin);

fclose(fout);

}

int main() {

const char *input_file = "example.txt";

const char *output_file = "encrypted_example.txt";

encrypt_file(input_file, output_file);

printf("Encryption complete.\n");

const char *decrypted_file = "decrypted_example.txt";

decrypt_file(output_file, decrypted_file);

printf("Decryption complete.\n");

return 0;

}

```

方法二:使用OpenSSL库

OpenSSL是一个强大的加密库,支持多种加密算法。以下是使用OpenSSL库进行AES加密和解密的示例:

生成密钥

```python

from cryptography.fernet import Fernet

key = Fernet.generate_key()

with open("secret.key", "wb") as key_file:

key_file.write(key)

print("密钥已生成并保存为 secret.key 文件。")

```

加密文件

```python

from cryptography.fernet import Fernet

def encrypt_file(filename):

with open("secret.key", "rb") as key_file:

key = key_file.read()

f = Fernet(key)

with open(filename, "rb") as file:

file_data = file.read()

encrypted_data = f.encrypt(file_data)

with open(f"encrypted_{filename}", "wb") as encrypted_file:

encrypted_file.write(encrypted_data)

```

解密文件

```python

from cryptography.fernet import Fernet

def decrypt_file(filename):

with open("secret.key", "rb") as key_file:

key = key_file.read()

f = Fernet(key)

with open(filename, "rb") as encrypted_file:

encrypted_data = encrypted_file.read()

decrypted_data = f.decrypt(encrypted_data)

with open(f"decrypted_{filename}", "wb") as decrypted_file:

decrypted_file.write(decrypted_data)

```