现在有一个consolabin的文件用C语言写出一个基于base64的解码函数把consolabin解码输出保存在另外的文件中注意内存泄漏的问题不要跟上次一样出现munmap_chunk invalid pointer 已放弃 核心已转储
首先,我们需要读取consola.bin文件的内容并进行base64解码。可以使用base64库来完成解码过程。然后,将解码后的内容保存到另一个文件中。
以下是一个可能的实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#define CHUNK_SIZE 4096
int main() {
int fd_in, fd_out;
char *buf_in, *buf_out;
off_t size_in, size_out;
int ret = 0;
// 打开输入文件
fd_in = open("consola.bin", O_RDONLY);
if (fd_in < 0) {
perror("open input file");
return 1;
}
// 获取输入文件大小
size_in = lseek(fd_in, 0, SEEK_END);
if (size_in < 0) {
perror("lseek input file");
ret = 1;
goto cleanup_fd_in;
}
// 映射输入文件到内存
buf_in = mmap(NULL, size_in, PROT_READ, MAP_PRIVATE, fd_in, 0);
if (buf_in == MAP_FAILED) {
perror("mmap input file");
ret = 1;
goto cleanup_fd_in;
}
// 创建输出文件
fd_out = open("decrypted.bin", O_WRONLY|O_CREAT|O_TRUNC, 0644);
if (fd_out < 0) {
perror("open output file");
ret = 1;
goto cleanup_mmap_in;
}
// 创建base64解码器
BIO *b64, *bio_out;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio_out = BIO_new_fd(fd_out, BIO_NOCLOSE);
// 解码并写入输出文件
int len;
buf_out = malloc(CHUNK_SIZE);
while ((len = BIO_read(b64, buf_out, CHUNK_SIZE)) > 0) {
BIO_write(bio_out, buf_out, len);
}
// 关闭文件和解码器
BIO_free_all(b64);
BIO_free_all(bio_out);
free(buf_out);
close(fd_out);
cleanup_mmap_in:
munmap(buf_in, size_in);
cleanup_fd_in:
close(fd_in);
return ret;
}
在这个实现中,我们使用了mmap函数将输入文件映射到内存中,这样可以避免一次性读取整个文件,也可以避免内存泄漏。解码后的内容也是通过循环读取和写入的方式,避免了一次性分配过大的内存。解码器使用了OpenSSL库中的BIO接口实现,这是一种流式编程的方式,可以方便地将解码器和输出文件连接起来。
需要注意的是,这个实现中并没有对解码后的内容进行验证和处理,如果解码失败或者解码后的内容不是二进制文件,可能会导致程序崩溃或者输出错误的内容。在实际应用中,需要根据具体情况进行处理。
原文地址: https://www.cveoy.top/t/topic/boWD 著作权归作者所有。请勿转载和采集!