以下是一个简单的Linux文本IO加密/解密代码的示例,使用了openssl库中的AES算法:
```c
#include <openssl/aes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KEY_SIZE 256
#define BLOCK_SIZE 16
void encrypt_file(const char *in_filename, const char *out_filename, const char *key_str) {
unsigned char key[KEY_SIZE/8];
AES_KEY aes_key;
int bytes_read, bytes_written;
unsigned char in_data[BLOCK_SIZE];
unsigned char out_data[BLOCK_SIZE];
FILE *in_file = fopen(in_filename, "rb");
FILE *out_file = fopen(out_filename, "wb");
// Convert key string to binary
memset(key, 0, sizeof(key));
memcpy(key, key_str, strlen(key_str));
// Set encryption key
AES_set_encrypt_key(key, KEY_SIZE, &aes_key);
// Encrypt file
while ((bytes_read = fread(in_data, 1, BLOCK_SIZE, in_file)) > 0) {
AES_encrypt(in_data, out_data, &aes_key);
bytes_written = fwrite(out_data, 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_str) {
unsigned char key[KEY_SIZE/8];
AES_KEY aes_key;
int bytes_read, bytes_written;
unsigned char in_data[BLOCK_SIZE];
unsigned char out_data[BLOCK_SIZE];
FILE *in_file = fopen(in_filename, "rb");
FILE *out_file = fopen(out_filename, "wb");
// Convert key string to binary
memset(key, 0, sizeof(key));
memcpy(key, key_str, strlen(key_str));
// Set decryption key
AES_set_decrypt_key(key, KEY_SIZE, &aes_key);
// Decrypt file
while ((bytes_read = fread(in_data, 1, BLOCK_SIZE, in_file)) > 0) {
AES_decrypt(in_data, out_data, &aes_key);
bytes_written = fwrite(out_data, 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_str = argv[3];
encrypt_file(in_filename, "encrypted.tmp", key_str);
decrypt_file("encrypted.tmp", out_filename, key_str);
remove("encrypted.tmp");
printf("File %s encrypted and decrypted successfully.\n", in_filename);
return 0;
}
```
这个例子中,我们使用了256位的AES算法,并将加密和解密操作封装到`encrypt_file`和`decrypt_file`函数中。我们还实现了一个简单的命令行接口,可以通过传递输入文件、输出文件和密钥来使用这些函数加密和解密文件。