写一个简单的linux文本io加密/解密代码
时间: 2024-01-12 19:05:44 浏览: 75
文本加密解密源代码.txt
以下是一个简单的Linux文本IO加密/解密代码的示例,使用了XOR算法:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
void xor_encrypt(char *data, int data_len, const char *key, int key_len) {
int i;
for(i = 0; i < data_len; i++) {
data[i] = data[i] ^ key[i % key_len];
}
}
void xor_decrypt(char *data, int data_len, const char *key, int key_len) {
int i;
for(i = 0; i < data_len; i++) {
data[i] = data[i] ^ key[i % key_len];
}
}
void encrypt_file(const char *in_filename, const char *out_filename, const char *key) {
char buffer[BUFFER_SIZE];
int bytes_read, bytes_written;
FILE *in_file = fopen(in_filename, "r");
FILE *out_file = fopen(out_filename, "w");
// Encrypt file
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, in_file)) > 0) {
xor_encrypt(buffer, bytes_read, key, strlen(key));
bytes_written = fwrite(buffer, 1, bytes_read, out_file);
}
fclose(in_file);
fclose(out_file);
}
void decrypt_file(const char *in_filename, const char *out_filename, const char *key) {
char buffer[BUFFER_SIZE];
int bytes_read, bytes_written;
FILE *in_file = fopen(in_filename, "r");
FILE *out_file = fopen(out_filename, "w");
// Decrypt file
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, in_file)) > 0) {
xor_decrypt(buffer, bytes_read, key, strlen(key));
bytes_written = fwrite(buffer, 1, bytes_read, out_file);
}
fclose(in_file);
fclose(out_file);
}
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s <input file> <output file> <key>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *in_filename = argv[1];
const char *out_filename = argv[2];
const char *key = argv[3];
encrypt_file(in_filename, "encrypted.tmp", key);
decrypt_file("encrypted.tmp", out_filename, key);
remove("encrypted.tmp");
printf("File %s encrypted and decrypted successfully.\n", in_filename);
return 0;
}
```
这个例子中,我们使用了XOR算法来加密和解密文件。我们实现了两个函数`xor_encrypt`和`xor_decrypt`用于加密和解密数据,另外我们实现了`encrypt_file`和`decrypt_file`函数来加密和解密文件。我们还实现了一个简单的命令行接口,可以通过传递输入文件、输出文件和密钥来使用这些函数加密和解密文件。
阅读全文